E-MailRelay
gstr.h
Go to the documentation of this file.
1//
2// Copyright (C) 2001-2023 Graeme Walker <graeme_walker@users.sourceforge.net>
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <http://www.gnu.org/licenses/>.
16// ===
17///
18/// \file gstr.h
19///
20
21#ifndef G_STR_H
22#define G_STR_H
23
24#include "gdef.h"
25#include "gexception.h"
26#include "gstringarray.h"
27#include "gstringmap.h"
28#include "gstringview.h"
29#include <string>
30#include <sstream>
31#include <iostream>
32#include <list>
33#include <vector>
34#include <limits>
35#include <array>
36#include <algorithm>
37#include <type_traits>
38
39namespace G
40{
41 class Str ;
42}
43
44//| \class G::Str
45/// A static class which provides string helper functions.
46///
47class G::Str
48{
49public:
50 G_EXCEPTION_CLASS( Overflow , tx("string conversion error: over/underflow") ) ;
51 G_EXCEPTION_CLASS( InvalidFormat, tx("string conversion error: invalid format") ) ;
52 G_EXCEPTION_CLASS( NotEmpty, tx("internal error: string container not empty") ) ;
53 G_EXCEPTION( InvalidEol , tx("invalid end-of-line specifier") ) ;
54
55 struct Limited /// Overload discrimiator for G::Str::toUWhatever() requesting a range-limited result.
56 {} ;
57
58 struct Hex /// Overload discrimiator for G::Str::toUWhatever() indicating hexadecimal strings.
59 {} ;
60
61 enum class Eol // See G::Str::readLine().
62 {
63 CrLf ,
64 Cr_Lf_CrLf
65 } ;
66
67 static bool replace( std::string & s , string_view from , string_view to ,
68 std::size_t * pos_p = nullptr ) ;
69 ///< A string_view overload. Replaces 'from' with 'to', starting at
70 ///< offset '*pos_p'. Returns true if a substitution was made,
71 ///< and adjusts '*pos_p' by to.length().
72
73 static void replace( std::string & s , char from , char to ) ;
74 ///< Replaces all 'from' characters with 'to'.
75
76 static void replace( StringArray & , char from , char to ) ;
77 ///< Replaces 'from' characters with 'to' in all the strings in the array.
78
79 static unsigned int replaceAll( std::string & s , string_view from , string_view to ) ;
80 ///< Does a global replace on string 's', replacing all occurrences
81 ///< of sub-string 'from' with 'to'. Returns the number of substitutions
82 ///< made. Consider using in a while loop if 'from' is more than one
83 ///< character.
84
85 static std::string replaced( const std::string & s , char from , char to ) ;
86 ///< Returns the string 's' with all occurrences of 'from' replaced by 'to'.
87
88 static void removeAll( std::string & , char ) ;
89 ///< Removes all occurrences of the character from the string. See also only().
90
91 static std::string removedAll( const std::string & , char ) ;
92 ///< Removes all occurrences of the character from the string and returns
93 ///< the result. See also only().
94
95 static std::string & trimLeft( std::string & s , string_view ws , std::size_t limit = 0U ) ;
96 ///< Trims the lhs of s, taking off up to 'limit' of the 'ws' characters.
97 ///< Returns s.
98
99 static string_view trimLeftView( string_view , string_view ws , std::size_t limit = 0U ) noexcept ;
100 ///< Trims the lhs of s, taking off up to 'limit' of the 'ws' characters.
101 ///< Returns a view into the input string.
102
103 static std::string & trimRight( std::string & s , string_view ws , std::size_t limit = 0U ) ;
104 ///< Trims the rhs of s, taking off up to 'limit' of the 'ws' characters.
105 ///< Returns s.
106
107 static string_view trimRightView( string_view sv , string_view ws , std::size_t limit = 0U ) noexcept ;
108 ///< Trims the rhs of s, taking off up to 'limit' of the 'ws' characters.
109 ///< Returns a view into the input string.
110
111 static std::string & trim( std::string & s , string_view ws ) ;
112 ///< Trims both ends of s, taking off any of the 'ws' characters.
113 ///< Returns s.
114
115 static std::string trimmed( const std::string & s , string_view ws ) ;
116 ///< Returns a trim()med version of s.
117
118 static std::string trimmed( std::string && s , string_view ws ) ;
119 ///< Returns a trim()med version of s.
120
121 static string_view trimmedView( string_view s , string_view ws ) noexcept ;
122 ///< Returns a trim()med view of the input view.
123
124 static bool isNumeric( string_view s , bool allow_minus_sign = false ) noexcept ;
125 ///< Returns true if every character is a decimal digit.
126 ///< Empty strings return true.
127
128 static bool isHex( string_view s ) noexcept ;
129 ///< Returns true if every character is a hexadecimal digit.
130 ///< Empty strings return true.
131
132 static bool isPrintableAscii( string_view s ) noexcept ;
133 ///< Returns true if every character is a 7-bit, non-control
134 ///< character (ie. 0x20<=c<0x7f). Empty strings return true.
135
136 static bool isPrintable( string_view s ) noexcept ;
137 ///< Returns true if every character is a non-control
138 ///< character (ie. 0x20<=c<0x7f || 0xa0<=c<0xff).
139 ///< Empty strings return true.
140
141 static bool isSimple( string_view s ) noexcept ;
142 ///< Returns true if every character is alphanumeric or
143 ///< "-" or "_". Empty strings return true.
144
145 static bool isUShort( string_view s ) noexcept ;
146 ///< Returns true if the string can be converted into
147 ///< an unsigned short without throwing an exception.
148
149 static bool isUInt( string_view s ) noexcept ;
150 ///< Returns true if the string can be converted into
151 ///< an unsigned integer without throwing an exception.
152
153 static bool isULong( string_view s ) noexcept ;
154 ///< Returns true if the string can be converted into
155 ///< an unsigned long without throwing an exception.
156
157 static bool isInt( string_view s ) noexcept ;
158 ///< Returns true if the string can be converted into
159 ///< an integer without throwing an exception.
160
161 static std::string fromBool( bool b ) ;
162 ///< Converts boolean 'b' to a string.
163
164 static std::string fromDouble( double d ) ;
165 ///< Converts double 'd' to a string.
166
167 static std::string fromInt( int i ) ;
168 ///< Converts int 'i' to a string.
169
170 static std::string fromLong( long l ) ;
171 ///< Converts long 'l' to a string.
172
173 static std::string fromShort( short s ) ;
174 ///< Converts short 's' to a string.
175
176 static std::string fromUInt( unsigned int ui ) ;
177 ///< Converts unsigned int 'ui' to a string.
178
179 static std::string fromULong( unsigned long ul ) ;
180 ///< Converts unsigned long 'ul' to a string.
181
182 static std::string fromUShort( unsigned short us ) ;
183 ///< Converts unsigned short 'us' to a string.
184
185 static std::string fromULong( unsigned long , const Hex & ) ;
186 ///< Converts an unsigned value to a lower-case
187 ///< hex string with no leading zeros.
188
189 static std::string fromULongLong( unsigned long long , const Hex & ) ;
190 ///< Converts an unsigned value to a lower-case
191 ///< hex string with no leading zeros.
192
193 static string_view fromULongToHex( unsigned long , char * out ) noexcept ;
194 ///< Low-level conversion from an unsigned value
195 ///< to a lower-case hex string with no leading zeros.
196 ///< The output buffer must be sizeof(long)*2.
197
198 static string_view fromULongLongToHex( unsigned long long , char * out ) noexcept ;
199 ///< Low-level conversion from an unsigned value
200 ///< to a lower-case hex string with no leading zeros.
201 ///< The output buffer must be sizeof(long long)*2.
202
203 static bool toBool( string_view s ) ;
204 ///< Converts string 's' to a bool.
205 ///<
206 ///< Exception: InvalidFormat
207
208 static double toDouble( const std::string & s ) ;
209 ///< Converts string 's' to a double.
210 ///<
211 ///< Exception: Overflow
212 ///< Exception: InvalidFormat
213
214 static float toFloat( const std::string & s ) ;
215 ///< Converts string 's' to a float.
216 ///<
217 ///< Exception: Overflow
218 ///< Exception: InvalidFormat
219
220 static int toInt( string_view s ) ;
221 ///< Converts string 's' to an int.
222 ///<
223 ///< Exception: Overflow
224 ///< Exception: InvalidFormat
225
226 static long toLong( string_view s ) ;
227 ///< Converts string 's' to a long.
228 ///<
229 ///< Exception: Overflow
230 ///< Exception: InvalidFormat
231
232 static short toShort( string_view s ) ;
233 ///< Converts string 's' to a short.
234 ///<
235 ///< Exception: Overflow
236 ///< Exception: InvalidFormat
237
238 static unsigned int toUInt( string_view s ) ;
239 ///< Converts string 's' to an unsigned int.
240 ///<
241 ///< Exception: Overflow
242 ///< Exception: InvalidFormat
243
244 static int toInt( string_view s1 , string_view s2 ) ;
245 ///< Overload that converts the first string if it can be converted
246 ///< without throwing, or otherwise the second string.
247
248 static unsigned int toUInt( string_view s , Limited ) ;
249 ///< Converts string 's' to an unsigned int.
250 ///<
251 ///< Very large numeric strings are limited to the maximum
252 ///< value of the numeric type, without an Overflow exception.
253 ///<
254 ///< Exception: InvalidFormat
255
256 static unsigned int toUInt( string_view s1 , string_view s2 ) ;
257 ///< Overload that converts the first string if it can be converted
258 ///< without throwing, or otherwise the second string.
259
260 static unsigned int toUInt( string_view s1 , unsigned int default_ ) ;
261 ///< Overload that converts the string if it can be converted
262 ///< without throwing, or otherwise returns the default value.
263
264 static unsigned long toULong( string_view s , Limited ) ;
265 ///< Converts string 's' to an unsigned long.
266 ///<
267 ///< Very large numeric strings are limited to the maximum value
268 ///< of the numeric type, without an Overflow exception.
269 ///<
270 ///< Exception: InvalidFormat
271
272 static unsigned long toULong( string_view s , Hex ) ;
273 ///< An overload for hexadecimal strings. To avoid exceptions
274 ///< use isHex() and check the string length.
275
276 static unsigned long toULong( string_view s , Hex , Limited ) ;
277 ///< An overload for hexadecimal strings where overflow
278 ///< results in the return of the maximum value. To avoid
279 ///< exceptions use isHex().
280
281 template <typename T> static T toUnsigned( const char * p , const char * end ,
282 bool & overflow , bool & invalid ) noexcept ;
283 ///< Low-level conversion from an unsigned decimal string to a number.
284 ///< All characters in the range are used; any character
285 ///< not 0..9 yields an 'invalid' result.
286
287 template <typename T> static T toUnsigned( const char * &p , const char * end ,
288 bool & overflow ) noexcept ;
289 ///< Low-level conversion from an unsigned decimal string to a number.
290 ///< Consumes characters until the first invalid character.
291
292 static unsigned long toULong( string_view s ) ;
293 ///< Converts string 's' to an unsigned long.
294 ///<
295 ///< Exception: Overflow
296 ///< Exception: InvalidFormat
297
298 static unsigned long toULong( string_view s1 , string_view s2 ) ;
299 ///< Overload that converts the first string if it can be converted
300 ///< without throwing, or otherwise the second string.
301
302 static unsigned short toUShort( string_view s , Limited ) ;
303 ///< Converts string 's' to an unsigned short.
304 ///<
305 ///< Very large numeric strings are limited to the maximum value
306 ///< of the numeric type, without an Overflow exception.
307 ///<
308 ///< Exception: InvalidFormat
309
310 static unsigned short toUShort( string_view s ) ;
311 ///< Converts string 's' to an unsigned short.
312 ///<
313 ///< Exception: Overflow
314 ///< Exception: InvalidFormat
315
316 static void toUpper( std::string & s ) ;
317 ///< Replaces all seven-bit lower-case characters in string 's' by
318 ///< upper-case characters.
319
320 static void toLower( std::string & s ) ;
321 ///< Replaces all seven-bit upper-case characters in string 's' by
322 ///< lower-case characters.
323
324 static std::string upper( string_view ) ;
325 ///< Returns a copy of 's' in which all seven-bit lower-case characters
326 ///< have been replaced by upper-case characters.
327
328 static std::string lower( string_view ) ;
329 ///< Returns a copy of 's' in which all seven-bit upper-case characters
330 ///< have been replaced by lower-case characters.
331
332 static std::string toPrintableAscii( const std::string & in , char escape = '\\' ) ;
333 ///< Returns a 7-bit printable representation of the given input string.
334
335 static std::string toPrintableAscii( const std::wstring & in , wchar_t escape = L'\\' ) ;
336 ///< Returns a 7-bit printable representation of the given input string.
337
338 static std::string printable( const std::string & in , char escape = '\\' ) ;
339 ///< Returns a printable representation of the given input string, using
340 ///< chacter code ranges 0x20 to 0x7e and 0xa0 to 0xfe inclusive.
341 ///< Typically used to prevent escape sequences getting into log files.
342
343 static std::string printable( string_view in , char escape = '\\' ) ;
344 ///< Returns a printable representation of the given input string, using
345 ///< chacter code ranges 0x20 to 0x7e and 0xa0 to 0xfe inclusive.
346 ///< Typically used to prevent escape sequences getting into log files.
347
348 static std::string only( string_view allow_chars , string_view s ) ;
349 ///< Returns the 's' with all occurrences of the characters not appearing in
350 ///< the first string deleted.
351
352 static void escape( std::string & s , char c_escape , string_view specials_in ,
353 string_view specials_out ) ;
354 ///< Prefixes each occurrence of one of the special-in characters with
355 ///< the escape character and its corresponding special-out character.
356 ///<
357 ///< The specials-in and specials-out strings must be the same size.
358 ///<
359 ///< The specials-in string should normally include the escape character
360 ///< itself, otherwise unescaping will not recover the original.
361
362 static void escape( std::string & s ) ;
363 ///< Overload for 'normal' backslash escaping of whitespace.
364
365 static std::string escaped( string_view , char c_escape , string_view specials_in ,
366 string_view specials_out ) ;
367 ///< Returns the escape()d string.
368
369 static std::string escaped( string_view ) ;
370 ///< Returns the escape()d string.
371
372 static void unescape( std::string & s , char c_escape , string_view specials_in , string_view specials_out ) ;
373 ///< Unescapes the string by replacing e-e with e, e-special-in with
374 ///< special-out, and e-other with other. The specials-in and
375 ///< specials-out strings must be the same length.
376
377 static void unescape( std::string & s ) ;
378 ///< Overload for 'normal' unescaping where the string has backslash escaping
379 ///< of whitespace.
380
381 static std::string unescaped( const std::string & s ) ;
382 ///< Returns the unescape()d version of s.
383
384 static string_view meta() noexcept ;
385 ///< Returns a list of shell meta-characters with a tilde as the
386 ///< first character. Does not contain the nul character. This is
387 ///< typically used with escape().
388
389 static std::string readLineFrom( std::istream & stream , string_view eol = {} ) ;
390 ///< Reads a line from the stream using the given line terminator.
391 ///< The line terminator is not part of the returned string.
392 ///< The terminator defaults to the newline.
393 ///<
394 ///< Note that alternatives in the standard library such as
395 ///< std::istream::getline() or std::getline(stream,string)
396 ///< in the standard "string" header are limited to a single
397 ///< character as the terminator.
398 ///<
399 ///< The side-effects on the stream state follow std::getline():
400 ///< reading an unterminated line at the end of the stream sets
401 ///< eof, but a fully-terminated line does not; if no characters
402 ///< are read (including terminators) (eg. already eof) then
403 ///< failbit is set.
404 ///<
405 ///< A read loop that processes even incomplete lines at the end
406 ///< of the stream should do:
407 ///< \code
408 ///< while(stream.good()){read(stream);if(stream)process(line)} // or
409 ///< while(read(stream)){process(line)}
410 ///< \endcode
411 ///< or to process only complete lines:
412 ///< \code
413 ///< while(stream){read(stream);if(stream.good())process(line)} // or
414 ///< while(read(stream)&&stream.good()){process(line)}
415 ///< \endcode
416
417 static std::istream & readLine( std::istream & stream , std::string & result ,
418 string_view eol = {} , bool pre_erase_result = true , std::size_t limit = 0U ) ;
419 ///< Reads a line from the stream using the given line
420 ///< terminator, which may be multi-character. Behaves like
421 ///< std::getline() when the trailing parameters are defaulted.
422 ///< Also behaves like std::getline() by not clearing the
423 ///< result if the stream is initially not good(), even if
424 ///< the pre-erase flag is set.
425
426 static std::istream & readLine( std::istream & stream , std::string & result ,
427 Eol , bool pre_erase_result = true , std::size_t limit = 0U ) ;
428 ///< An overload where lines are terminated with some
429 ///< enumerated combination of CR, LF or CRLF.
430
431 static void splitIntoTokens( const std::string & in , StringArray & out , string_view ws , char esc = '\0' ) ;
432 ///< Splits the string into 'ws'-delimited tokens. The behaviour is like
433 ///< strtok() in that adjacent delimiters count as one and leading and
434 ///< trailing delimiters are ignored. The output array is _not_ cleared
435 ///< first; new tokens are appended to the output list. If the escape
436 ///< character is supplied then it can be used to escape whitespace
437 ///< characters, preventing a split, with those escape characters being
438 ///< consumed in the process. For shell-like tokenising use dequote()
439 ///< before splitIntoTokens(), and revert the non-breaking spaces
440 ///< afterwards.
441
442 static StringArray splitIntoTokens( const std::string & in , string_view ws = Str::ws() , char esc = '\0' ) ;
443 ///< Overload that returns by value.
444
445 static void splitIntoFields( string_view in , StringArray & out ,
446 char sep , char escape = '\0' ,
447 bool remove_escapes = true ) ;
448 ///< Splits the string into fields. Duplicated, leading and trailing
449 ///< separator characters are all significant. The output array is
450 ///< cleared first.
451 ///<
452 ///< If a non-null escape character is given then escaped separators
453 ///< do not result in a split. If the 'remove-escapes' parameter is
454 ///< true then all unescaped escapes are removed from the output; this
455 ///< is generally the preferred behaviour for nested escaping. If the
456 ///< 'remove-escapes' parameter is false then escapes are not removed;
457 ///< unescaped escapes are used to prevent splitting but they remain
458 ///< in the output.
459
460 static StringArray splitIntoFields( string_view in , char sep ) ;
461 ///< Overload that returns by value.
462
463 static std::string dequote( const std::string & , char qq = '\"' , char esc = '\\' ,
464 string_view ws = Str::ws() , string_view nbws = Str::ws() ) ;
465 ///< Dequotes a string by removing unescaped quotes and escaping
466 ///< quoted whitespace, so "qq-aaa-esc-qq-bbb-ws-ccc-qq" becomes
467 ///< "aaa-qq-bbb-esc-ws-ccc". Escaped whitespace characters within
468 ///< quotes can optionally be converted to non-breaking equivalents.
469
470 static std::string join( string_view sep , const StringArray & strings ) ;
471 ///< Concatenates an array of strings with separators.
472
473 static std::string join( string_view sep , string_view s1 , string_view s2 ,
474 string_view s3 = {} , string_view s4 = {} , string_view s5 = {} ,
475 string_view s6 = {} , string_view s7 = {} , string_view s8 = {} ,
476 string_view s9 = {} ) ;
477 ///< Concatenates a small number of strings with separators.
478 ///< In this overload empty strings are ignored.
479
480 static std::string join( string_view sep , const StringMap & , string_view eq ,
481 string_view tail = {} ) ;
482 ///< Concatenates entries in a map, where an entry is "<key><eq><value><tail>".
483
484 static StringArray keys( const StringMap & string_map ) ;
485 ///< Extracts the keys from a map of strings.
486
487 static std::string head( string_view in , std::size_t pos , string_view default_ = {} ) ;
488 ///< Returns the first part of the string up to just before the given position.
489 ///< The character at pos is not returned. Returns the supplied default
490 ///< if pos is npos. Returns the whole string if pos is one-or-more
491 ///< off the end.
492
493 static std::string head( string_view , string_view sep , bool default_empty = true ) ;
494 ///< Overload taking a separator string, and with the default
495 ///< as either the input string or the empty string. If the
496 ///< separator occurs more than once in the input then only the
497 ///< first occurrence is relevant.
498
499 static string_view headView( string_view in , std::size_t pos , string_view default_ = {} ) noexcept ;
500 ///< Like head() but returning a view into the input string.
501
502 static string_view headView( string_view in , string_view sep , bool default_empty = true ) noexcept ;
503 ///< Like head() but returning a view into the input string.
504
505 static std::string tail( string_view in , std::size_t pos , string_view default_ = {} ) ;
506 ///< Returns the last part of the string after the given position.
507 ///< The character at pos is not returned. Returns the supplied default
508 ///< if pos is npos. Returns the empty string if pos is one-or-more
509 ///< off the end.
510
511 static std::string tail( string_view in , string_view sep , bool default_empty = true ) ;
512 ///< Overload taking a separator string, and with the default
513 ///< as either the input string or the empty string. If the
514 ///< separator occurs more than once in the input then only the
515 ///< first occurrence is relevant.
516
517 static string_view tailView( string_view in , std::size_t pos , string_view default_ = {} ) noexcept ;
518 ///< Like tail() but returning a view into the input string.
519
520 static string_view tailView( string_view in , string_view sep , bool default_empty = true ) noexcept ;
521 ///< Like tail() but returning a view into the input string.
522
523 static bool match( string_view , string_view ) noexcept ;
524 ///< Returns true if the two strings are the same.
525
526 static bool iless( string_view , string_view ) noexcept ;
527 ///< Returns true if the first string is lexicographically less
528 ///< than the first, after seven-bit lower-case letters have been
529 ///< folded to upper-case.
530
531 static bool imatch( char , char ) noexcept ;
532 ///< Returns true if the two characters are the same, ignoring seven-bit case.
533
534 static bool imatch( string_view , string_view ) noexcept ;
535 ///< Returns true if the two strings are the same, ignoring seven-bit case.
536 ///< The locale is ignored.
537
538 static std::size_t ifind( string_view s , string_view key ) ;
539 ///< Returns the position of the key in 's' using a seven-bit case-insensitive
540 ///< search. Returns std::string::npos if not found. The locale is ignored.
541
542 static std::size_t ifindat( string_view s , string_view key , std::size_t pos ) ;
543 ///< Returns the position of the key in 's' at of after position 'pos'
544 ///< using a seven-bit case-insensitive search. Returns std::string::npos
545 ///< if not found. The locale is ignored.
546
547 static bool tailMatch( const std::string & in , string_view ending ) noexcept ;
548 ///< Returns true if the string has the given ending (or the given ending is empty).
549
550 static bool headMatch( const std::string & in , string_view head ) noexcept ;
551 ///< Returns true if the string has the given start (or head is empty).
552
553 static string_view ws() noexcept ;
554 ///< Returns a string of standard whitespace characters.
555
556 static string_view alnum() noexcept ;
557 ///< Returns a string of seven-bit alphanumeric characters, ie A-Z, a-z and 0-9.
558
559 static string_view alnum_() noexcept ;
560 ///< Returns alnum() with an additional trailing underscore character.
561
562 static std::string positive() ;
563 ///< Returns a default positive string. See isPositive().
564
565 static std::string negative() ;
566 ///< Returns a default negative string. See isNegative().
567
568 static bool isPositive( string_view ) noexcept ;
569 ///< Returns true if the string has a positive meaning, such as "1", "true", "yes".
570
571 static bool isNegative( string_view ) noexcept ;
572 ///< Returns true if the string has a negative meaning, such as "0", "false", "no".
573
574 static std::string unique( const std::string & s , char c , char r ) ;
575 ///< Returns a string with repeated 'c' characters replaced by
576 ///< one 'r' character. Single 'c' characters are not replaced.
577
578 static std::string unique( const std::string & s , char c ) ;
579 ///< An overload that replaces repeated 'c' characters by
580 ///< one 'c' character.
581
582 static constexpr std::size_t truncate = (~(static_cast<std::size_t>(0U))) ;
583 ///< A special value for the G::Str::strncpy_s() 'count' parameter.
584
585 static errno_t strncpy_s( char * dst , std::size_t n_dst , const char * src , std::size_t count ) noexcept ;
586 ///< Does the same as windows strncpy_s(). Copies count characters
587 ///< from src to dst and adds a terminator character, but fails
588 ///< if dst is too small. If the count is 'truncate' then as
589 ///< much of src is copied as will fit in dst, allowing for the
590 ///< terminator character. Returns zero on success or on
591 ///< truncation (unlike windows strncpy_s()).
592
593public:
594 Str() = delete ;
595} ;
596
597inline
598std::string G::Str::fromInt( int i )
599{
600 return std::to_string( i ) ;
601}
602
603inline
604std::string G::Str::fromLong( long l )
605{
606 return std::to_string( l ) ;
607}
608
609inline
610std::string G::Str::fromShort( short s )
611{
612 return std::to_string( s ) ;
613}
614
615inline
616std::string G::Str::fromUInt( unsigned int ui )
617{
618 return std::to_string( ui ) ;
619}
620
621inline
622std::string G::Str::fromULong( unsigned long ul )
623{
624 return std::to_string( ul ) ;
625}
626
627inline
628std::string G::Str::fromUShort( unsigned short us )
629{
630 return std::to_string( us ) ;
631}
632
633inline
634std::string G::Str::fromULong( unsigned long u , const Hex & )
635{
636 std::array <char,sizeof(u)*2U> buffer ; // NOLINT cppcoreguidelines-pro-type-member-init
637 return sv_to_string( fromULongToHex( u , &buffer[0] ) ) ;
638}
639
640inline
641std::string G::Str::fromULongLong( unsigned long long u , const Hex & )
642{
643 std::array <char,sizeof(u)*2U> buffer ; // NOLINT cppcoreguidelines-pro-type-member-init
644 return sv_to_string( fromULongLongToHex( u , &buffer[0] ) ) ;
645}
646
647template <typename T>
648T G::Str::toUnsigned( const char * p , const char * end , bool & overflow , bool & invalid ) noexcept
649{
650 if( p == nullptr || end == nullptr || p == end )
651 {
652 invalid = true ;
653 overflow = false ;
654 return 0UL ;
655 }
656 T result = toUnsigned<T>( p , end , overflow ) ;
657 if( p != end )
658 invalid = true ;
659 return result ;
660}
661
662template <typename T>
663T G::Str::toUnsigned( const char * &p , const char * end , bool & overflow ) noexcept
664{
665 static_assert( std::is_integral<T>::value , "" ) ;
666 T result = 0 ;
667 for( ; p != end ; p++ )
668 {
669 T n = 0 ;
670 if( *p == '0' ) n = 0 ;
671 else if( *p == '1' ) n = 1 ;
672 else if( *p == '2' ) n = 2 ;
673 else if( *p == '3' ) n = 3 ;
674 else if( *p == '4' ) n = 4 ;
675 else if( *p == '5' ) n = 5 ;
676 else if( *p == '6' ) n = 6 ;
677 else if( *p == '7' ) n = 7 ;
678 else if( *p == '8' ) n = 8 ;
679 else if( *p == '9' ) n = 9 ;
680 else break ;
681
682 auto old = result ;
683 result = result * 10 ;
684 result += n ;
685 if( result < old )
686 overflow = true ;
687 }
688 return result ;
689}
690
691#endif
A static class which provides string helper functions.
Definition: gstr.h:48
static std::string fromShort(short s)
Converts short 's' to a string.
Definition: gstr.h:610
static bool isPrintableAscii(string_view s) noexcept
Returns true if every character is a 7-bit, non-control character (ie.
Definition: gstr.cpp:416
static std::size_t ifind(string_view s, string_view key)
Returns the position of the key in 's' using a seven-bit case-insensitive search.
Definition: gstr.cpp:1436
static string_view headView(string_view in, std::size_t pos, string_view default_={}) noexcept
Like head() but returning a view into the input string.
Definition: gstr.cpp:1311
static bool match(string_view, string_view) noexcept
Returns true if the two strings are the same.
Definition: gstr.cpp:1395
static bool replace(std::string &s, string_view from, string_view to, std::size_t *pos_p=nullptr)
A string_view overload.
Definition: gstr.cpp:226
static bool isUShort(string_view s) noexcept
Returns true if the string can be converted into an unsigned short without throwing an exception.
Definition: gstr.cpp:440
static string_view tailView(string_view in, std::size_t pos, string_view default_={}) noexcept
Like tail() but returning a view into the input string.
Definition: gstr.cpp:1340
static constexpr std::size_t truncate
A special value for the G::Str::strncpy_s() 'count' parameter.
Definition: gstr.h:582
static unsigned int toUInt(string_view s)
Converts string 's' to an unsigned int.
Definition: gstr.cpp:651
static string_view alnum() noexcept
Returns a string of seven-bit alphanumeric characters, ie A-Z, a-z and 0-9.
Definition: gstr.cpp:1276
static void toLower(std::string &s)
Replaces all seven-bit upper-case characters in string 's' by lower-case characters.
Definition: gstr.cpp:822
static bool isNumeric(string_view s, bool allow_minus_sign=false) noexcept
Returns true if every character is a decimal digit.
Definition: gstr.cpp:403
static short toShort(string_view s)
Converts string 's' to a short.
Definition: gstr.cpp:603
static StringArray keys(const StringMap &string_map)
Extracts the keys from a map of strings.
Definition: gstr.cpp:1259
static float toFloat(const std::string &s)
Converts string 's' to a float.
Definition: gstr.cpp:520
static std::istream & readLine(std::istream &stream, std::string &result, string_view eol={}, bool pre_erase_result=true, std::size_t limit=0U)
Reads a line from the stream using the given line terminator, which may be multi-character.
Definition: gstr.cpp:961
static int toInt(string_view s)
Converts string 's' to an int.
Definition: gstr.cpp:541
static bool isHex(string_view s) noexcept
Returns true if every character is a hexadecimal digit.
Definition: gstr.cpp:410
static std::string positive()
Returns a default positive string. See isPositive().
Definition: gstr.cpp:1369
static unsigned int replaceAll(std::string &s, string_view from, string_view to)
Does a global replace on string 's', replacing all occurrences of sub-string 'from' with 'to'.
Definition: gstr.cpp:247
static bool iless(string_view, string_view) noexcept
Returns true if the first string is lexicographically less than the first, after seven-bit lower-case...
Definition: gstr.cpp:1407
static unsigned short toUShort(string_view s, Limited)
Converts string 's' to an unsigned short.
Definition: gstr.cpp:753
static bool imatch(char, char) noexcept
Returns true if the two characters are the same, ignoring seven-bit case.
Definition: gstr.cpp:1418
static bool tailMatch(const std::string &in, string_view ending) noexcept
Returns true if the string has the given ending (or the given ending is empty).
Definition: gstr.cpp:1355
static std::size_t ifindat(string_view s, string_view key, std::size_t pos)
Returns the position of the key in 's' at of after position 'pos' using a seven-bit case-insensitive ...
Definition: gstr.cpp:1441
static bool isPrintable(string_view s) noexcept
Returns true if every character is a non-control character (ie.
Definition: gstr.cpp:421
static std::string unescaped(const std::string &s)
Returns the unescape()d version of s.
Definition: gstr.cpp:203
static std::string fromULong(unsigned long ul)
Converts unsigned long 'ul' to a string.
Definition: gstr.h:622
static T toUnsigned(const char *p, const char *end, bool &overflow, bool &invalid) noexcept
Low-level conversion from an unsigned decimal string to a number.
Definition: gstr.h:648
static double toDouble(const std::string &s)
Converts string 's' to a double.
Definition: gstr.cpp:498
static std::string replaced(const std::string &s, char from, char to)
Returns the string 's' with all occurrences of 'from' replaced by 'to'.
Definition: gstr.cpp:255
static std::string fromBool(bool b)
Converts boolean 'b' to a string.
Definition: gstr.cpp:466
static std::string & trimLeft(std::string &s, string_view ws, std::size_t limit=0U)
Trims the lhs of s, taking off up to 'limit' of the 'ws' characters.
Definition: gstr.cpp:288
static void splitIntoTokens(const std::string &in, StringArray &out, string_view ws, char esc='\0')
Splits the string into 'ws'-delimited tokens.
Definition: gstr.cpp:1122
static std::string toPrintableAscii(const std::string &in, char escape='\\')
Returns a 7-bit printable representation of the given input string.
Definition: gstr.cpp:934
static string_view trimmedView(string_view s, string_view ws) noexcept
Returns a trim()med view of the input view.
Definition: gstr.cpp:354
static std::string unique(const std::string &s, char c, char r)
Returns a string with repeated 'c' characters replaced by one 'r' character.
Definition: gstr.cpp:1470
static long toLong(string_view s)
Converts string 's' to a long.
Definition: gstr.cpp:570
static string_view alnum_() noexcept
Returns alnum() with an additional trailing underscore character.
Definition: gstr.cpp:1282
static string_view fromULongToHex(unsigned long, char *out) noexcept
Low-level conversion from an unsigned value to a lower-case hex string with no leading zeros.
Definition: gstr.cpp:790
static string_view meta() noexcept
Returns a list of shell meta-characters with a tilde as the first character.
Definition: gstr.cpp:1290
static std::string join(string_view sep, const StringArray &strings)
Concatenates an array of strings with separators.
Definition: gstr.cpp:1224
static bool isULong(string_view s) noexcept
Returns true if the string can be converted into an unsigned long without throwing an exception.
Definition: gstr.cpp:457
static void removeAll(std::string &, char)
Removes all occurrences of the character from the string. See also only().
Definition: gstr.cpp:262
static std::string fromInt(int i)
Converts int 'i' to a string.
Definition: gstr.h:598
static std::string lower(string_view)
Returns a copy of 's' in which all seven-bit upper-case characters have been replaced by lower-case c...
Definition: gstr.cpp:827
static std::string readLineFrom(std::istream &stream, string_view eol={})
Reads a line from the stream using the given line terminator.
Definition: gstr.cpp:954
static std::string negative()
Returns a default negative string. See isNegative().
Definition: gstr.cpp:1374
static std::string only(string_view allow_chars, string_view s)
Returns the 's' with all occurrences of the characters not appearing in the first string deleted.
Definition: gstr.cpp:276
static bool isUInt(string_view s) noexcept
Returns true if the string can be converted into an unsigned integer without throwing an exception.
Definition: gstr.cpp:449
static std::string & trimRight(std::string &s, string_view ws, std::size_t limit=0U)
Trims the rhs of s, taking off up to 'limit' of the 'ws' characters.
Definition: gstr.cpp:313
static std::string removedAll(const std::string &, char)
Removes all occurrences of the character from the string and returns the result.
Definition: gstr.cpp:268
static std::string fromUInt(unsigned int ui)
Converts unsigned int 'ui' to a string.
Definition: gstr.h:616
static std::string dequote(const std::string &, char qq='\"' , char esc = '\\' , string_view ws = Str::ws() , string_view nbws = Str::ws() )
Dequotes a string by removing unescaped quotes and escaping quoted whitespace, so "qq-aaa-esc-qq-bbb-...
Definition: gstr.cpp:128
static std::string printable(const std::string &in, char escape='\\')
Returns a printable representation of the given input string, using chacter code ranges 0x20 to 0x7e ...
Definition: gstr.cpp:916
static bool isPositive(string_view) noexcept
Returns true if the string has a positive meaning, such as "1", "true", "yes".
Definition: gstr.cpp:1379
static bool isSimple(string_view s) noexcept
Returns true if every character is alphanumeric or "-" or "_".
Definition: gstr.cpp:426
static bool isNegative(string_view) noexcept
Returns true if the string has a negative meaning, such as "0", "false", "no".
Definition: gstr.cpp:1387
static std::string upper(string_view)
Returns a copy of 's' in which all seven-bit lower-case characters have been replaced by upper-case c...
Definition: gstr.cpp:839
static std::string fromUShort(unsigned short us)
Converts unsigned short 'us' to a string.
Definition: gstr.h:628
static void unescape(std::string &s, char c_escape, string_view specials_in, string_view specials_out)
Unescapes the string by replacing e-e with e, e-special-in with special-out, and e-other with other.
Definition: gstr.cpp:180
static bool isInt(string_view s) noexcept
Returns true if the string can be converted into an integer without throwing an exception.
Definition: gstr.cpp:431
static void toUpper(std::string &s)
Replaces all seven-bit lower-case characters in string 's' by upper-case characters.
Definition: gstr.cpp:834
static unsigned long toULong(string_view s, Limited)
Converts string 's' to an unsigned long.
Definition: gstr.cpp:672
static std::string fromDouble(double d)
Converts double 'd' to a string.
Definition: gstr.cpp:473
static std::string tail(string_view in, std::size_t pos, string_view default_={})
Returns the last part of the string after the given position.
Definition: gstr.cpp:1325
static std::string fromULongLong(unsigned long long, const Hex &)
Converts an unsigned value to a lower-case hex string with no leading zeros.
Definition: gstr.h:641
static std::string head(string_view in, std::size_t pos, string_view default_={})
Returns the first part of the string up to just before the given position.
Definition: gstr.cpp:1297
static void splitIntoFields(string_view in, StringArray &out, char sep, char escape='\0', bool remove_escapes=true)
Splits the string into fields.
Definition: gstr.cpp:1194
static string_view fromULongLongToHex(unsigned long long, char *out) noexcept
Low-level conversion from an unsigned value to a lower-case hex string with no leading zeros.
Definition: gstr.cpp:797
static errno_t strncpy_s(char *dst, std::size_t n_dst, const char *src, std::size_t count) noexcept
Does the same as windows strncpy_s().
Definition: gstr.cpp:1493
static std::string trimmed(const std::string &s, string_view ws)
Returns a trim()med version of s.
Definition: gstr.cpp:343
static std::string fromLong(long l)
Converts long 'l' to a string.
Definition: gstr.h:604
static bool toBool(string_view s)
Converts string 's' to a bool.
Definition: gstr.cpp:484
static bool headMatch(const std::string &in, string_view head) noexcept
Returns true if the string has the given start (or head is empty).
Definition: gstr.cpp:1362
static string_view trimLeftView(string_view, string_view ws, std::size_t limit=0U) noexcept
Trims the lhs of s, taking off up to 'limit' of the 'ws' characters.
Definition: gstr.cpp:300
static string_view ws() noexcept
Returns a string of standard whitespace characters.
Definition: gstr.cpp:1268
static void escape(std::string &s, char c_escape, string_view specials_in, string_view specials_out)
Prefixes each occurrence of one of the special-in characters with the escape character and its corres...
Definition: gstr.cpp:100
static string_view trimRightView(string_view sv, string_view ws, std::size_t limit=0U) noexcept
Trims the rhs of s, taking off up to 'limit' of the 'ws' characters.
Definition: gstr.cpp:325
static std::string escaped(string_view, char c_escape, string_view specials_in, string_view specials_out)
Returns the escape()d string.
Definition: gstr.cpp:92
static std::string & trim(std::string &s, string_view ws)
Trims both ends of s, taking off any of the 'ws' characters.
Definition: gstr.cpp:338
A class like c++17's std::string_view.
Definition: gstringview.h:51
Low-level classes.
Definition: garg.h:30
std::vector< std::string > StringArray
A std::vector of std::strings.
Definition: gstringarray.h:30
constexpr const char * tx(const char *p)
A briefer alternative to G::gettext_noop().
Definition: ggettext.h:84
std::map< std::string, std::string > StringMap
A std::map of std::strings.
Definition: gstringmap.h:30
STL namespace.
Overload discrimiator for G::Str::toUWhatever() indicating hexadecimal strings.
Definition: gstr.h:59
Overload discrimiator for G::Str::toUWhatever() requesting a range-limited result.
Definition: gstr.h:56