d7432ebfaf001eb09be2c4a6fc05f1e0b9fdac3d
[alexxy/gromacs.git] / src / gromacs / topology / symtab.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 /*! \internal \file
39  * \brief
40  * Implements new and legacy symbol table routines.
41  *
42  * \author David van der Spoel <david.vanderspoel@icm.uu.se>
43  * \author Paul Bauer <paul.bauer.q@gmail.com>
44  * \ingroup module_topology
45  */
46 #include "gmxpre.h"
47
48 #include "symtab.h"
49
50 #include <cstdio>
51 #include <cstring>
52
53 #include <algorithm>
54
55 #include "gromacs/utility/basedefinitions.h"
56 #include "gromacs/utility/cstringutil.h"
57 #include "gromacs/utility/exceptions.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/iserializer.h"
60 #include "gromacs/utility/smalloc.h"
61 #include "gromacs/utility/stringutil.h"
62 #include "gromacs/utility/txtdump.h"
63
64 StringTableEntry StringTableBuilder::addString(const std::string& theString)
65 {
66     int         size     = map_.size();
67     std::string stripped = gmx::stripString(theString);
68
69     const auto foundEntry = map_.insert(StringTablePair(stripped, size));
70     return StringTableEntry(foundEntry.first->first, foundEntry.first->second);
71 }
72
73 int StringTableBuilder::findEntryByName(const std::string& name) const
74 {
75     auto foundEntry = map_.find(name);
76     if (foundEntry != map_.end())
77     {
78         return foundEntry->second;
79     }
80     else
81     {
82         GMX_THROW(gmx::InternalError(
83                 gmx::formatString("Could not find string \"%s\" in SymbolTable", name.c_str())));
84     }
85 }
86
87 StringTable StringTableBuilder::build()
88 {
89     std::vector<std::string> table(map_.size());
90     for (const auto& entry : map_)
91     {
92         table[entry.second] = entry.first;
93     }
94     map_.clear();
95     return StringTable(table);
96 }
97
98 void StringTable::printStringTableStorageToFile(FILE* fp, int indent, const char* title) const
99 {
100     indent = pr_title_n(fp, indent, title, table_.size());
101     int i  = 0;
102     for (const auto& entry : table_)
103     {
104         pr_indent(fp, indent);
105         fprintf(fp, "%s[%d]=\"%s\"\n", title, i++, entry.c_str());
106     }
107 }
108
109 StringTable::StringTable(gmx::ISerializer* serializer)
110 {
111     GMX_RELEASE_ASSERT(serializer->reading(),
112                        "Can not use writing serializer to read string table");
113     int nr = 0;
114     serializer->doInt(&nr);
115     table_.resize(nr);
116     for (auto& entry : table_)
117     {
118         serializer->doString(&entry);
119     }
120 }
121
122 void StringTable::serializeStringTable(gmx::ISerializer* serializer)
123 {
124     GMX_RELEASE_ASSERT(!serializer->reading(),
125                        "Can not use reading serializer to write string table");
126     int nr = table_.size();
127     serializer->doInt(&nr);
128     for (auto& entry : table_)
129     {
130         serializer->doString(&entry);
131     }
132 }
133
134 StringTableEntry StringTable::at(gmx::index index) const
135 {
136     if (index >= gmx::ssize(table_))
137     {
138         GMX_THROW(gmx::InternalError("Can't read beyond last entry"));
139     }
140     return StringTableEntry(table_[index], index);
141 }
142
143 StringTableEntry StringTable::operator[](gmx::index index) const
144 {
145     GMX_ASSERT(index < gmx::ssize(table_), "Can't read beyond last entry");
146     return StringTableEntry(table_[index], index);
147 }
148
149 void StringTableEntry::serialize(gmx::ISerializer* serializer) const
150 {
151     GMX_RELEASE_ASSERT(!serializer->reading(),
152                        "Can not use reading serializer to write string index");
153     int entry = tableIndex_;
154     serializer->doInt(&entry);
155 }
156
157 StringTableEntry readStringTableEntry(gmx::ISerializer* serializer, const StringTable& table)
158 {
159     GMX_RELEASE_ASSERT(serializer->reading(),
160                        "Can not use writing serializer to read string index");
161     int entry = 0;
162     serializer->doInt(&entry);
163     return table.at(entry);
164 }
165
166 void StringTable::copyToLegacySymtab(struct t_symtab* symtab) const
167 {
168     for (const auto& entry : table_)
169     {
170         put_symtab(symtab, entry.c_str());
171     }
172 }
173
174 // Old code for legacy data structure starts below.
175 //! Maximum size of character string in table.
176 constexpr int c_trimSize = 1024;
177 //! Maximum number of entries in each element of the linked list.
178 constexpr int c_maxBufSize = 5;
179
180 /*! \brief
181  * Remove leading and trailing whitespace from string and enforce maximum length.
182  *
183  * \param[in]    s      String to trim.
184  * \param[inout] out    String to return.
185  * \param[in]    maxlen Maximum string length to use.
186  * \returns New pruned string.
187  */
188 static char* trim_string(const char* s, char* out, int maxlen)
189 {
190     int len, i;
191
192     if (strlen(s) > static_cast<size_t>(maxlen - 1))
193     {
194         gmx_fatal(FARGS, "String '%s' (%zu) is longer than buffer (%d).\n", s, strlen(s), maxlen - 1);
195     }
196
197     for (; (*s) == ' '; s++) {}
198     for (len = strlen(s); (len > 0); len--)
199     {
200         if (s[len - 1] != ' ')
201         {
202             break;
203         }
204     }
205     if (len >= c_trimSize)
206     {
207         len = c_trimSize - 1;
208     }
209     for (i = 0; i < len; i++)
210     {
211         out[i] = *(s++);
212     }
213     out[i] = 0;
214     return out;
215 }
216
217 int lookup_symtab(t_symtab* symtab, char** name)
218 {
219     int       base;
220     t_symbuf* symbuf;
221
222     base   = 0;
223     symbuf = symtab->symbuf;
224     while (symbuf != nullptr)
225     {
226         const int index = name - symbuf->buf;
227         if ((index >= 0) && (index < symbuf->bufsize))
228         {
229             return index + base;
230         }
231         else
232         {
233             base += symbuf->bufsize;
234             symbuf = symbuf->next;
235         }
236     }
237     gmx_fatal(FARGS, "symtab lookup \"%s\" not found", *name);
238 }
239
240 char** get_symtab_handle(t_symtab* symtab, int name)
241 {
242     t_symbuf* symbuf;
243
244     symbuf = symtab->symbuf;
245     while (symbuf != nullptr)
246     {
247         if (name < symbuf->bufsize)
248         {
249             return &(symbuf->buf[name]);
250         }
251         else
252         {
253             name -= symbuf->bufsize;
254             symbuf = symbuf->next;
255         }
256     }
257     gmx_fatal(FARGS, "symtab get_symtab_handle %d not found", name);
258 }
259
260 //! Returns a new initialized entry into the symtab linked list.
261 static t_symbuf* new_symbuf()
262 {
263     t_symbuf* symbuf;
264
265     snew(symbuf, 1);
266     symbuf->bufsize = c_maxBufSize;
267     snew(symbuf->buf, symbuf->bufsize);
268     symbuf->next = nullptr;
269
270     return symbuf;
271 }
272
273 /*! \brief
274  * Low level function to enter new string into legacy symtab.
275  *
276  * \param[inout] symtab Symbol table to add entry to.
277  * \param[in]    name   New string to add to symtab.
278  * \returns Pointer to new entry in the legacy symbol table, or to existing entry if it already existed.
279  */
280 static char** enter_buf(t_symtab* symtab, char* name)
281 {
282     int       i;
283     t_symbuf* symbuf;
284     gmx_bool  bCont;
285
286     if (symtab->symbuf == nullptr)
287     {
288         symtab->symbuf = new_symbuf();
289     }
290
291     symbuf = symtab->symbuf;
292     do
293     {
294         for (i = 0; (i < symbuf->bufsize); i++)
295         {
296             if (symbuf->buf[i] == nullptr)
297             {
298                 symtab->nr++;
299                 symbuf->buf[i] = gmx_strdup(name);
300                 return &(symbuf->buf[i]);
301             }
302             else if (strcmp(symbuf->buf[i], name) == 0)
303             {
304                 return &(symbuf->buf[i]);
305             }
306         }
307         if (symbuf->next != nullptr)
308         {
309             symbuf = symbuf->next;
310             bCont  = TRUE;
311         }
312         else
313         {
314             bCont = FALSE;
315         }
316     } while (bCont);
317
318     symbuf->next = new_symbuf();
319     symbuf       = symbuf->next;
320
321     symtab->nr++;
322     symbuf->buf[0] = gmx_strdup(name);
323     return &(symbuf->buf[0]);
324 }
325
326 char** put_symtab(t_symtab* symtab, const char* name)
327 {
328     char buf[1024];
329
330     return enter_buf(symtab, trim_string(name, buf, 1023));
331 }
332
333 void open_symtab(t_symtab* symtab)
334 {
335     symtab->nr     = 0;
336     symtab->symbuf = nullptr;
337 }
338
339 void close_symtab(t_symtab gmx_unused* symtab) {}
340
341 // TODO this will go away when we use a
342 // std::list<std::vector<std::string>>> for t_symtab.
343 t_symtab* duplicateSymtab(const t_symtab* symtab)
344 {
345     t_symtab* copySymtab;
346     snew(copySymtab, 1);
347     open_symtab(copySymtab);
348     t_symbuf* symbuf = symtab->symbuf;
349     if (symbuf != nullptr)
350     {
351         snew(copySymtab->symbuf, 1);
352     }
353     t_symbuf* copySymbuf = copySymtab->symbuf;
354     while (symbuf != nullptr)
355     {
356         snew(copySymbuf->buf, symbuf->bufsize);
357         copySymbuf->bufsize = symbuf->bufsize;
358         for (int i = 0; (i < symbuf->bufsize) && (i < symtab->nr); i++)
359         {
360             if (symbuf->buf[i])
361             {
362                 copySymbuf->buf[i] = gmx_strdup(symbuf->buf[i]);
363             }
364         }
365         symbuf = symbuf->next;
366         if (symbuf != nullptr)
367         {
368             snew(copySymbuf->next, 1);
369             copySymbuf = copySymbuf->next;
370         }
371     }
372     copySymtab->nr = symtab->nr;
373     return copySymtab;
374 }
375
376 void done_symtab(t_symtab* symtab)
377 {
378     int       i;
379     t_symbuf *symbuf, *freeptr;
380
381     close_symtab(symtab);
382     symbuf = symtab->symbuf;
383     while (symbuf != nullptr)
384     {
385         for (i = 0; (i < symbuf->bufsize) && (i < symtab->nr); i++)
386         {
387             sfree(symbuf->buf[i]);
388         }
389         symtab->nr -= i;
390         sfree(symbuf->buf);
391         freeptr = symbuf;
392         symbuf  = symbuf->next;
393         sfree(freeptr);
394     }
395     symtab->symbuf = nullptr;
396     if (symtab->nr != 0)
397     {
398         gmx_incons("Freeing symbol table (symtab) structure");
399     }
400 }
401
402 void free_symtab(t_symtab* symtab)
403 {
404     t_symbuf *symbuf, *freeptr;
405
406     close_symtab(symtab);
407     symbuf = symtab->symbuf;
408     while (symbuf != nullptr)
409     {
410         symtab->nr -= std::min(symbuf->bufsize, symtab->nr);
411         freeptr = symbuf;
412         symbuf  = symbuf->next;
413         sfree(freeptr);
414     }
415     symtab->symbuf = nullptr;
416     if (symtab->nr != 0)
417     {
418         gmx_incons("Freeing symbol table (symtab) structure");
419     }
420 }
421
422 void pr_symtab(FILE* fp, int indent, const char* title, t_symtab* symtab)
423 {
424     int       i, j, nr;
425     t_symbuf* symbuf;
426
427     if (available(fp, symtab, indent, title))
428     {
429         indent = pr_title_n(fp, indent, title, symtab->nr);
430         i      = 0;
431         nr     = symtab->nr;
432         symbuf = symtab->symbuf;
433         while (symbuf != nullptr)
434         {
435             for (j = 0; (j < symbuf->bufsize) && (j < nr); j++)
436             {
437                 pr_indent(fp, indent);
438                 (void)fprintf(fp, "%s[%d]=\"%s\"\n", title, i++, symbuf->buf[j]);
439             }
440             nr -= j;
441             symbuf = symbuf->next;
442         }
443         if (nr != 0)
444         {
445             gmx_incons("Printing symbol table (symtab) structure");
446         }
447     }
448 }