The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
string_utils.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2005 - 2025
3 by Philippe Plantier <ayin@anathas.org>
4 Copyright (C) 2005 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
5 Copyright (C) 2003 by David White <dave@whitevine.net>
6 Part of the Battle for Wesnoth Project https://www.wesnoth.org/
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY.
14
15 See the COPYING file for more details.
16*/
17
18/**
19 * @file
20 * Various string-routines.
21 */
22
23#include "gettext.hpp"
24#include "log.hpp"
27#include "utils/charconv.hpp"
28#include "utils/general.hpp"
29#include <algorithm>
30#include <array>
31#include <limits>
33#include <stdexcept>
34
35#include <boost/algorithm/string.hpp>
36
37static lg::log_domain log_engine("engine");
38#define ERR_GENERAL LOG_STREAM(err, lg::general())
39#define ERR_NG LOG_STREAM(err, log_engine)
40
41namespace utils {
42
43void trim(std::string_view& s)
44{
45 s.remove_prefix(std::min(s.find_first_not_of(" \t\r\n"), s.size()));
46 if(s.empty()) {
47 return;
48 }
49 //find_last_not_of never returns npos because !s.empty()
50 std::size_t first_to_trim = s.find_last_not_of(" \t\r\n") + 1;
51 s = s.substr(0, first_to_trim);
52}
53
54/**
55 * Splits a (comma-)separated string into a vector of pieces.
56 * @param[in] s A (comma-)separated string.
57 * @param[in] sep The separator character (usually a comma).
58 * @param[in] flags Flags controlling how the split is done.
59 * This is a bit field with two settings (both on by default):
60 * REMOVE_EMPTY causes empty pieces to be skipped/removed.
61 * STRIP_SPACES causes the leading and trailing spaces of each piece to be ignored/stripped.
62 */
63std::vector<std::string> split(std::string_view s, const char sep, const int flags)
64{
65 std::vector<std::string> res;
66 split_foreach(s, sep, flags, [&](std::string_view item) {
67 res.emplace_back(item);
68 });
69 return res;
70}
71
72std::set<std::string> split_set(std::string_view s, char sep, const int flags)
73{
74 std::set<std::string> res;
75 split_foreach(s, sep, flags, [&](std::string_view item) {
76 res.emplace(item);
77 });
78 return res;
79}
80
81std::vector<std::string_view> split_view(std::string_view s, const char sep, const int flags)
82{
83 std::vector<std::string_view> res;
84 split_foreach(s, sep, flags, [&](std::string_view item) {
85 res.push_back(item);
86 });
87 return res;
88}
89
90namespace {
91 std::size_t get_padding(std::string_view str)
92 {
93 // A leading '0' signals we want to pad upto the size of the number
94 return (str.size() > 1 && str[0] == '0') ? (str.size() - 1) : 0;
95 }
96}
97
98std::vector<std::string> square_parenthetical_split(const std::string& val,
99 const char separator, const std::string& left,
100 const std::string& right,const int flags)
101{
102 std::vector< std::string > res;
103
104 if (val.empty()) {
105 return res;
106 }
107 if (!separator) {
108 ERR_GENERAL << "Separator must be specified for square bracket split function.";
109 return res;
110 }
111 if (left.size() != right.size()) {
112 ERR_GENERAL << "Left and Right Parenthesis lists not same length";
113 return res;
114 }
115
116 std::string lp = left;
117 std::string rp = right;
118 std::vector<char> part;
119 bool in_parenthesis = false;
120 std::vector<std::string::const_iterator> square_left;
121 std::vector<std::string::const_iterator> square_right;
122 std::vector< std::string > square_expansion;
123
124 std::string::const_iterator i1 = val.begin();
125 std::string::const_iterator i2;
126 std::string::const_iterator j1;
127 if (flags & STRIP_SPACES) {
128 while (i1 != val.end() && portable_isspace(*i1))
129 ++i1;
130 }
131 if (i1 == val.end()) return res;
132 i2=i1;
133 j1=i1;
134
135 // If the string contains no animation markers, return the string immediately.
136 // Added since many static images are treated as animations and run through here.
137 const std::string complex_markers = separator + std::string("[");
138 if (val.find_first_of(complex_markers) == std::string::npos)
139 {
140 std::string mutable_val(i1, val.end());
141 if (flags & STRIP_SPACES) {
142 boost::trim_right(mutable_val);
143 }
144 return { mutable_val };
145 }
146
147 while (true) {
148 if(i2 == val.end() || (!in_parenthesis && *i2 == separator)) {
149 //push back square contents
150 std::size_t size_square_exp = 0;
151 for (std::size_t i=0; i < square_left.size(); i++) {
152 std::string tmp_val(square_left[i]+1,square_right[i]);
153 std::vector< std::string > tmp = split(tmp_val);
154 for(const std::string& piece : tmp) {
155 std::size_t found_tilde = piece.find_first_of('~');
156 if (found_tilde == std::string::npos) {
157 std::size_t found_asterisk = piece.find_first_of('*');
158 if (found_asterisk == std::string::npos) {
159 std::string tmp2(piece);
160 boost::trim(tmp2);
161 square_expansion.push_back(tmp2);
162 }
163 else { //'*' multiple expansion
164 std::string s_begin = piece.substr(0,found_asterisk);
165 boost::trim(s_begin);
166 std::string s_end = piece.substr(found_asterisk+1);
167 boost::trim(s_end);
168 for (int ast=std::stoi(s_end); ast>0; --ast)
169 square_expansion.push_back(s_begin);
170 }
171 }
172 else { //expand number range
173 std::string s_begin = piece.substr(0,found_tilde);
174 boost::trim(s_begin);
175 int begin = std::stoi(s_begin);
176 std::string s_end = piece.substr(found_tilde+1);
177 boost::trim(s_end);
178 int end = std::stoi(s_end);
179
180 std::size_t padding = std::max(get_padding(s_begin), get_padding(s_end));
181 if (padding > 0 && s_begin.size() != s_end.size()) {
182 ERR_GENERAL << "Square bracket padding sizes not matching: "
183 << s_begin << " and " << s_end <<".";
184 }
185
186 int increment = (end >= begin ? 1 : -1);
187 end+=increment; //include end in expansion
188 for (int k=begin; k!=end; k+=increment) {
189 std::string pb = std::to_string(k);
190 for (std::size_t p=pb.size(); p<=padding; p++)
191 pb = std::string("0") + pb;
192 square_expansion.push_back(pb);
193 }
194 }
195 }
196 if (i*square_expansion.size() != (i+1)*size_square_exp ) {
197 std::string tmp2(i1, i2);
198 ERR_GENERAL << "Square bracket lengths do not match up: " << tmp2;
199 return res;
200 }
201 size_square_exp = square_expansion.size();
202 }
203
204 //combine square contents and rest of string for comma zone block
205 std::size_t j = 0;
206 std::size_t j_max = 0;
207 if (!square_left.empty())
208 j_max = square_expansion.size() / square_left.size();
209 do {
210 j1 = i1;
211 std::string new_val;
212 for (std::size_t i=0; i < square_left.size(); i++) {
213 std::string tmp_val(j1, square_left[i]);
214 new_val.append(tmp_val);
215 std::size_t k = j+i*j_max;
216 if (k < square_expansion.size())
217 new_val.append(square_expansion[k]);
218 j1 = square_right[i]+1;
219 }
220 std::string tmp_val(j1, i2);
221 new_val.append(tmp_val);
222 if (flags & STRIP_SPACES)
223 boost::trim_right(new_val);
224 if (!(flags & REMOVE_EMPTY) || !new_val.empty())
225 res.push_back(new_val);
226 j++;
227 } while (j<j_max);
228
229 if (i2 == val.end()) //escape loop
230 break;
231 ++i2;
232 if (flags & STRIP_SPACES) { //strip leading spaces
233 while (i2 != val.end() && portable_isspace(*i2))
234 ++i2;
235 }
236 i1=i2;
237 square_left.clear();
238 square_right.clear();
239 square_expansion.clear();
240 continue;
241 }
242 if(!part.empty() && *i2 == part.back()) {
243 part.pop_back();
244 if (*i2 == ']') square_right.push_back(i2);
245 if (part.empty())
246 in_parenthesis = false;
247 ++i2;
248 continue;
249 }
250 bool found=false;
251 for(std::size_t i=0; i < lp.size(); i++) {
252 if (*i2 == lp[i]){
253 if (*i2 == '[')
254 square_left.push_back(i2);
255 ++i2;
256 part.push_back(rp[i]);
257 found=true;
258 break;
259 }
260 }
261 if(!found){
262 ++i2;
263 } else
264 in_parenthesis = true;
265 }
266
267 if(!part.empty()){
268 ERR_GENERAL << "Mismatched parenthesis:\n"<<val;
269 }
270
271 return res;
272}
273
274std::map<std::string, std::string> map_split(
275 const std::string& val
276 , char major
277 , char minor
278 , int flags
279 , const std::string& default_value)
280{
281 //first split by major so that we get a vector with the key-value pairs
282 std::vector< std::string > v = split(val, major, flags);
283
284 //now split by minor to extract keys and values
285 std::map< std::string, std::string > res;
286
287 for( std::vector< std::string >::iterator i = v.begin(); i != v.end(); ++i) {
288 std::size_t pos = i->find_first_of(minor);
289 std::string key, value;
290
291 if(pos == std::string::npos) {
292 key = (*i);
293 value = default_value;
294 } else {
295 key = i->substr(0, pos);
296 value = i->substr(pos + 1);
297 }
298
299 res[key] = value;
300 }
301
302 return res;
303}
304
305std::vector<std::string> parenthetical_split(std::string_view val,
306 const char separator, std::string_view left,
307 std::string_view right,const int flags)
308{
309 std::vector< std::string > res;
310 std::vector<char> part;
311 bool in_parenthesis = false;
312
313 std::string_view::const_iterator i1 = val.begin();
314 std::string_view::const_iterator i2;
315 if (flags & STRIP_SPACES) {
316 while (i1 != val.end() && portable_isspace(*i1))
317 ++i1;
318 }
319 i2=i1;
320
321 if(left.size()!=right.size()){
322 ERR_GENERAL << "Left and Right Parenthesis lists not same length";
323 return res;
324 }
325
326 while (i2 != val.end()) {
327 if(!in_parenthesis && separator && *i2 == separator){
328 std::string new_val(i1, i2);
329 if (flags & STRIP_SPACES)
330 boost::trim_right(new_val);
331 if (!(flags & REMOVE_EMPTY) || !new_val.empty())
332 res.push_back(new_val);
333 ++i2;
334 if (flags & STRIP_SPACES) {
335 while (i2 != val.end() && portable_isspace(*i2))
336 ++i2;
337 }
338 i1=i2;
339 continue;
340 }
341 if(!part.empty() && *i2 == part.back()){
342 part.pop_back();
343 if(!separator && part.empty()){
344 std::string new_val(i1, i2);
345 if (flags & STRIP_SPACES)
346 boost::trim(new_val);
347 res.push_back(new_val);
348 ++i2;
349 i1=i2;
350 }else{
351 if (part.empty())
352 in_parenthesis = false;
353 ++i2;
354 }
355 continue;
356 }
357 bool found=false;
358 for(std::size_t i=0; i < left.size(); i++){
359 if (*i2 == left[i]){
360 if (!separator && part.empty()){
361 std::string new_val(i1, i2);
362 if (flags & STRIP_SPACES)
363 boost::trim(new_val);
364 res.push_back(new_val);
365 ++i2;
366 i1=i2;
367 }else{
368 ++i2;
369 }
370 part.push_back(right[i]);
371 found=true;
372 break;
373 }
374 }
375 if(!found){
376 ++i2;
377 } else
378 in_parenthesis = true;
379 }
380
381 std::string new_val(i1, i2);
382 if (flags & STRIP_SPACES)
383 boost::trim(new_val);
384 if (!(flags & REMOVE_EMPTY) || !new_val.empty())
385 res.push_back(std::move(new_val));
386
387 if(!part.empty()){
388 ERR_GENERAL << "Mismatched parenthesis:\n"<<val;
389 }
390
391 return res;
392}
393
394// Modify a number by string representing integer difference, or optionally %
395int apply_modifier( const int number, const std::string &amount, const int minimum ) {
396 // wassert( amount.empty() == false );
397 // Everything below is done in a wider type than int, and only narrowed (with
398 // saturation) at the very end, so that a huge WML-supplied amount/percentage
399 // or a unit value near INT_MAX/INT_MIN won't silently wrap around to a bogus
400 // (and possibly negative) result.
401 long long value = 0;
402 try {
403 value = std::stoll(amount);
404 } catch(const std::invalid_argument&) {
405 } catch(const std::out_of_range&) {
406 value = (!amount.empty() && amount.front() == '-')
407 ? std::numeric_limits<long long>::min()
408 : std::numeric_limits<long long>::max();
409 }
410 if(amount[amount.size()-1] == '%') {
411 // Clamp first so the multiplication below can't overflow a long long either.
412 constexpr long long pct_limit = 1'000'000'000LL;
413 value = std::clamp(value, -pct_limit, pct_limit);
414 const long long product = static_cast<long long>(number) * value;
415 value = (product < 0) ? -((-product + 50) / 100) : (product + 50) / 100;
416 }
417 value += number;
418 if (( minimum > 0 ) && ( value < minimum ))
419 value = minimum;
420 value = std::clamp<long long>(value, std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
421 return static_cast<int>(value);
422}
423
424std::string escape(std::string_view str, const char *special_chars)
425{
426 std::string::size_type pos = str.find_first_of(special_chars);
427 if (pos == std::string::npos) {
428 return std::string(str);
429 }
430 std::string res = std::string(str);
431 do {
432 res.insert(pos, 1, '\\');
433 pos = res.find_first_of(special_chars, pos + 2);
434 } while (pos != std::string::npos);
435 return res;
436}
437
438std::string unescape(std::string_view str)
439{
440 std::string::size_type pos = str.find('\\');
441 if (pos == std::string::npos) {
442 return std::string(str);
443 }
444 std::string res = std::string(str);
445 do {
446 res.erase(pos, 1);
447 pos = res.find('\\', pos + 1);
448 } while (pos != std::string::npos);
449 return res;
450}
451
452std::string urlencode(std::string_view str)
453{
454 static const std::string nonresv_str =
455 "-."
456 "0123456789"
457 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
458 "_"
459 "abcdefghijklmnopqrstuvwxyz"
460 "~";
461 static const std::set<char> nonresv(nonresv_str.begin(), nonresv_str.end());
462
463 std::ostringstream res;
464 res << std::hex;
465 res.fill('0');
466
467 for(char c : str) {
468 if(nonresv.count(c) != 0) {
469 res << c;
470 continue;
471 }
472
473 res << '%';
474 res.width(2);
475 res << static_cast<int>(c);
476 }
477
478 return res.str();
479}
480
481bool string_bool(const std::string& str, bool def) {
482 if (str.empty()) return def;
483
484 // yes/no is the standard, test it first
485 if (str == "yes") return true;
486 if (str == "no"|| str == "false" || str == "off" || str == "0" || str == "0.0")
487 return false;
488
489 // all other non-empty string are considered as true
490 return true;
491}
492
493std::string bool_string(const bool value)
494{
495 std::ostringstream ss;
496 ss << std::boolalpha << value;
497
498 return ss.str();
499}
500
501std::string signed_value(int val)
502{
503 std::ostringstream oss;
504 oss << (val >= 0 ? "+" : font::unicode_minus) << std::abs(val);
505 return oss.str();
506}
507
508std::string half_signed_value(int val)
509{
510 std::ostringstream oss;
511 if (val < 0)
512 oss << font::unicode_minus;
513 oss << std::abs(val);
514 return oss.str();
515}
516
517static void si_string_impl_stream_write(std::stringstream &ss, double input) {
518 std::streamsize oldprec = ss.precision();
519#ifdef _MSC_VER
520 // For MSVC, default mode misbehaves, so we use fixed instead.
521 ss.precision(1);
522 ss << std::fixed
523 << input;
524#else
525 // In default mode, precision sets the number of significant figures.
526
527 // 999.5 and above will render as 1000+, however, only numbers above 1000 will use 4 digits
528 // Rounding everything from 100 up (at which point we stop using decimals anyway) avoids this.
529 if (input >= 100) {
530 input = std::round(input);
531 }
532
533 // When in binary mode, numbers of up to 1023.9999 can be passed
534 // We should render those with 4 digits, instead of as 1e+3.
535 // Input should be an integer number now, but doubles can do strange things, so check the halfway point instead.
536 if (input >= 999.5) {
537 ss.precision(4);
538 } else {
539 ss.precision(3);
540 }
541 ss << input;
542#endif
543 ss.precision(oldprec);
544}
545
546std::string si_string(double input, bool base2, const std::string& unit) {
547 const double multiplier = base2 ? 1024 : 1000;
548
549 typedef std::array<std::string, 9> strings9;
550
551 if(input < 0){
552 return font::unicode_minus + si_string(std::abs(input), base2, unit);
553 }
554
555 strings9 prefixes;
556 strings9::const_iterator prefix;
557 if (input == 0.0) {
558 strings9 tmp { { "","","","","","","","","" } };
559 prefixes = tmp;
560 prefix = prefixes.begin();
561 } else if (input < 1.0) {
562 strings9 tmp { {
563 "",
564 _("prefix_milli^m"),
565 _("prefix_micro^µ"),
566 _("prefix_nano^n"),
567 _("prefix_pico^p"),
568 _("prefix_femto^f"),
569 _("prefix_atto^a"),
570 _("prefix_zepto^z"),
571 _("prefix_yocto^y")
572 } };
573 prefixes = tmp;
574 prefix = prefixes.begin();
575 while (input < 1.0 && *prefix != prefixes.back()) {
576 input *= multiplier;
577 ++prefix;
578 }
579 } else {
580 strings9 tmp { {
581 "",
582 (base2 ?
583 // TRANSLATORS: Translate the K in KiB only
584 _("prefix_kibi^K") :
585 _("prefix_kilo^k")
586 ),
587 _("prefix_mega^M"),
588 _("prefix_giga^G"),
589 _("prefix_tera^T"),
590 _("prefix_peta^P"),
591 _("prefix_exa^E"),
592 _("prefix_zetta^Z"),
593 _("prefix_yotta^Y")
594 } };
595 prefixes = tmp;
596 prefix = prefixes.begin();
597 while (input > multiplier && *prefix != prefixes.back()) {
598 input /= multiplier;
599 ++prefix;
600 }
601 }
602
603 std::stringstream ss;
605 ss << ' '
606 << *prefix
607 // TRANSLATORS: Translate the i in (for example) KiB only
608 << (base2 && (!(*prefix).empty()) ? _("infix_binary^i") : "")
609 << unit;
610 return ss.str();
611}
612
613static bool is_username_char(char c) {
614 return ((c == '_') || (c == '-'));
615}
616
617static bool is_wildcard_char(char c) {
618 return ((c == '?') || (c == '*'));
619}
620
621bool isvalid_username(const std::string& username) {
622 const std::size_t alnum = std::count_if(username.begin(), username.end(), portable_isalnum);
623 const std::size_t valid_char =
624 std::count_if(username.begin(), username.end(), is_username_char);
625 if ((alnum + valid_char != username.size())
626 || valid_char == username.size() || username.empty() )
627 {
628 return false;
629 }
630 return true;
631}
632
633bool isvalid_wildcard(const std::string& username) {
634 const std::size_t alnum = std::count_if(username.begin(), username.end(), portable_isalnum);
635 const std::size_t valid_char =
636 std::count_if(username.begin(), username.end(), is_username_char);
637 const std::size_t wild_char =
638 std::count_if(username.begin(), username.end(), is_wildcard_char);
639 if ((alnum + valid_char + wild_char != username.size())
640 || valid_char == username.size() || username.empty() )
641 {
642 return false;
643 }
644 return true;
645}
646
647
648bool word_completion(std::string& text, std::vector<std::string>& wordlist) {
649 std::vector<std::string> matches;
650 const std::size_t last_space = text.rfind(" ");
651 // If last character is a space return.
652 if (last_space == text.size() -1) {
653 wordlist = matches;
654 return false;
655 }
656
657 bool text_start;
658 std::string semiword;
659 if (last_space == std::string::npos) {
660 text_start = true;
661 semiword = text;
662 } else {
663 text_start = false;
664 semiword.assign(text, last_space + 1, text.size());
665 }
666
667 std::string best_match = semiword;
668 for (std::vector<std::string>::const_iterator word = wordlist.begin();
669 word != wordlist.end(); ++word)
670 {
671 if (word->size() < semiword.size()
672 || !std::equal(semiword.begin(), semiword.end(), word->begin(),
673 [](char a, char b) { return tolower(a) == tolower(b); })) // TODO: is this the right approach?
674 {
675 continue;
676 }
677 if (matches.empty()) {
678 best_match = *word;
679 } else {
680 int j = 0;
681 while (toupper(best_match[j]) == toupper((*word)[j])) j++;
682 if (best_match.begin() + j < best_match.end()) {
683 best_match.erase(best_match.begin() + j, best_match.end());
684 }
685 }
686 matches.push_back(*word);
687 }
688 if(!matches.empty()) {
689 text.replace(last_space + 1, best_match.size(), best_match);
690 }
691 wordlist = matches;
692 return text_start;
693}
694
695static bool is_word_boundary(char c) {
696 return (c == ' ' || c == ',' || c == ':' || c == '\'' || c == '"' || c == '-');
697}
698
699bool word_match(const std::string& message, const std::string& word) {
700 std::size_t first = message.find(word);
701 if (first == std::string::npos) return false;
702 if (first == 0 || is_word_boundary(message[first - 1])) {
703 std::size_t next = first + word.size();
704 if (next == message.size() || is_word_boundary(message[next])) {
705 return true;
706 }
707 }
708 return false;
709}
710
711[[nodiscard]] bool wildcard_string_match(std::string_view str, std::string_view pat) noexcept
712{
713 auto s_first = str.cbegin();
714 auto p_first = pat.cbegin();
715 const auto s_last = str.cend();
716 const auto p_last = pat.cend();
717
718 // First, match the initial characters up to, and including, the first '*'/'+' wildcard.
719 // Matching the first wildcard early allows the `std::equal` to be skipped in some common cases.
720
721 auto is_star_or_plus = [](char x) noexcept { return x == '*' || x == '+'; };
722 auto match_char = [](char s, char p) noexcept { return s == p || p == '?'; };
723
724 const auto first_wild = std::find_if(p_first, p_last, is_star_or_plus);
725
726 if(first_wild == p_last) {
727 return std::equal(s_first, s_last, p_first, p_last, match_char);
728 }
729
730 const auto wild_cat = static_cast<int>(*first_wild == '+');
731
732 if(first_wild != p_first) {
733 const auto n_chars = std::distance(p_first, first_wild);
734
735 if(std::distance(s_first, s_last) < (n_chars + wild_cat)) {
736 return false;
737 }
738
739 std::tie(s_first, p_first) = std::mismatch(s_first, s_first + n_chars, p_first, match_char);
740
741 if(p_first != first_wild) {
742 return false;
743 }
744 }
745
746 if(s_first == s_last) {
747 return std::all_of(p_first, p_last, [](char c) { return c == '*'; });
748 }
749
750 s_first += wild_cat;
751 p_first += 1;
752
753 // Then
754
755 while(true) {
756 const auto next_wild = std::find_if(p_first, p_last, is_star_or_plus);
757
758 if(next_wild == p_last) {
759 return boost::ends_with(std::pair{s_first, s_last}, std::pair{p_first, p_last}, match_char);
760 }
761
762 if(next_wild != p_first) {
763 auto [sub_f, sub_l] = std::default_searcher{p_first, next_wild, match_char}(s_first, s_last);
764
765 if(sub_f == s_last) {
766 return false;
767 }
768
769 s_first = sub_l;
770 p_first = next_wild;
771 }
772
773 auto is_wildcard = [](char x) noexcept { return x == '*' || x == '+' || x == '?'; };
774 const auto next_non_wild = std::find_if_not(p_first, p_last, is_wildcard);
775 const auto required_chars = std::distance(p_first, next_non_wild) - std::count(p_first, next_non_wild, '*');
776
777 if(std::distance(s_first, s_last) < required_chars) {
778 return false;
779 }
780
781 s_first += required_chars;
782 p_first = next_non_wild;
783
784 if(p_first == p_last) {
785 return true;
786 }
787 }
788}
789
790void to_sql_wildcards(std::string& str, bool underscores)
791{
792 std::replace(str.begin(), str.end(), '*', '%');
793 if(underscores)
794 {
795 std::size_t n = 0;
796 while((n = str.find("_", n)) != std::string::npos)
797 {
798 str.replace(n, 1, "\\_");
799 n += 2;
800 }
801 }
802}
803
804std::string indent(const std::string& string, std::size_t indent_size)
805{
806 if(indent_size == 0) {
807 return string;
808 }
809
810 std::string indent(indent_size, ' ');
811
812 if(string.empty()) {
813 return indent;
814 }
815
816 const std::vector<std::string>& lines = split(string, '\x0A', 0);
817 std::string res;
818
819 for(std::size_t lno = 0; lno < lines.size();) {
820 const std::string& line = lines[lno];
821
822 // Lines containing only a carriage return count as empty.
823 if(!line.empty() && line != "\x0D") {
824 res += indent;
825 }
826
827 res += line;
828
829 if(++lno < lines.size()) {
830 res += '\x0A';
831 }
832 }
833
834 return res;
835}
836
837std::vector<std::string> quoted_split(const std::string& val, char c, int flags, char quote)
838{
839 std::vector<std::string> res;
840
841 std::string::const_iterator i1 = val.begin();
842 std::string::const_iterator i2 = val.begin();
843
844 while (i2 != val.end()) {
845 if (*i2 == quote) {
846 // Ignore quoted character
847 ++i2;
848 if (i2 != val.end()) ++i2;
849 } else if (*i2 == c) {
850 std::string new_val(i1, i2);
851 if (flags & STRIP_SPACES)
852 boost::trim(new_val);
853 if (!(flags & REMOVE_EMPTY) || !new_val.empty())
854 res.push_back(std::move(new_val));
855 ++i2;
856 if (flags & STRIP_SPACES) {
857 while(i2 != val.end() && *i2 == ' ')
858 ++i2;
859 }
860
861 i1 = i2;
862 } else {
863 ++i2;
864 }
865 }
866
867 std::string new_val(i1, i2);
868 if (flags & STRIP_SPACES)
869 boost::trim(new_val);
870 if (!(flags & REMOVE_EMPTY) || !new_val.empty())
871 res.push_back(new_val);
872
873 return res;
874}
875
876namespace
877{
878/**
879 * Internal common code for parse_range and parse_range_real.
880 *
881 * If str contains two elements and a separator such as "a-b", returns a and b.
882 * Otherwise, returns the original string and utils::nullopt.
883 */
884std::pair<std::string_view, utils::optional<std::string_view>> parse_range_internal_separator(std::string_view str)
885{
886 // If turning this into a list with additional options, ensure that "-" (if present) is last. Otherwise a
887 // range such as "-2..-1" might be incorrectly split as "-2..", "1".
888 static const auto separator = std::string{"-"};
889
890 // Starting from the second character means that it won't interpret the minus
891 // sign on a negative number as the separator.
892 // No need to check the string length first, as str.find() already does that.
893 auto pos = str.find(separator, 1);
894 auto length = separator.size();
895
896 if(pos != std::string::npos && pos + length < str.size()) {
897 return {str.substr(0, pos), str.substr(pos + length)};
898 }
899
900 return {str, utils::nullopt};
901}
902} // namespace
903
904std::pair<int, int> parse_range(std::string_view str)
905{
906 auto [a, b] = parse_range_internal_separator(str);
907 std::pair<int, int> res{0, 0};
908 try {
909 if(a == "-infinity" && b) {
910 // The "&& b" is so that we treat parse_range("-infinity") the same as parse_range("infinity"),
911 // both of those will report an invalid range.
912 res.first = std::numeric_limits<int>::min();
913 } else {
914 res.first = utils::stoi(a);
915 }
916
917 if(!b) {
918 res.second = res.first;
919 } else if(*b == "infinity") {
920 res.second = std::numeric_limits<int>::max();
921 } else {
922 res.second = utils::stoi(*b);
923 if(res.second < res.first) {
924 res.second = res.first;
925 }
926 }
927 } catch(const std::invalid_argument&) {
928 ERR_GENERAL << "Invalid range: " << str;
929 }
930
931 return res;
932}
933
934std::pair<double, double> parse_range_real(std::string_view str)
935{
936 auto [a, b] = parse_range_internal_separator(str);
937 std::pair<double, double> res{0, 0};
938 try {
939 if(a == "-infinity" && b) {
940 // There's already a static-assert for is_iec559 in random.cpp, so this isn't limiting the architectures
941 // that Wesnoth can run on.
942 static_assert(std::numeric_limits<double>::is_iec559,
943 "Don't know how negative infinity is treated on this architecture");
944 res.first = -std::numeric_limits<double>::infinity();
945 } else {
946 res.first = utils::stod(a);
947 }
948
949 if(!b) {
950 res.second = res.first;
951 } else if(*b == "infinity") {
952 res.second = std::numeric_limits<double>::infinity();
953 } else {
954 res.second = utils::stod(*b);
955 if(res.second < res.first) {
956 res.second = res.first;
957 }
958 }
959 } catch(const std::invalid_argument&) {
960 ERR_GENERAL << "Invalid range: " << str;
961 }
962
963 return res;
964}
965
966std::vector<std::pair<int, int>> parse_ranges_unsigned(const std::string& str)
967{
968 auto to_return = parse_ranges_int(str);
969 if(std::any_of(to_return.begin(), to_return.end(), [](const std::pair<int, int>& r) { return r.first < 0; })) {
970 ERR_GENERAL << "Invalid range (expected values to be zero or positive): " << str;
971 return {};
972 }
973
974 return to_return;
975}
976
977std::vector<std::pair<double, double>> parse_ranges_real(const std::string& str)
978{
979 std::vector<std::pair<double, double>> to_return;
980 for(const std::string& r : utils::split(str)) {
981 to_return.push_back(parse_range_real(r));
982 }
983
984 return to_return;
985}
986
987std::vector<std::pair<int, int>> parse_ranges_int(const std::string& str)
988{
989 std::vector<std::pair<int, int>> to_return;
990 for(const std::string& r : utils::split(str)) {
991 to_return.push_back(parse_range(r));
992 }
993
994 return to_return;
995}
996
997void ellipsis_truncate(std::string& str, const std::size_t size)
998{
999 const std::size_t prev_size = str.length();
1000
1001 utf8::truncate(str, size);
1002
1003 if(str.length() != prev_size) {
1004 str += font::ellipsis;
1005 }
1006}
1007
1008} // end namespace utils
This class represents a single unit of a specific type.
Definition unit.hpp:39
static lg::log_domain log_engine("engine")
#define ERR_GENERAL
static std::string _(const char *str)
Definition gettext.hpp:100
static int indent
Definition log.cpp:89
Standard logging facilities (interface).
const std::string ellipsis
Definition constants.cpp:39
const std::string unicode_minus
Definition constants.cpp:42
std::string & truncate(std::string &str, const std::size_t size)
Truncates a UTF-8 string to the specified number of characters.
Definition unicode.cpp:118
@ STRIP_SPACES
REMOVE_EMPTY: remove empty elements.
std::vector< std::string_view > split_view(std::string_view s, const char sep, const int flags)
std::string si_string(double input, bool base2, const std::string &unit)
Convert into a string with an SI-postfix.
void trim(std::string_view &s)
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.
bool isvalid_wildcard(const std::string &username)
Check if the username pattern contains only valid characters.
std::set< std::string > split_set(std::string_view s, char sep, const int flags)
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...
int stoi(std::string_view str)
Same interface as std::stoi and meant as a drop in replacement, except:
Definition charconv.hpp:157
static void si_string_impl_stream_write(std::stringstream &ss, double input)
std::vector< std::pair< int, int > > parse_ranges_int(const std::string &str)
Handles a comma-separated list of inputs to parse_range.
std::vector< std::string > parenthetical_split(std::string_view val, const char separator, std::string_view left, std::string_view right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
bool wildcard_string_match(std::string_view str, std::string_view pat) noexcept
Performs pattern matching with wildcards.
std::string half_signed_value(int val)
Sign with Unicode "−" if negative.
std::string bool_string(const bool value)
Converts a bool value to 'true' or 'false'.
static bool is_word_boundary(char c)
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.
std::vector< std::pair< int, int > > parse_ranges_unsigned(const std::string &str)
Handles a comma-separated list of inputs to parse_range, in a context that does not expect negative v...
std::string urlencode(std::string_view str)
Percent-escape characters in a UTF-8 string intended to be part of a URL.
void to_sql_wildcards(std::string &str, bool underscores)
Converts '*' to '' and optionally escapes '_'.
void split_foreach(std::string_view s, char sep, const int flags, const F &f)
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.
bool isvalid_username(const std::string &username)
Check if the username contains only valid characters.
double stod(std::string_view str)
Same interface as std::stod and meant as a drop in replacement, except:
Definition charconv.hpp:143
int apply_modifier(const int number, const std::string &amount, const int minimum)
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< int, int > parse_range(std::string_view str)
Recognises the following patterns, and returns a {min, max} pair.
std::string unescape(std::string_view str)
Remove all escape characters (backslash)
std::vector< std::pair< double, double > > parse_ranges_real(const std::string &str)
bool word_match(const std::string &message, const std::string &word)
Check if a message contains a word.
std::string escape(std::string_view str, const char *special_chars)
Prepends a configurable set of characters with a backslash.
constexpr bool portable_isspace(int c)
std::string signed_value(int val)
Convert into a signed value (using the Unicode "−" and +0 convention.
constexpr bool portable_isalnum(int c)
std::pair< double, double > parse_range_real(std::string_view str)
Recognises similar patterns to parse_range, and returns a {min, max} pair.
std::vector< std::string > split(const config_attribute_value &val)
bool word_completion(std::string &text, std::vector< std::string > &wordlist)
Try to complete the last word of 'text' with the 'wordlist'.
static bool is_wildcard_char(char c)
static bool is_username_char(char c)
std::unique_ptr< MIX_Audio, decltype(&MIX_DestroyAudio)> value
Definition sound.cpp:139
mock_party p
static map_location::direction n
static map_location::direction s
#define i
#define c
#define b