Merge branch release-5-1
[alexxy/gromacs.git] / src / gromacs / utility / stringutil.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2011,2012,2013,2014,2015, 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 /*! \file
36  * \brief
37  * Declares common string utility and formatting routines.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \inpublicapi
41  * \ingroup module_utility
42  */
43 #ifndef GMX_UTILITY_STRINGUTIL_H
44 #define GMX_UTILITY_STRINGUTIL_H
45
46 #include <cstring>
47
48 #include <string>
49 #include <vector>
50
51 namespace gmx
52 {
53
54 //! \addtogroup module_utility
55 //! \{
56
57 /*! \brief
58  * Tests whether a string is null or empty.
59  *
60  * Does not throw.
61  */
62 static inline bool isNullOrEmpty(const char *str)
63 {
64     return str == NULL || str[0] == '\0';
65 }
66
67 /*! \brief
68  * Tests whether a string starts with another string.
69  *
70  * \param[in] str    String to process.
71  * \param[in] prefix Prefix to find.
72  * \returns   true if \p str starts with \p prefix.
73  *
74  * Returns true if \p prefix is empty.
75  * Does not throw.
76  */
77 static inline bool startsWith(const std::string &str, const std::string &prefix)
78 {
79     return str.compare(0, prefix.length(), prefix) == 0;
80 }
81 //! \copydoc startsWith(const std::string &, const std::string &)
82 static inline bool startsWith(const char *str, const char *prefix)
83 {
84     return std::strncmp(str, prefix, std::strlen(prefix)) == 0;
85 }
86
87 /*! \brief
88  * Tests whether a string ends with another string.
89  *
90  * \param[in] str    String to process.
91  * \param[in] suffix Suffix to find.
92  * \returns   true if \p str ends with \p suffix.
93  *
94  * Returns true if \p suffix is NULL or empty.
95  * Does not throw.
96  */
97 bool endsWith(const char *str, const char *suffix);
98 //! \copydoc endsWith(const char *, const char *)
99 static inline bool endsWith(const std::string &str, const char *suffix)
100 {
101     return endsWith(str.c_str(), suffix);
102 }
103
104 /*! \brief
105  * Removes a suffix from a string.
106  *
107  * \param[in] str    String to process.
108  * \param[in] suffix Suffix to remove.
109  * \returns   \p str with \p suffix removed, or \p str unmodified if it does
110  *      not end with \p suffix.
111  * \throws    std::bad_alloc if out of memory.
112  *
113  * Returns \p str if \p suffix is NULL or empty.
114  */
115 std::string stripSuffixIfPresent(const std::string &str, const char *suffix);
116 /*! \brief
117  * Removes leading and trailing whitespace from a string.
118  *
119  * \param[in] str  String to process.
120  * \returns   \p str with leading and trailing whitespaces removed.
121  * \throws    std::bad_alloc if out of memory.
122  */
123 std::string stripString(const std::string &str);
124
125 /*! \brief
126  * Formats a string (snprintf() wrapper).
127  *
128  * \throws  std::bad_alloc if out of memory.
129  *
130  * This function works like sprintf(), except that it returns an std::string
131  * instead of requiring a preallocated buffer.  Arbitrary length output is
132  * supported.
133  */
134 std::string formatString(const char *fmt, ...);
135
136 /*! \brief Function object that wraps a call to formatString() that
137  * expects a single conversion argument, for use with algorithms. */
138 class StringFormatter
139 {
140     public:
141         /*! \brief Constructor
142          *
143          * \param[in] format The printf-style format string that will
144          *     be applied to convert values of type T to
145          *     string. Exactly one argument to the conversion
146          *     specification(s) in `format` is supported. */
147         explicit StringFormatter(const char *format) : format_(format)
148         {
149         }
150
151         //! Implements the formatting functionality
152         template <typename T>
153         std::string operator()(const T &value) const
154         {
155             return formatString(format_, value);
156         }
157
158     private:
159         //! Format string to use
160         const char *format_;
161 };
162
163 /*! \brief Function object to implement the same interface as
164  * `StringFormatter` to use with strings that should not be formatted
165  * further. */
166 class IdentityFormatter
167 {
168     public:
169         //! Implements the formatting non-functionality
170         std::string operator()(const std::string &value) const
171         {
172             return value;
173         }
174 };
175
176 /*! \brief Formats all the range as strings, and then joins them with
177  * a separator in between.
178  *
179  * \param[in] begin      Iterator the beginning of the range to join.
180  * \param[in] end        Iterator the end of the range to join.
181  * \param[in] separator  String to put in between the joined strings.
182  * \param[in] formatter  Function object to format the objects in
183  *     `container` as strings
184  * \returns   All objects in the range from `begin` to `end` formatted
185  *     as strings and concatenated with `separator` between each pair.
186  * \throws    std::bad_alloc if out of memory.
187  */
188 template <typename InputIterator, typename FormatterType>
189 std::string formatAndJoin(InputIterator begin, InputIterator end, const char *separator, const FormatterType &formatter)
190 {
191     std::string result;
192     const char *currentSeparator = "";
193     for (InputIterator i = begin; i != end; ++i)
194     {
195         result.append(currentSeparator);
196         result.append(formatter(*i));
197         currentSeparator = separator;
198     }
199     return result;
200 }
201
202 /*! \brief Formats all elements of the container as strings, and then
203  * joins them with a separator in between.
204  *
205  * \param[in] container  Objects to join.
206  * \param[in] separator  String to put in between the joined strings.
207  * \param[in] formatter  Function object to format the objects in
208  *     `container` as strings
209  * \returns   All objects from `container` formatted as strings and
210  *     concatenated with `separator` between each pair.
211  * \throws    std::bad_alloc if out of memory.
212  */
213 template <typename ContainerType, typename FormatterType>
214 std::string formatAndJoin(const ContainerType &container, const char *separator, const FormatterType &formatter)
215 {
216     return formatAndJoin(container.begin(), container.end(), separator, formatter);
217 }
218
219 /*! \brief
220  * Joins strings from a range with a separator in between.
221  *
222  * \param[in] begin      Iterator the beginning of the range to join.
223  * \param[in] end        Iterator the end of the range to join.
224  * \param[in] separator  String to put in between the joined strings.
225  * \returns   All strings from (`begin`, `end`) concatenated with `separator`
226  *     between each pair.
227  * \throws    std::bad_alloc if out of memory.
228  */
229 template <typename InputIterator>
230 std::string joinStrings(InputIterator begin, InputIterator end,
231                         const char *separator)
232 {
233     return formatAndJoin(begin, end, separator, IdentityFormatter());
234 }
235
236 /*! \brief
237  * Joins strings from a container with a separator in between.
238  *
239  * \param[in] container  Strings to join.
240  * \param[in] separator  String to put in between the joined strings.
241  * \returns   All strings from `container` concatenated with `separator`
242  *     between each pair.
243  * \throws    std::bad_alloc if out of memory.
244  */
245 template <typename ContainerType>
246 std::string joinStrings(const ContainerType &container, const char *separator)
247 {
248     return joinStrings(container.begin(), container.end(), separator);
249 }
250
251 /*! \brief
252  * Joins strings from an array with a separator in between.
253  *
254  * \param[in] array      Array of strings to join.
255  * \param[in] separator  String to put in between the joined strings.
256  * \tparam    count      Deduced number of elements in \p array.
257  * \returns   All strings from `aray` concatenated with `separator`
258  *     between each pair.
259  * \throws    std::bad_alloc if out of memory.
260  */
261 template <size_t count>
262 std::string joinStrings(const char *const (&array)[count], const char *separator)
263 {
264     return joinStrings(array, array + count, separator);
265 }
266
267 /*! \brief
268  * Splits a string to whitespace separated tokens.
269  *
270  * \param[in] str  String to process.
271  * \returns   \p str split into tokens at each whitespace sequence.
272  * \throws    std::bad_alloc if out of memory.
273  *
274  * This function works like `split` in Python, i.e., leading and trailing
275  * whitespace is ignored, and consecutive whitespaces are treated as a single
276  * separator.
277  */
278 std::vector<std::string> splitString(const std::string &str);
279
280 /*! \brief
281  * Replace all occurrences of a string with another string.
282  *
283  * \param[in] input  Input string.
284  * \param[in] from   String to find.
285  * \param[in] to     String to use to replace \p from.
286  * \returns   Copy of \p input with all occurrences of \p from replaced with \p to.
287  * \throws    std::bad_alloc if out of memory.
288  *
289  * The replacement is greedy and not recursive: starting from the beginning of
290  * \p input, each match of \p from is replaced with \p to, and the search for
291  * the next match begins after the end of the previous match.
292  *
293  * Compexity is O(N), where N is length of output.
294  *
295  * \see replaceAllWords()
296  */
297 std::string replaceAll(const std::string &input,
298                        const char *from, const char *to);
299 //! \copydoc replaceAll(const std::string &, const char *, const char *)
300 std::string replaceAll(const std::string &input,
301                        const std::string &from, const std::string &to);
302 /*! \brief
303  * Replace whole words with others.
304  *
305  * \param[in] input  Input string.
306  * \param[in] from   String to find.
307  * \param[in] to     String to use to replace \p from.
308  * \returns   Copy of \p input with all \p from words replaced with \p to.
309  * \throws    std::bad_alloc if out of memory.
310  *
311  * Works as replaceAll(), but a match is only considered if it is delimited by
312  * non-alphanumeric characters.
313  *
314  * \see replaceAll()
315  */
316 std::string replaceAllWords(const std::string &input,
317                             const char *from, const char *to);
318 //! \copydoc replaceAllWords(const std::string &, const char *, const char *)
319 std::string replaceAllWords(const std::string &input,
320                             const std::string &from, const std::string &to);
321
322 class TextLineWrapper;
323
324 /*! \brief
325  * Stores settings for line wrapping.
326  *
327  * Methods in this class do not throw.
328  *
329  * \see TextLineWrapper
330  *
331  * \inpublicapi
332  */
333 class TextLineWrapperSettings
334 {
335     public:
336         /*! \brief
337          * Initializes default wrapper settings.
338          *
339          * Default settings are:
340          *  - No maximum line width (only explicit line breaks).
341          *  - No indentation.
342          *  - No continuation characters.
343          *  - Do not keep final spaces in input strings.
344          */
345         TextLineWrapperSettings();
346
347         /*! \brief
348          * Sets the maximum length for output lines.
349          *
350          * \param[in] length  Maximum length for the lines after wrapping.
351          *
352          * If this method is not called, or is called with zero \p length, the
353          * wrapper has no maximum length (only wraps at explicit line breaks).
354          */
355         void setLineLength(int length) { maxLength_ = length; }
356         /*! \brief
357          * Sets the indentation for output lines.
358          *
359          * \param[in] indent  Number of spaces to add for indentation.
360          *
361          * If this method is not called, the wrapper does not add indentation.
362          */
363         void setIndent(int indent) { indent_ = indent; }
364         /*! \brief
365          * Sets the indentation for first output line after a line break.
366          *
367          * \param[in] indent  Number of spaces to add for indentation.
368          *
369          * If this method is not called, or called with \p indent equal to -1,
370          * the value set with setIndent() is used.
371          */
372         void setFirstLineIndent(int indent) { firstLineIndent_ = indent; }
373         /*! \brief
374          * Sets whether final spaces in input should be kept.
375          *
376          * \param[in] bKeep  Whether to keep spaces at the end of the input.
377          *
378          * This means that wrapping a string that ends in spaces also keeps
379          * those spaces in the output.  This allows using the wrapper for
380          * partial lines where the initial part of the line may end in a space.
381          * By default, all trailing whitespace is removed.  Note that this
382          * option does not affect spaces before an explicit newline: those are
383          * always removed.
384          */
385         void setKeepFinalSpaces(bool bKeep) { bKeepFinalSpaces_ = bKeep; }
386         /*! \brief
387          * Sets a continuation marker for wrapped lines.
388          *
389          * \param[in] continuationChar  Character to use to mark continuation
390          *      lines.
391          *
392          * If set to non-zero character code, this character is added at the
393          * end of each line where a line break is added by TextLineWrapper
394          * (but not after lines produced by explicit line breaks).
395          * The default (\c '\0') is to not add continuation markers.
396          *
397          * Note that currently, the continuation char may cause the output line
398          * length to exceed the value set with setLineLength() by at most two
399          * characters.
400          */
401         void setContinuationChar(char continuationChar)
402         {
403             continuationChar_ = continuationChar;
404         }
405
406         //! Returns the maximum length set with setLineLength().
407         int lineLength() const { return maxLength_; }
408         //! Returns the indentation set with setIndent().
409         int indent() const { return indent_; }
410         /*! \brief
411          * Returns the indentation set with setFirstLineIndent().
412          *
413          * If setFirstLineIndent() has not been called or has been called with
414          * -1, indent() is returned.
415          */
416         int firstLineIndent() const
417         {
418             return (firstLineIndent_ >= 0 ? firstLineIndent_ : indent_);
419         }
420
421     private:
422         //! Maximum length of output lines, or <= 0 if no limit.
423         int                     maxLength_;
424         //! Number of spaces to indent each output line with.
425         int                     indent_;
426         /*! \brief
427          * Number of spaces to indent the first line after a newline.
428          *
429          * If -1, \a indent_ is used.
430          */
431         int                     firstLineIndent_;
432         //! Whether to keep spaces at end of input.
433         bool                    bKeepFinalSpaces_;
434         //! If not \c '\0', mark each wrapping point with this character.
435         char                    continuationChar_;
436
437         //! Needed to access the members.
438         friend class TextLineWrapper;
439 };
440
441 /*! \brief
442  * Wraps lines to a predefined length.
443  *
444  * This utility class wraps lines at word breaks to produce lines that are not
445  * longer than a predefined length.  Explicit newlines ('\\n') are preserved.
446  * Only space is considered a word separator.  If a single word exceeds the
447  * maximum line length, it is still printed on a single line.
448  * Extra whitespace is stripped from the end of produced lines.
449  * Other options on the wrapping, such as the line length or indentation,
450  * can be changed using a TextLineWrapperSettings object.
451  *
452  * Two interfaces to do the wrapping are provided:
453  *  -# High-level interface using either wrapToString() (produces a single
454  *     string with embedded newlines) or wrapToVector() (produces a vector of
455  *     strings with each line as one element).
456  *     These methods operate on std::string and wrap the entire input string.
457  *  -# Low-level interface using findNextLine() and formatLine().
458  *     findNextLine() operates either on a C string or an std::string, and does
459  *     not do any memory allocation (so it does not throw).  It finds the next
460  *     line to be wrapped, considering the wrapping settings.
461  *     formatLine() does whitespace operations on the line found by
462  *     findNextLine() and returns an std::string.
463  *     These methods allow custom wrapping implementation to either avoid
464  *     exceptions or to wrap only a part of the input string.
465  *
466  * Typical usage:
467  * \code
468    gmx::TextLineWrapper wrapper;
469    wrapper.settings().setLineLength(78);
470    printf("%s\n", wrapper.wrapToString(textToWrap).c_str());
471    \endcode
472  *
473  * \inpublicapi
474  */
475 class TextLineWrapper
476 {
477     public:
478         /*! \brief
479          * Constructs a new line wrapper with default settings.
480          *
481          * Does not throw.
482          */
483         TextLineWrapper()
484         {
485         }
486         /*! \brief
487          * Constructs a new line wrapper with given settings.
488          *
489          * \param[in] settings  Wrapping settings.
490          *
491          * Does not throw.
492          */
493         explicit TextLineWrapper(const TextLineWrapperSettings &settings)
494             : settings_(settings)
495         {
496         }
497
498         /*! \brief
499          * Provides access to settings of this wrapper.
500          *
501          * \returns  The settings object for this wrapper.
502          *
503          * The returned object can be used to modify settings for the wrapper.
504          * All subsequent calls to wrapToString() and wrapToVector() use the
505          * modified settings.
506          *
507          * Does not throw.
508          */
509         TextLineWrapperSettings &settings() { return settings_; }
510
511         //! Returns true if the wrapper would not modify the input string.
512         bool isTrivial() const;
513
514         /*! \brief
515          * Finds the next line to be wrapped.
516          *
517          * \param[in] input     String to wrap.
518          * \param[in] lineStart Index of first character of the line to find.
519          * \returns   Index of first character of the next line.
520          *
521          * If this is the last line, returns the length of \p input.
522          * In determining the length of the returned line, this function
523          * considers the maximum line length, leaving space for indentation,
524          * and also whitespace stripping behavior.
525          * Thus, the line returned may be longer than the maximum line length
526          * if it has leading and/or trailing space.
527          * When wrapping a line on a space (not on an explicit line break),
528          * the returned index is always on a non-whitespace character after the
529          * space.
530          *
531          * To iterate over lines in a string, use the following code:
532          * \code
533            gmx::TextLineWrapper wrapper;
534            // <set desired wrapping settings>
535            size_t lineStart = 0;
536            size_t length = input.length();
537            while (lineStart < length)
538            {
539                size_t nextLineStart = wrapper.findNextLine(input, lineStart);
540                std::string line = wrapper.formatLine(input, lineStart, nextLineStart));
541                // <do something with the line>
542                lineStart = nextLineStart;
543            }
544            return result;
545            \endcode
546          *
547          * Does not throw.
548          */
549         size_t findNextLine(const char *input, size_t lineStart) const;
550         //! \copydoc findNextLine(const char *, size_t)const
551         size_t findNextLine(const std::string &input, size_t lineStart) const;
552         /*! \brief
553          * Formats a single line for output according to wrapping settings.
554          *
555          * \param[in] input     Input string.
556          * \param[in] lineStart Index of first character of the line to format.
557          * \param[in] lineEnd   Index of first character of the next line.
558          * \returns   The line with leading and/or trailing whitespace removed
559          *      and indentation applied.
560          * \throws    std::bad_alloc if out of memory.
561          *
562          * Intended to be used on the lines found by findNextLine().
563          * When used with the lines returned from findNextLine(), the returned
564          * line conforms to the wrapper settings.
565          * Trailing whitespace is always stripped (including any newlines,
566          * i.e., the return value does not contain a newline).
567          */
568         std::string formatLine(const std::string &input,
569                                size_t lineStart, size_t lineEnd) const;
570
571         /*! \brief
572          * Formats a string, producing a single string with all the lines.
573          *
574          * \param[in] input  String to wrap.
575          * \returns   \p input with added newlines such that maximum line
576          *      length is not exceeded.
577          * \throws    std::bad_alloc if out of memory.
578          *
579          * Newlines in the input are preserved, including terminal newlines.
580          * Note that if the input does not contain a terminal newline, the
581          * output does not either.
582          */
583         std::string wrapToString(const std::string &input) const;
584         /*! \brief
585          * Formats a string, producing a vector with all the lines.
586          *
587          * \param[in] input  String to wrap.
588          * \returns   \p input split into lines such that maximum line length
589          *      is not exceeded.
590          * \throws    std::bad_alloc if out of memory.
591          *
592          * The strings in the returned vector do not contain newlines at the
593          * end.
594          * Note that a single terminal newline does not affect the output:
595          * "line\\n" and "line" both produce the same output (but "line\\n\\n"
596          * produces two lines, the second of which is empty).
597          */
598         std::vector<std::string> wrapToVector(const std::string &input) const;
599
600     private:
601         TextLineWrapperSettings settings_;
602 };
603
604 //! \}
605
606 } // namespace gmx
607
608 #endif