E-MailRelay

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