The Battle for Wesnoth  1.15.12+dev
string_utils.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 by David White <dave@whitevine.net>
3  Copyright (C) 2005 - 2018 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 #pragma once
17 
18 #include "font/constants.hpp"
19 
20 #include <algorithm>
21 #include <map>
22 #include <ostream>
23 #include <set>
24 #include <sstream>
25 #include <string>
26 #include <string_view>
27 #include <utility>
28 #include <vector>
29 
30 class t_string;
31 
32 namespace utils {
33 
34 using string_map = std::map<std::string, t_string>;
35 
36 bool isnewline(const char c);
37 bool portable_isspace(const char c);
38 bool notspace(char c);
39 
40 enum {
41  REMOVE_EMPTY = 0x01, /** REMOVE_EMPTY: remove empty elements. */
42  STRIP_SPACES = 0x02 /** STRIP_SPACES: strips leading and trailing blank spaces. */
43 };
44 
45 void trim(std::string_view& s);
46 
47 template<typename F>
48 void split_foreach_impl(std::string_view s, char sep, const F& f)
49 {
50  if(s.empty()) {
51  return;
52  }
53  while(true)
54  {
55  int partend = s.find(sep);
56  if(partend == int(std::string_view::npos)) {
57  break;
58  }
59  f(s.substr(0, partend));
60  s.remove_prefix(partend + 1);
61  }
62  f(s);
63 }
64 
65 template<typename F>
66 void split_foreach(std::string_view s, char sep, const int flags, const F& f)
67 {
68  split_foreach_impl(s, sep, [&](std::string_view item) {
69  if(flags & STRIP_SPACES) {
70  trim(item);
71  }
72  if(!(flags & REMOVE_EMPTY) || !item.empty()) {
73  f(item);
74  }
75  });
76 }
77 
78 
79 
80 /** Splits a (comma-)separated string into a vector of pieces. */
81 std::vector<std::string> split(std::string_view val, const char c = ',', const int flags = REMOVE_EMPTY | STRIP_SPACES);
82 std::set<std::string> split_set(std::string_view val, const char c = ',', const int flags = REMOVE_EMPTY | STRIP_SPACES);
83 
84 /**
85  * This function is identical to split(), except it does not split when it otherwise would if the
86  * previous character was identical to the parameter 'quote' (i.e. it does not split quoted commas).
87  * This method was added to make it possible to quote user input, particularly so commas in user input
88  * would not cause visual problems in menus.
89  *
90  * @todo Why not change split()? That would change the methods post condition.
91  */
92 std::vector<std::string> quoted_split(const std::string& val, char c= ',', int flags = REMOVE_EMPTY | STRIP_SPACES, char quote = '\\');
93 
94 /**
95  * Splits a (comma-)separated string into a set of pieces.
96  * See split() for the meanings of the parameters.
97  */
98 inline std::set<std::string> set_split(const std::string& val, const char c = ',', const int flags = REMOVE_EMPTY | STRIP_SPACES)
99 {
100  std::vector<std::string> vec_split = split(val, c, flags);
101  return std::set< std::string >(vec_split.begin(), vec_split.end());
102 }
103 
104 /**
105  * Splits a string based on two separators into a map.
106  *
107  * Major: the separator between elements of the map
108  * Minor: the separator between keys and values in one element
109  *
110  * For example, the string 'a:b,c:d,e:f' would be parsed into:
111  * a => b
112  * c => d
113  * e => f
114  */
115 std::map<std::string, std::string> map_split(
116  const std::string& val,
117  char major = ',',
118  char minor = ':',
119  int flags = REMOVE_EMPTY | STRIP_SPACES,
120  const std::string& default_value = "");
121 
122 /**
123  * Splits a string based either on a separator, except then the text appears within specified parenthesis.
124  *
125  * If the separator is "0" (default), it splits a string into an odd number of parts:
126  * - The part before the first '(',
127  * - the part between the first '('
128  * - and the matching right ')', etc ...
129  * and the remainder of the string.
130  *
131  * Note that one can use the same character for both the left and right parenthesis, which usually makes
132  * the most sense for this function.
133  *
134  * Note that this will find the first matching char in the left string and match against the corresponding
135  * char in the right string. A correctly processed string should return a vector with an odd number of
136  * elements. Empty elements are never removed as they are placeholders, hence REMOVE EMPTY only works for
137  * the separator split.
138  *
139  * INPUT: ("a(b)c{d}e(f{g})h", 0, "({", ")}")
140  * RETURNS: {"a", "b", "c", "d", "e", "f{g}", "h"}
141  */
142 std::vector< std::string > parenthetical_split(
143  const std::string& val,
144  const char separator = 0,
145  const std::string& left = "(",
146  const std::string& right = ")",
147  const int flags = REMOVE_EMPTY | STRIP_SPACES);
148 
149 /**
150  * Similar to parenthetical_split, but also expands embedded square brackets.
151  *
152  * Notes:
153  * - The Separator must be specified and number of entries in each square bracket must match in each section.
154  * - Leading zeros are preserved if specified between square brackets.
155  * - An asterisk as in [a*n] indicates to expand 'a' n times
156  *
157  * This is useful for expanding animation WML code.
158  *
159  * Examples:
160  *
161  * INPUT: ("a[1~3](1,[5,6,7]),b[8,9]", ",")
162  * RETURNS: {"a1(1,5)", "a2(1,6)", "a3(1,7)", "b8", "b9"}
163  *
164  * INPUT: ("abc[07~10]")
165  * RETURNS: {"abc07", "abc08", "abc09", "abc10"}
166  *
167  * INPUT: ("a[1,2]b[3~4]:c[5,6]")
168  * RETURNS: {"a1b3:c5", "a2b4:c6"}
169  *
170  * INPUT: ("abc[3~1].png")
171  * RETURNS: {"abc3.png", "abc2.png", "abc1.png"}
172  *
173  * INPUT: ("abc[3,1].png")
174  * RETURNS: {"abc3.png", "abc1.png"}
175  *
176  * INPUT: ("abc[de,xyz]")
177  * RETURNS: {"abcde", "abcxyz"}
178  *
179  * INPUT: ("abc[1*3]")
180  * RETURNS: {"abc1", "abc1", "abc1"}
181  */
182 std::vector<std::string> square_parenthetical_split(
183  const std::string& val,
184  const char separator = ',',
185  const std::string& left = "([",
186  const std::string& right = ")]",
187  const int flags = REMOVE_EMPTY | STRIP_SPACES);
188 
189 /**
190  * Generates a new string joining container items in a list.
191  *
192  * @param v A container with elements.
193  * @param s List delimiter.
194  */
195 template <typename T>
196 std::string join(const T& v, const std::string& s = ",")
197 {
198  std::stringstream str;
199 
200  for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
201  str << *i;
202  if(std::next(i) != v.end()) {
203  str << s;
204  }
205  }
206 
207  return str.str();
208 }
209 
210 template <typename T>
211 std::string join_map(
212  const T& v,
213  const std::string& major = ",",
214  const std::string& minor = ":")
215 {
216  std::stringstream str;
217 
218  for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
219  str << i->first << minor << i->second;
220  if(std::next(i) != v.end()) {
221  str << major;
222  }
223  }
224 
225  return str.str();
226 }
227 
228 /**
229  * Generates a new string containing a bullet list.
230  *
231  * List items are preceded by the indentation blanks, a bullet string and
232  * another blank; all but the last item are followed by a newline.
233  *
234  * @param v A container with elements.
235  * @param indent Number of indentation blanks.
236  * @param bullet The leading bullet string.
237  */
238 template<typename T>
239 std::string bullet_list(const T& v, std::size_t indent = 4, const std::string& bullet = font::unicode_bullet)
240 {
241  std::ostringstream str;
242 
243  for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
244  if(i != v.begin()) {
245  str << '\n';
246  }
247 
248  str << std::string(indent, ' ') << bullet << ' ' << *i;
249  }
250 
251  return str.str();
252 }
253 
254 /**
255  * Indent a block of text.
256  *
257  * Only lines with content are changed; empty lines are left intact. However,
258  * if @a string is an empty string itself, the indentation unit with the
259  * specified @a indent_size will be returned instead.
260  *
261  * @param string Text to indent.
262  * @param indent_size Number of indentation units to use.
263  */
264 std::string indent(const std::string& string, std::size_t indent_size = 4);
265 
266 std::pair<int, int> parse_range(const std::string& str);
267 
268 std::vector<std::pair<int, int>> parse_ranges(const std::string& str);
269 
270 int apply_modifier(const int number, const std::string &amount, const int minimum = 0);
271 
272 /** Add a "+" or replace the "-" par Unicode minus */
273 inline std::string print_modifier(const std::string &mod)
274 {
275  return mod[0] == '-' ? (font::unicode_minus + std::string(mod.begin() + 1, mod.end())) : ("+" + mod);
276 }
277 
278 /** Prepends a configurable set of characters with a backslash */
279 std::string escape(const std::string &str, const char *special_chars);
280 
281 /**
282  * Prepend all special characters with a backslash.
283  *
284  * Special characters are:
285  * #@{}+-,\*=
286  */
287 inline std::string escape(const std::string &str)
288 {
289  return escape(str, "#@{}+-,\\*=");
290 }
291 
292 /** Remove all escape characters (backslash) */
293 std::string unescape(const std::string &str);
294 
295 /** Percent-escape characters in a UTF-8 string intended to be part of a URL. */
296 std::string urlencode(const std::string &str);
297 
298 /** Surround the string 'str' with double quotes. */
299 inline std::string quote(const std::string &str)
300 {
301  return '"' + str + '"';
302 }
303 
304 /** Convert no, false, off, 0, 0.0 to false, empty to def, and others to true */
305 bool string_bool(const std::string& str,bool def=false);
306 
307 /** Converts a bool value to 'true' or 'false' */
308 std::string bool_string(const bool value);
309 
310 /** Convert into a signed value (using the Unicode "−" and +0 convention */
311 std::string signed_value(int val);
312 
313 /** Sign with Unicode "−" if negative */
314 std::string half_signed_value(int val);
315 
316 /** Convert into a percentage (using the Unicode "−" and +0% convention */
317 inline std::string signed_percent(int val) {return signed_value(val) + "%";}
318 
319 /**
320  * Convert into a string with an SI-postfix.
321  *
322  * If the unit is to be translatable,
323  * a t_string should be passed as the third argument.
324  * _("unit_byte^B") is suggested as standard.
325  *
326  * There are no default values because they would not be translatable.
327  */
328 std::string si_string(double input, bool base2, const std::string& unit);
329 
330 /**
331  * Try to complete the last word of 'text' with the 'wordlist'.
332  *
333  * @param[in, out] text The parameter's usage is:
334  * - Input: Text where we try to complete the last word
335  * of.
336  * - Output: Text with completed last word.
337  * @param[in, out] wordlist
338  * The parameter's usage is:
339  * - Inout: A vector of strings to complete against.
340  * - Output: A vector of strings that matched 'text'.
341  *
342  * @retval true iff text is just one word (no spaces)
343  */
344 bool word_completion(std::string& text, std::vector<std::string>& wordlist);
345 
346 /** Check if a message contains a word. */
347 bool word_match(const std::string& message, const std::string& word);
348 
349 /**
350  * Match using '*' as any number of characters (including none),
351  * '+' as one or more characters, and '?' as any one character.
352  */
353 bool wildcard_string_match(const std::string& str, const std::string& match);
354 
355 /**
356  * Converts '*' to '%' and optionally escapes '_'.
357  *
358  * @param str The original string.
359  * @param underscores Whether to escape underscore characters as well.
360  */
361 void to_sql_wildcards(std::string& str, bool underscores = true);
362 
363 /**
364  * Check if the username contains only valid characters.
365  *
366  * (all alpha-numeric characters plus underscore and hyphen)
367  */
368 bool isvalid_username(const std::string& login);
369 
370 /**
371  * Check if the username pattern contains only valid characters.
372  *
373  * (all alpha-numeric characters plus underscore, hyphen,
374  * question mark and asterisk)
375  */
376 bool isvalid_wildcard(const std::string& login);
377 
378 /**
379  * Truncates a string to a given utf-8 character count and then appends an ellipsis.
380  */
381 void ellipsis_truncate(std::string& str, const std::size_t size);
382 
383 } // end namespace utils
bool isvalid_wildcard(const std::string &username)
Check if the username pattern contains only valid characters.
std::pair< int, int > parse_range(const std::string &str)
std::string join_map(const T &v, const std::string &major=",", const std::string &minor=":")
std::string urlencode(const std::string &str)
Percent-escape characters in a UTF-8 string intended to be part of a URL.
bool isvalid_username(const std::string &username)
Check if the username contains only valid characters.
std::map< std::string, t_string > string_map
This class represents a single unit of a specific type.
Definition: unit.hpp:120
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
std::set< std::string > split_set(std::string_view s, char sep, const int flags)
std::string unescape(const std::string &str)
Remove all escape characters (backslash)
bool wildcard_string_match(const std::string &str, const std::string &match)
Match using &#39;*&#39; as any number of characters (including none), &#39;+&#39; as one or more characters, and &#39;?&#39; as any one character.
void ellipsis_truncate(std::string &str, const std::size_t size)
Truncates a string to a given utf-8 character count and then appends an ellipsis. ...
bool notspace(const char c)
std::map< std::string, std::string > map_split(const std::string &val, char major, char minor, int flags, const std::string &default_value)
Splits a string based on two separators into a map.
std::string quote(const std::string &str)
Surround the string &#39;str&#39; with double quotes.
std::string half_signed_value(int val)
Sign with Unicode "−" if negative.
std::string bullet_list(const T &v, std::size_t indent=4, const std::string &bullet=font::unicode_bullet)
Generates a new string containing a bullet list.
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:86
const std::string unicode_minus
Definition: constants.cpp:41
std::vector< std::pair< int, int > > parse_ranges(const std::string &str)
std::string si_string(double input, bool base2, const std::string &unit)
Convert into a string with an SI-postfix.
void to_sql_wildcards(std::string &str, bool underscores)
Converts &#39;*&#39; to &#39;&#39; and optionally escapes &#39;_&#39;.
lu_byte right
Definition: lparser.cpp:1227
std::string escape(const std::string &str, const char *special_chars)
Prepends a configurable set of characters with a backslash.
std::string login()
std::size_t i
Definition: function.cpp:940
static map_location::DIRECTION s
void split_foreach_impl(std::string_view s, char sep, const F &f)
std::vector< std::string > quoted_split(const std::string &val, char c, int flags, char quote)
This function is identical to split(), except it does not split when it otherwise would if the previo...
std::string signed_percent(int val)
Convert into a percentage (using the Unicode "−" and +0% convention.
std::string bool_string(const bool value)
Converts a bool value to &#39;true&#39; or &#39;false&#39;.
bool string_bool(const std::string &str, bool def)
Convert no, false, off, 0, 0.0 to false, empty to def, and others to true.
const std::string unicode_bullet
Definition: constants.cpp:46
bool isnewline(const char c)
REMOVE_EMPTY: remove empty elements.
#define next(ls)
Definition: llex.cpp:32
void split_foreach(std::string_view s, char sep, const int flags, const F &f)
#define f
std::vector< std::string > split(const config_attribute_value &val)
int apply_modifier(const int number, const std::string &amount, const int minimum)
lu_byte left
Definition: lparser.cpp:1226
std::string indent(const std::string &string, std::size_t indent_size)
Indent a block of text.
static const char * match(MatchState *ms, const char *s, const char *p)
Definition: lstrlib.cpp:567
void trim(std::string_view &s)
std::set< std::string > set_split(const std::string &val, const char c=',', const int flags=REMOVE_EMPTY|STRIP_SPACES)
Splits a (comma-)separated string into a set of pieces.
bool portable_isspace(const char c)
std::string signed_value(int val)
Convert into a signed value (using the Unicode "−" and +0 convention.
mock_char c
std::string print_modifier(const std::string &mod)
Add a "+" or replace the "-" par Unicode minus.
bool word_completion(std::string &text, std::vector< std::string > &wordlist)
Try to complete the last word of &#39;text&#39; with the &#39;wordlist&#39;.
std::vector< std::string > square_parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Similar to parenthetical_split, but also expands embedded square brackets.
std::pair< std::string, unsigned > item
Definition: help_impl.hpp:409
bool word_match(const std::string &message, const std::string &word)
Check if a message contains a word.
std::vector< std::string > parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...