Merge branch 'release-4-6' into release-5-0
[alexxy/gromacs.git] / src / gromacs / utility / stringutil.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2011,2012,2013,2014, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements functions and classes in stringutil.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_utility
41  */
42 #include "stringutil.h"
43
44 #include <cctype>
45 #include <cstdio>
46 #include <cstdarg>
47 #include <cstring>
48
49 #include <algorithm>
50 #include <string>
51 #include <vector>
52
53 #include "gromacs/utility/gmxassert.h"
54
55 namespace gmx
56 {
57
58 bool endsWith(const std::string &str, const char *suffix)
59 {
60     if (suffix == NULL || suffix[0] == '\0')
61     {
62         return true;
63     }
64     size_t length = std::strlen(suffix);
65     return (str.length() >= length
66             && str.compare(str.length() - length, length, suffix) == 0);
67 }
68
69 std::string stripSuffixIfPresent(const std::string &str, const char *suffix)
70 {
71     if (suffix != NULL)
72     {
73         size_t suffixLength = std::strlen(suffix);
74         if (suffixLength > 0 && endsWith(str, suffix))
75         {
76             return str.substr(0, str.length() - suffixLength);
77         }
78     }
79     return str;
80 }
81
82 std::string stripString(const std::string &str)
83 {
84     std::string::const_iterator start = str.begin();
85     std::string::const_iterator end   = str.end();
86     while (start != end && std::isspace(*start))
87     {
88         ++start;
89     }
90     while (start != end && std::isspace(*(end - 1)))
91     {
92         --end;
93     }
94     return std::string(start, end);
95 }
96
97 std::string formatString(const char *fmt, ...)
98 {
99     va_list           ap;
100     char              staticBuf[1024];
101     int               length = 1024;
102     std::vector<char> dynamicBuf;
103     char             *buf = staticBuf;
104
105     // TODO: There may be a better way of doing this on Windows, Microsoft
106     // provides their own way of doing things...
107     while (1)
108     {
109         va_start(ap, fmt);
110         int n = vsnprintf(buf, length, fmt, ap);
111         va_end(ap);
112         if (n > -1 && n < length)
113         {
114             std::string result(buf);
115             return result;
116         }
117         if (n > -1)
118         {
119             length = n + 1;
120         }
121         else
122         {
123             length *= 2;
124         }
125         dynamicBuf.resize(length);
126         buf = &dynamicBuf[0];
127     }
128 }
129
130 std::vector<std::string> splitString(const std::string &str)
131 {
132     std::vector<std::string>          result;
133     std::string::const_iterator       currPos = str.begin();
134     const std::string::const_iterator end     = str.end();
135     while (currPos != end)
136     {
137         while (currPos != end && std::isspace(*currPos))
138         {
139             ++currPos;
140         }
141         const std::string::const_iterator startPos = currPos;
142         while (currPos != end && !std::isspace(*currPos))
143         {
144             ++currPos;
145         }
146         if (startPos != end)
147         {
148             result.push_back(std::string(startPos, currPos));
149         }
150     }
151     return result;
152 }
153
154 std::string concatenateStrings(const char *const *sarray, size_t count)
155 {
156     std::string result;
157
158     for (size_t i = 0; i < count && sarray[i] != NULL; ++i)
159     {
160         if (sarray[i][0] != '\0')
161         {
162             result.append(sarray[i]);
163             char lastchar = sarray[i][std::strlen(sarray[i])-1];
164             if (!std::isspace(lastchar))
165             {
166                 result.append(" ");
167             }
168         }
169     }
170     result.resize(result.find_last_not_of(" \n\r\t") + 1);
171     return result;
172 }
173
174 namespace
175 {
176
177 /*! \brief
178  * Common implementation for string replacement functions.
179  *
180  * \param[in] input  Input string.
181  * \param[in] from   String to find.
182  * \param[in] to     String to use to replace \p from.
183  * \param[in] bWholeWords  Whether to only consider matches to whole words.
184  * \returns   \p input with all occurrences of \p from replaced with \p to.
185  * \throws    std::bad_alloc if out of memory.
186  *
187  * \ingroup module_utility
188  */
189 std::string
190 replaceInternal(const std::string &input, const char *from, const char *to,
191                 bool bWholeWords)
192 {
193     GMX_RELEASE_ASSERT(from != NULL && to != NULL,
194                        "Replacement strings must not be NULL");
195     size_t      matchLength = std::strlen(from);
196     std::string result;
197     size_t      inputPos = 0;
198     size_t      matchPos = input.find(from);
199     while (matchPos < input.length())
200     {
201         size_t matchEnd = matchPos + matchLength;
202         if (bWholeWords)
203         {
204             if (!((matchPos == 0 || !std::isalnum(input[matchPos-1]))
205                   && (matchEnd == input.length() || !std::isalnum(input[matchEnd]))))
206             {
207                 matchPos = input.find(from, matchPos + 1);
208                 continue;
209             }
210
211         }
212         result.append(input, inputPos, matchPos - inputPos);
213         result.append(to);
214         inputPos = matchEnd;
215         matchPos = input.find(from, inputPos);
216     }
217     result.append(input, inputPos, matchPos - inputPos);
218     return result;
219 }
220
221 }   // namespace
222
223 std::string
224 replaceAll(const std::string &input, const char *from, const char *to)
225 {
226     return replaceInternal(input, from, to, false);
227 }
228
229 std::string
230 replaceAll(const std::string &input, const std::string &from,
231            const std::string &to)
232 {
233     return replaceInternal(input, from.c_str(), to.c_str(), false);
234 }
235
236 std::string
237 replaceAllWords(const std::string &input, const char *from, const char *to)
238 {
239     return replaceInternal(input, from, to, true);
240 }
241
242 std::string
243 replaceAllWords(const std::string &input, const std::string &from,
244                 const std::string &to)
245 {
246     return replaceInternal(input, from.c_str(), to.c_str(), true);
247 }
248
249
250 /********************************************************************
251  * TextLineWrapperSettings
252  */
253
254 TextLineWrapperSettings::TextLineWrapperSettings()
255     : maxLength_(0), indent_(0), firstLineIndent_(-1),
256       bStripLeadingWhitespace_(true), continuationChar_('\0')
257 {
258 }
259
260
261 /********************************************************************
262  * TextLineWrapper
263  */
264
265 size_t
266 TextLineWrapper::findNextLine(const char *input, size_t lineStart) const
267 {
268     size_t inputLength = std::strlen(input);
269     bool   bFirstLine  = (lineStart == 0 || input[lineStart - 1] == '\n');
270     // Ignore leading whitespace if necessary.
271     if (!bFirstLine || settings_.bStripLeadingWhitespace_)
272     {
273         lineStart += std::strspn(input + lineStart, " ");
274         if (lineStart >= inputLength)
275         {
276             return inputLength;
277         }
278     }
279
280     int    indent = (bFirstLine ? settings_.firstLineIndent() : settings_.indent());
281     size_t lastAllowedBreakPoint
282         = (settings_.lineLength() > 0
283            ? std::min(lineStart + settings_.lineLength() - indent, inputLength)
284            : inputLength);
285     // Ignore trailing whitespace.
286     lastAllowedBreakPoint += std::strspn(input + lastAllowedBreakPoint, " ");
287     size_t lineEnd = lineStart;
288     do
289     {
290         const char *nextBreakPtr = std::strpbrk(input + lineEnd, " \n");
291         size_t      nextBreak
292             = (nextBreakPtr != NULL ? nextBreakPtr - input : inputLength);
293         if (nextBreak > lastAllowedBreakPoint && lineEnd > lineStart)
294         {
295             break;
296         }
297         lineEnd = nextBreak + 1;
298     }
299     while (lineEnd < lastAllowedBreakPoint && input[lineEnd - 1] != '\n');
300     return (lineEnd < inputLength ? lineEnd : inputLength);
301 }
302
303 size_t
304 TextLineWrapper::findNextLine(const std::string &input, size_t lineStart) const
305 {
306     return findNextLine(input.c_str(), lineStart);
307 }
308
309 std::string
310 TextLineWrapper::formatLine(const std::string &input,
311                             size_t lineStart, size_t lineEnd) const
312 {
313     size_t inputLength = input.length();
314     bool   bFirstLine  = (lineStart == 0 || input[lineStart - 1] == '\n');
315     // Strip leading whitespace if necessary.
316     if (!bFirstLine || settings_.bStripLeadingWhitespace_)
317     {
318         lineStart = input.find_first_not_of(' ', lineStart);
319         if (lineStart >= inputLength)
320         {
321             return std::string();
322         }
323     }
324     int  indent        = (bFirstLine ? settings_.firstLineIndent() : settings_.indent());
325     bool bContinuation = (lineEnd < inputLength && input[lineEnd - 1] != '\n');
326     // Strip trailing whitespace.
327     while (lineEnd > lineStart && std::isspace(input[lineEnd - 1]))
328     {
329         --lineEnd;
330     }
331
332     size_t      lineLength = lineEnd - lineStart;
333     std::string result(indent, ' ');
334     result.append(input, lineStart, lineLength);
335     if (bContinuation && settings_.continuationChar_ != '\0')
336     {
337         result.append(1, ' ');
338         result.append(1, settings_.continuationChar_);
339     }
340     return result;
341 }
342
343 std::string
344 TextLineWrapper::wrapToString(const std::string &input) const
345 {
346     std::string result;
347     size_t      lineStart = 0;
348     size_t      length    = input.length();
349     while (lineStart < length)
350     {
351         size_t nextLineStart = findNextLine(input, lineStart);
352         result.append(formatLine(input, lineStart, nextLineStart));
353         if (nextLineStart < length
354             || (nextLineStart == length && input[length - 1] == '\n'))
355         {
356             result.append("\n");
357         }
358         lineStart = nextLineStart;
359     }
360     return result;
361 }
362
363 std::vector<std::string>
364 TextLineWrapper::wrapToVector(const std::string &input) const
365 {
366     std::vector<std::string> result;
367     size_t                   lineStart = 0;
368     size_t                   length    = input.length();
369     while (lineStart < length)
370     {
371         size_t nextLineStart = findNextLine(input, lineStart);
372         result.push_back(formatLine(input, lineStart, nextLineStart));
373         lineStart = nextLineStart;
374     }
375     return result;
376 }
377
378 } // namespace gmx