1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/base/String.h
12 #ifndef ZYPP_BASE_STRING_H
13 #define ZYPP_BASE_STRING_H
21 #include <boost/format.hpp>
22 #include <boost/utility/string_ref.hpp>
24 #include "zypp/base/Easy.h"
25 #include "zypp/base/PtrTypes.h"
26 #include "zypp/base/Function.h"
28 ///////////////////////////////////////////////////////////////////
29 namespace boost { namespace logic { class tribool; } }
30 namespace zypp { typedef boost::logic::tribool TriBool; }
31 ///////////////////////////////////////////////////////////////////
33 ///////////////////////////////////////////////////////////////////
36 /** A formater with (N)o (A)rgument (C)heck.
37 * It won't complain about missing or excess arguments. Sometimes
38 * usefull when dealing with translations or classes providing a
41 inline format formatNAC( const std::string & string_r ) {
42 using namespace boost::io;
43 format fmter( string_r );
44 fmter.exceptions( all_error_bits ^ ( too_many_args_bit | too_few_args_bit ) );
48 namespace zypp { using boost::formatNAC; }
49 ///////////////////////////////////////////////////////////////////
51 ///////////////////////////////////////////////////////////////////
54 /** Request a human readable (translated) string representation of Tp [Tp.asUserString()]
55 * Classes may implement a default as member function.
58 std::string asUserString( const Tp & val_r )
59 { return val_r.asUserString(); }
62 ///////////////////////////////////////////////////////////////////
64 ///////////////////////////////////////////////////////////////////
66 { /////////////////////////////////////////////////////////////////
68 struct MessageString : public std::string
71 MessageString( const char * str_r ) : std::string( str_r ? str_r : "" ) {}
72 MessageString( const std::string & str_r ) : std::string( str_r ) {}
73 // boost::format, std::ostringstream, str::Str ...
75 MessageString( const TStr & str_r ) : std::string( str_r.str() ) {}
78 /** Convenience \c char* constructible from \c std::string and \c char*,
79 * it maps \c (char*)0 to an empty string.
82 * bool hasPrefix( const std::string & str_r, const std::string & prefix_r )
83 * { return( ::strncmp( str_r.c_str(), prefix_r.c_str(), prefix_r.size() ) == 0 ); }
86 * Called with a plain \c char* as argument, the \c std::string is created form
87 * for nothing. The implementation actually does not use the \c std::string.
89 * Best would be to implement \c hasPrefix for each combination of \c char*
90 * and \c std::string arguments:
93 * bool hasPrefix( const std::string & str_r, const std::string & prefix_r )
94 * { return( ::strncmp( str_r.c_str(), prefix_r.c_str(), prefix_r.size() ) == 0 ); }
96 * bool hasPrefix( const std::string & str_r, const char * prefix_r )
97 * { return( !prefix_r || ::strncmp( str_r.c_str(), prefix_r, ::strlen(prefix_r) ) == 0 ); }
99 * bool hasPrefix( const char * str_r, const std::string & prefix_r )
100 * { return( str_r ? ::strncmp( str_r, prefix_r.c_str(), prefix_r.size() ) == 0 : prefix_r.empty() ); }
102 * bool hasPrefix( const char * str_r, const char * prefix_r )
103 * { return( str && prefix_r ? ::strncmp( str_r, prefix_r, ::strlen(prefix_r) ) == 0
104 * : !((str_r && *str_r) || (prefix_r && *prefix_r)); }
107 * This is where \ref C_Str can help. Constructible from \c std::string and \c char*,
108 * it \e reduces the \c std::string to it's \c char*. At the same time it converts
109 * \c (char*)0 into an \c "" string.
112 * bool hasPrefix( const C_Str & str_r, const C_Str & prefix_r )
113 * { return( ::strncmp( str_r, prefix_r, prefix_r.size() ) == 0 ); }
116 * \todo Check whether to replace by boost::string_ref
121 typedef std::string::size_type size_type;
124 C_Str() : _val( 0 ), _sze( 0 ) {}
125 C_Str( char * c_str_r ) : _val( c_str_r ), _sze( std::string::npos ) {}
126 C_Str( const char * c_str_r ) : _val( c_str_r ), _sze( std::string::npos ) {}
127 C_Str( const std::string & str_r ) : _val( str_r.c_str() ), _sze( str_r.size() ) {}
128 C_Str( const boost::string_ref & str_r ) : _val( str_r.data() ), _sze( str_r.size() ) {}
131 bool isNull() const { return !_val; }
132 bool empty() const { return !(_val && *_val); }
133 size_type size() const
135 if ( _sze == std::string::npos )
136 { _sze = _val ? ::strlen( _val ) : 0; }
140 operator const char *() const { return c_str(); }
141 const char * c_str() const { return _val ? _val : ""; }
144 const char *const _val;
145 mutable size_type _sze;
148 /** \relates C_Str Stream output */
149 inline std::ostream & operator<<( std::ostream & str, const C_Str & obj )
150 { return str << obj.c_str(); }
152 ///////////////////////////////////////////////////////////////////
153 /** String related utilities and \ref ZYPP_STR_REGEX.
154 \see \ref ZYPP_STR_REGEX
158 { /////////////////////////////////////////////////////////////////
160 ///////////////////////////////////////////////////////////////////
162 * Global asString() that works with std::string too
164 inline const std::string & asString( const std::string & t )
167 #ifndef SWIG // Swig treats it as syntax error
168 inline std::string && asString( std::string && t )
169 { return std::move(t); }
172 inline std::string asString( const char * t )
175 inline std::string asString( char * t )
179 inline std::string asString( const Tp &t )
180 { return t.asString(); }
183 inline std::string asString( const intrusive_ptr<Tp> &p )
184 { return p->asString(); }
187 inline std::string asString( const weak_ptr<Tp> &p )
188 { return p->asString(); }
191 inline std::string asString( const bool &t )
192 { return t ? "true" : "false"; }
194 ///////////////////////////////////////////////////////////////////
195 /** Printf style construction of std::string. */
196 std::string form( const char * format, ... )
197 __attribute__ ((format (printf, 1, 2)));
199 ///////////////////////////////////////////////////////////////////
200 /** Return string describing the \a error_r code.
201 * Like ::strerror, but the numerical value is included in
202 * the string as well.
204 std::string strerror( int errno_r );
206 ///////////////////////////////////////////////////////////////////
207 /** Assert \c free called for allocated <tt>char *</tt>.
211 * vasprintf( &safe._buf, format, ap );
212 * return safe.asString();
220 SafeBuf() : _buf( 0 ) {}
221 ~SafeBuf() { if ( _buf ) free( _buf ); }
222 std::string asString() const
223 { return _buf ? std::string(_buf) : std::string(); }
226 ///////////////////////////////////////////////////////////////////
227 /** Convenient building of std::string via std::ostream::operator<<.
228 * Basically this is an \ref ostringstream which is autocenvertible
229 * into a \ref string.
231 * void fnc( const std::string & txt_r );
232 * fnc( str::Str() << "Hello " << 13 );
234 * std::string txt( str::Str() << 45 );
240 Str & operator<<( const Tp & val )
241 { _str << val; return *this; }
243 Str & operator<<( std::ostream& (*iomanip)( std::ostream& ) )
244 { _str << iomanip; return *this; }
246 operator std::string() const
247 { return _str.str(); }
249 std::string str() const
250 { return _str.str(); }
252 std::ostream & stream()
256 { _str.str( std::string() ); }
258 std::ostringstream _str;
261 inline std::ostream & operator<<( std::ostream & str, const Str & obj )
262 { return str << (std::string)obj; }
264 ///////////////////////////////////////////////////////////////////
265 /** \name String representation of number.
267 * Optional second argument sets the minimal string width (' ' padded).
268 * Negative values will cause the number to be left adjusted within the string.
270 * Default width is 0.
272 * numstring(42) -> "42"
273 * numstring(42, 4) -> " 42"
274 * numstring(42,-4) -> "42 "
278 inline std::string numstring( char n, int w = 0 ) { return form( "%*hhd", w, n ); }
279 inline std::string numstring( unsigned char n, int w = 0 ) { return form( "%*hhu", w, n ); }
280 inline std::string numstring( short n, int w = 0 ) { return form( "%*hd", w, n ); }
281 inline std::string numstring( unsigned short n, int w = 0 ) { return form( "%*hu", w, n ); }
282 inline std::string numstring( int n, int w = 0 ) { return form( "%*d", w, n ); }
283 inline std::string numstring( unsigned n, int w = 0 ) { return form( "%*u", w, n ); }
284 inline std::string numstring( long n, int w = 0 ) { return form( "%*ld", w, n ); }
285 inline std::string numstring( unsigned long n, int w = 0 ) { return form( "%*lu", w, n ); }
286 inline std::string numstring( long long n, int w = 0 ) { return form( "%*lld", w, n ); }
287 inline std::string numstring( unsigned long long n, int w = 0 ) { return form( "%*llu", w, n ); }
289 template<> inline std::string asString( const char & t ) { return numstring( t ); }
290 template<> inline std::string asString( const unsigned char & t ) { return numstring( t ); }
291 template<> inline std::string asString( const short & t ) { return numstring( t ); }
292 template<> inline std::string asString( const unsigned short & t ) { return numstring( t ); }
293 template<> inline std::string asString( const int & t ) { return numstring( t ); }
294 template<> inline std::string asString( const unsigned & t ) { return numstring( t ); }
295 template<> inline std::string asString( const long & t ) { return numstring( t ); }
296 template<> inline std::string asString( const unsigned long & t ) { return numstring( t ); }
297 template<> inline std::string asString( const long long & t ) { return numstring( t ); }
298 template<> inline std::string asString( const unsigned long long & t ) { return numstring( t ); }
301 ///////////////////////////////////////////////////////////////////
302 /** \name String representation of number as hex value with leading '0x'.
303 * Optional second argument sets the minimal
304 * string width (0 padded). Negative values will cause the number to be left adjusted
305 * within the string. Default width is 10 (4 for char).
307 * hexstring(42) -> "0x0000002a"
308 * hexstring(42, 4) -> "0x2a"
309 * hexstring(42,-4) -> "0x2a"
313 inline std::string hexstring( char n, int w = 4 ) { return form( "%#0*hhx", w, n ); }
314 inline std::string hexstring( unsigned char n, int w = 4 ) { return form( "%#0*hhx", w, n ); }
315 inline std::string hexstring( short n, int w = 10 ){ return form( "%#0*hx", w, n ); }
316 inline std::string hexstring( unsigned short n, int w = 10 ){ return form( "%#0*hx", w, n ); }
317 inline std::string hexstring( int n, int w = 10 ){ return form( "%#0*x", w, n ); }
318 inline std::string hexstring( unsigned n, int w = 10 ){ return form( "%#0*x", w, n ); }
319 inline std::string hexstring( long n, int w = 10 ){ return form( "%#0*lx", w, n ); }
320 inline std::string hexstring( unsigned long n, int w = 10 ){ return form( "%#0*lx", w, n ); }
321 inline std::string hexstring( long long n, int w = 0 ) { return form( "%#0*llx", w, n ); }
322 inline std::string hexstring( unsigned long long n, int w = 0 ) { return form( "%#0*llx", w, n ); }
325 ///////////////////////////////////////////////////////////////////
326 /** \name String representation of number as octal value with leading '0'.
327 * Optional second argument sets the minimal
328 * string width (0 padded). Negative values will cause the number to be left adjusted
329 * within the string. Default width is 5 (4 for char).
331 * octstring(42) -> "00052"
332 * octstring(42, 4) -> "0052"
333 * octstring(42,-4) -> "052 "
337 inline std::string octstring( char n, int w = 4 ) { return form( "%#0*hho", w, n ); }
338 inline std::string octstring( unsigned char n, int w = 4 ) { return form( "%#0*hho", w, n ); }
339 inline std::string octstring( short n, int w = 5 ) { return form( "%#0*ho", w, n ); }
340 inline std::string octstring( unsigned short n, int w = 5 ) { return form( "%#0*ho", w, n ); }
341 inline std::string octstring( int n, int w = 5 ) { return form( "%#0*o", w, n ); }
342 inline std::string octstring( unsigned n, int w = 5 ) { return form( "%#0*o", w, n ); }
343 inline std::string octstring( long n, int w = 5 ) { return form( "%#0*lo", w, n ); }
344 inline std::string octstring( unsigned long n, int w = 5 ) { return form( "%#0*lo", w, n ); }
345 inline std::string octstring( long long n, int w = 0 ) { return form( "%#0*llo", w, n ); }
346 inline std::string octstring( unsigned long long n, int w = 0 ) { return form( "%#0*llo", w, n ); }
349 ///////////////////////////////////////////////////////////////////
350 /** Parsing numbers from string.
353 /** String to integer type determined by template arg.
354 * \note Only specializations are defined.
356 * time_t t = strtonum<time_t>( "42" );
359 template<typename TInt>
360 TInt strtonum( const C_Str & str );
363 inline short strtonum( const C_Str & str ) { return ::strtol ( str, NULL, 0 ); }
365 inline int strtonum( const C_Str & str ) { return ::strtol ( str, NULL, 0 ); }
367 inline long strtonum( const C_Str & str ) { return ::strtol ( str, NULL, 0 ); }
369 inline long long strtonum( const C_Str & str ) { return ::strtoll ( str, NULL, 0 ); }
372 inline unsigned short strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
374 inline unsigned strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
376 inline unsigned long strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
378 inline unsigned long long strtonum( const C_Str & str ) { return ::strtoull( str, NULL, 0 ); }
380 /** String to integer type detemined 2nd function arg \a i.
382 * time_t t; strtonum( "42", t );
385 template<typename TInt>
386 inline TInt strtonum( const C_Str & str, TInt & i )
387 { return i = strtonum<TInt>( str ); }
390 ///////////////////////////////////////////////////////////////////
391 /** Parsing boolean from string.
394 /** Return \c true if str is <tt>1, true, yes, on</tt> (or a nonzero number). */
395 bool strToTrue( const C_Str & str );
397 /** Return \c false if str is <tt>0, false, no, off</tt>. */
398 bool strToFalse( const C_Str & str );
400 /** Parse \c str into a bool depending on the default value.
401 * If the \c default is true, look for a legal \c false string.
402 * If the \c default is false, look for a legal \c true string.
404 inline bool strToBool( const C_Str & str, bool default_r )
405 { return( default_r ? strToFalse( str ) : strToTrue( str ) ); }
407 /** Parse \c str into a bool if it's a legal \c true or \c false string.
408 * If \c str is not a recognized \c true or \c false string, \a return_r
411 inline bool strToBoolNodefault( const C_Str & str, bool & return_r )
413 if ( strToTrue( str ) ) return (return_r = true);
414 if ( !strToFalse( str ) ) return (return_r = false);
418 /** Parse \c str into a bool if it's a legal \c true or \c false string; else \c indterminate. */
419 TriBool strToTriBool( const C_Str & str );
424 * \short Return a string with all occurrences of \c from_r replaced with \c to_r.
426 std::string gsub( const std::string & str_r, const std::string & from_r, const std::string & to_r );
428 /** \overload A function is called on demand to compute each replacement value.
430 std::string gsubFun( const std::string & str_r, const std::string & from_r, function<std::string()> to_r );
433 * \short Replace all occurrences of \c from_r with \c to_r in \c str_r (inplace).
434 * A reference to \c str_r is also returned for convenience.
436 std::string & replaceAll( std::string & str_r, const std::string & from_r, const std::string & to_r );
438 /** \overload A function is called on demand to compute each replacement value.
440 std::string & replaceAllFun( std::string & str_r, const std::string & from_r, function<std::string()> to_r );
442 /** Enhance readability: insert gaps at regular distance
445 * Key Fingerprint: 22C07BA534178CD02EFE22AAB88B2FD43DBDC284
447 * Key Fingerprint: 22C07BA5 34178CD0 2EFE22AA B88B2FD4 3DBDC284
449 * Key Fingerprint: 22C0 7BA5 3417 8CD0 2EFE 22AA B88B 2FD4 3DBD C284
451 * Key Fingerprint: 22C0-7BA5-3417-8CD0-2EFE-22AA-B88B-2FD4-3DBD-C284
454 inline std::string gapify( std::string inp_r, std::string::size_type gap_r = 1, char gapchar = ' ' )
456 if ( gap_r && inp_r.size() > gap_r )
458 inp_r.reserve( inp_r.size() + (inp_r.size()-1)/gap_r );
459 for ( std::string::size_type pos = gap_r; pos < inp_r.size(); pos += gap_r+1 )
460 inp_r.insert( pos, 1, gapchar );
465 ///////////////////////////////////////////////////////////////////
468 /** Split \a line_r into words.
469 * Any sequence of characters in \a sepchars_r is treated as
470 * delimiter. The words are passed to OutputIterator \a result_r.
472 * std::vector<std::string> words;
473 * str::split( "some line", std::back_inserter(words) )
477 template<class TOutputIterator>
478 unsigned split( const C_Str & line_r, TOutputIterator result_r, const C_Str & sepchars_r = " \t" )
480 const char * beg = line_r;
481 const char * cur = beg;
482 // skip leading sepchars
483 while ( *cur && ::strchr( sepchars_r, *cur ) )
486 for ( beg = cur; *beg; beg = cur, ++result_r, ++ret )
489 while( *cur && !::strchr( sepchars_r, *cur ) )
492 *result_r = std::string( beg, cur-beg );
494 while ( *cur && ::strchr( sepchars_r, *cur ) )
500 /** Split \a line_r into words with respect to escape delimeters.
501 * Any sequence of characters in \a sepchars_r is treated as
502 * delimiter if not inside \c "" or \c '' or escaped by \c \.
504 * \li A non-quoted backslash (\) preserves the literal value of the next character.
505 * \li Enclosing characters in single quotes preserves the literal value of each
506 * character within the quotes. A single quote may not occur between single
507 * quotes, even when preceded by a backslash.
508 * \li Enclosing characters in double quotes preserves the literal value of all
509 * characters within the quotes, with the exception of \c \. The backslash
510 * retains its special meaning only when followed by \c " or \c \.
512 * The words are passed to OutputIterator \a result_r.
514 * \see \ref splitEscaped
517 * std::vector<std::string> words;
518 * str::splitEscaped( "some line", std::back_inserter(words) )
522 * example splitted strings
523 * normal line -> 2 elements ( "normal", "line" )
524 * escaped\ line -> 1 element(escaped line)
525 * "quoted line" -> 1 element same as above
526 * 'quoted line' -> 1 element same as above
527 * "escaped quote\"" -> 1 element (escaped quote")
529 * \param line_r The string to parse.
531 * \param sepchars_r String of separator characters.
532 * \param withEmpty Whether to include empty fields between separators in the result.
536 template<class TOutputIterator>
537 unsigned splitEscaped( const C_Str & line_r, TOutputIterator result_r, const C_Str & sepchars_r = " \t", bool withEmpty = false)
539 const char * beg = line_r;
540 const char * cur = beg;
543 // skip leading sepchars
544 while ( *cur && ::strchr( sepchars_r, *cur ) )
554 // there were only sepchars in the string
555 if (!*cur && withEmpty)
561 // after the leading sepchars
562 enum class Quote { None, Slash, Single, Double, DoubleSlash };
563 std::vector<char> buf;
564 Quote quoting = Quote::None;
565 for ( beg = cur; *beg; beg = cur, ++result_r, ++ret )
567 // read next value until unquoted sepchar
569 quoting = Quote::None;
576 case '\\': quoting = Quote::Slash; break;
577 case '\'': quoting = Quote::Single; break;
578 case '"': quoting = Quote::Double; break;
579 default: buf.push_back( *cur ); break;
584 buf.push_back( *cur );
585 quoting = Quote::None;
591 case '\'': quoting = Quote::None; break;
592 default: buf.push_back( *cur ); break;
599 case '\"': quoting = Quote::None; break;
600 case '\\': quoting = Quote::DoubleSlash; break;
601 default: buf.push_back( *cur ); break;
605 case Quote::DoubleSlash:
608 case '\"': /*fallthrough*/
609 case '\\': buf.push_back( *cur ); break;
611 buf.push_back( '\\' );
612 buf.push_back( *cur );
615 quoting = Quote::Double;
619 } while ( *cur && ( quoting != Quote::None || !::strchr( sepchars_r, *cur ) ) );
620 *result_r = std::string( buf.begin(), buf.end() );
624 if ( *cur && ::strchr( sepchars_r, *cur ) )
626 while ( *cur && ::strchr( sepchars_r, *cur ) )
635 // the last was a separator => one more field
636 if ( !*cur && withEmpty && ::strchr( sepchars_r, *(cur-1) ) )
645 /** Split \a line_r into fields.
646 * Any single character in \a sepchars_r is treated as a
647 * field separator unless \-escaped. The words are passed
654 * ":a" -> words 2 ||a|
655 * "a:" -> words 2 |a||
656 * ":a:" -> words 3 ||a||
661 * std::vector<std::string> words;
662 * str::split( "some line", std::back_inserter(words) )
666 template<class TOutputIterator>
667 unsigned splitFields( const C_Str & line_r, TOutputIterator result_r, const C_Str & sepchars_r = ":" )
669 const char * beg = line_r;
670 const char * cur = beg;
672 for ( beg = cur; *beg; beg = cur, ++result_r )
675 while( *cur && !::strchr( sepchars_r, *cur ) )
677 if ( *cur == '\\' && *(cur+1) )
682 *result_r = std::string( beg, cur-beg );
688 if ( ! *cur ) // ending with sepchar
690 *result_r = std::string(); // add final empty field
700 * Split \a line_r into fields handling also escaped separators.
703 * \see splitEscaped()
705 template<class TOutputIterator>
706 unsigned splitFieldsEscaped( const C_Str & line_r, TOutputIterator result_r, const C_Str & sepchars_r = ":" )
708 return splitEscaped( line_r, result_r, sepchars_r, true /* withEmpty */ );
713 ///////////////////////////////////////////////////////////////////
716 /** Join strings using separator \a sep_r (defaults to BLANK). */
717 template <class TIterator>
718 std::string join( TIterator begin, TIterator end, const C_Str & sep_r = " " )
721 for ( TIterator iter = begin; iter != end; ++ iter )
725 res += asString(*iter);
730 /** Join strings using separator \a sep_r (defaults to BLANK). */
731 template <class TContainer>
732 std::string join( const TContainer & cont_r, const C_Str & sep_r = " " )
733 { return join( cont_r.begin(), cont_r.end(), sep_r ); }
735 /** Join strings using separator \a sep_r, quoting or escaping the values.
736 * Separator defaults to BLANK. Use \ref splitEscaped to restore the
739 template <class TIterator>
740 std::string joinEscaped( TIterator begin, TIterator end, const char sep_r = ' ' )
742 std::vector<char> buf;
743 for ( TIterator iter = begin; iter != end; ++ iter )
746 buf.push_back( sep_r );
750 // empty string goes ""
751 buf.push_back( '"' );
752 buf.push_back( '"' );
756 std::string toadd( asString(*iter) );
757 for_( ch, toadd.begin(), toadd.end() )
764 buf.push_back( '\\' );
765 buf.push_back( *ch );
769 buf.push_back( '\\' );
770 buf.push_back( *ch );
775 return std::string( buf.begin(), buf.end() );
780 ///////////////////////////////////////////////////////////////////
783 /** Indent by string [" "] optionally wrap.
784 * Prints nothing for an empty string. Asserts a trainling '\n' on
785 * the last line. Optionally wrap lines at ' ' at a given length.
787 inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, const std::string & indent_r = " ", unsigned maxWitdh_r = 0 )
791 if ( indent_r.size() >= maxWitdh_r )
792 maxWitdh_r = 0; // nonsense: indent larger than line witdh
794 maxWitdh_r -= indent_r.size();
797 for ( const char * e = text_r.c_str(), * s = e; *e; s = ++e )
799 for ( ; *e && *e != '\n'; ++e ) ;/*searching*/
801 if ( maxWitdh_r && width > maxWitdh_r )
805 for ( e = s+width; e > s && *e != ' '; --e ) ;/*searching*/
807 width = e-s; // on a ' ', replaced by '\n'
809 e = s+width-1; // cut line;
812 str.write( s, width );
814 if ( !*e ) // on '\0'
819 /** \overload Indent by number of chars [' '] optionally wrap. */
820 inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, unsigned indent_r, char indentch_r = ' ', unsigned maxWitdh_r = 0 )
821 { return printIndented( str, text_r, std::string( indent_r, indentch_r ), maxWitdh_r ); }
822 /** \overload Indent by number of chars [' '] wrap. */
823 inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, unsigned indent_r, unsigned maxWitdh_r, char indentch_r = ' ' )
824 { return printIndented( str, text_r, std::string( indent_r, indentch_r ), maxWitdh_r ); }
826 /** Prefix lines by string computed by function taking line begin/end [std::string(const char*, const char*)]
827 * Prints nothing for an empty string. Asserts a trainling '\n' on the last line.
829 inline std::ostream & autoPrefix( std::ostream & str, const std::string & text_r, function<std::string(const char*, const char*)> fnc_r )
831 for ( const char * e = text_r.c_str(); *e; ++e )
834 for ( ; *e && *e != '\n'; ++e ) /*searching*/;
835 str << fnc_r( s, e );
838 if ( !*e ) // on '\0'
843 /** \overload Prefix lines by string generated by function [std::string()] */
844 inline std::ostream & autoPrefix0( std::ostream & str, const std::string & text_r, function<std::string()> fnc_r )
846 auto wrap = [&fnc_r]( const char*, const char* )-> std::string {
849 return autoPrefix( str, text_r, wrap );
852 ///////////////////////////////////////////////////////////////////
856 * Escape desired character \a c using a backslash.
858 * For use when printing \a c separated values, and where
859 * \ref joinEscaped() is too heavy.
861 std::string escape( const C_Str & str_r, const char c = ' ' );
863 /** Escape \a next_r and append it to \a str_r using separator \a sep_r. */
864 inline void appendEscaped( std::string & str_r, const C_Str & next_r, const char sep_r = ' ' )
866 if ( ! str_r.empty() )
868 if ( next_r.empty() )
871 str_r += escape( next_r, sep_r );
877 ///////////////////////////////////////////////////////////////////
878 ///////////////////////////////////////////////////////////////////
880 * Encode all characters other than [a-zA-Z0-9] as %XX.
881 * This includes the % character itself, which becomes %25.
884 /** Encode all characters other than [a-zA-Z0-9] as %XX.
885 * This includes the % character itself, which becomes %25.
887 std::string hexencode( const C_Str & str_r );
888 /** Decode hexencoded %XX sequences. */
889 std::string hexdecode( const C_Str & str_r );
891 ///////////////////////////////////////////////////////////////////
893 /** \name Case conversion. */
895 /** Return lowercase version of \a s
898 std::string toLower( const std::string & s );
900 inline std::string toLower( const char * s )
901 { return( s ? toLower( std::string(s) ) : std::string() ); }
903 /** Return uppercase version of \a s
906 std::string toUpper( const std::string & s );
908 inline std::string toUpper( const char * s )
909 { return( s ? toUpper( std::string(s) ) : std::string() ); }
913 /** \name Case insensitive comparison. */
915 inline int compareCI( const C_Str & lhs, const C_Str & rhs )
916 { return ::strcasecmp( lhs, rhs ); }
919 /** \name Locate substring. */
921 /** Locate substring case sensitive. */
922 inline bool contains( const C_Str & str_r, const C_Str & val_r )
923 { return ::strstr( str_r, val_r ); }
924 /** Locate substring case insensitive. */
925 inline bool containsCI( const C_Str & str_r, const C_Str & val_r )
926 { return ::strcasestr( str_r, val_r ); }
929 ///////////////////////////////////////////////////////////////////
930 /** \name Trimming whitepace.
931 * \todo optimize l/r trim.
934 /** To define how to trim. */
939 TRIM = (L_TRIM|R_TRIM)
942 std::string trim( const std::string & s, const Trim trim_r = TRIM );
944 inline std::string ltrim( const std::string & s )
945 { return trim( s, L_TRIM ); }
947 inline std::string rtrim( const std::string & s )
948 { return trim( s, R_TRIM ); }
951 std::string stripFirstWord( std::string & line, const bool ltrim_first = true );
953 std::string stripLastWord( std::string & line, const bool rtrim_first = true );
955 /** Return stream content up to (but not returning) the next newline.
956 * \see \ref receiveUpTo
958 std::string getline( std::istream & str, bool trim = false );
960 /** Return stream content up to (but not returning) the next newline.
961 * \see \ref receiveUpTo
963 std::string getline( std::istream & str, const Trim trim_r );
965 /** Return stream content up to the next ocurrence of \c delim_r or EOF
966 * \c delim_r, if found, is always read from the stream. Whether it is
967 * also returned in the string depends on \c returnDelim_r.
968 * If the stream status is \c good, \c delim_r was found in the stream.
969 * If we reached EOF while looking for \c delim_r, \c eof is set; and
970 * also \c fail, if we did not read any data before.
972 std::string receiveUpTo( std::istream & str, const char delim_r, bool returnDelim_r = false );
974 ///////////////////////////////////////////////////////////////////
976 /** \name String prefix/suffix handling.
979 /** Return whether \a str_r has prefix \a prefix_r. */
980 inline bool hasPrefix( const C_Str & str_r, const C_Str & prefix_r )
981 { return( ::strncmp( str_r, prefix_r, prefix_r.size() ) == 0 ); }
983 /** Strip a \a prefix_r from \a str_r and return the resulting string. */
984 inline std::string stripPrefix( const C_Str & str_r, const C_Str & prefix_r )
985 { return( hasPrefix( str_r, prefix_r ) ? str_r + prefix_r.size() : str_r.c_str() ); }
987 /** Return whether \a str_r has suffix \a suffix_r. */
988 inline bool hasSuffix( const C_Str & str_r, const C_Str & suffix_r )
989 { return( str_r.size() >= suffix_r.size() && ::strncmp( str_r + str_r.size() - suffix_r.size() , suffix_r, suffix_r.size() ) == 0 ); }
991 /** Strip a \a suffix_r from \a str_r and return the resulting string. */
992 inline std::string stripSuffix( const C_Str & str_r, const C_Str & suffix_r )
994 if ( hasSuffix( str_r, suffix_r ) )
995 return std::string( str_r, str_r.size() - suffix_r.size() );
996 return str_r.c_str();
998 /** Return size of the common prefix of \a lhs and \a rhs. */
999 inline std::string::size_type commonPrefix( const C_Str & lhs, const C_Str & rhs )
1001 const char * lp = lhs.c_str();
1002 const char * rp = rhs.c_str();
1003 std::string::size_type ret = 0;
1004 while ( *lp == *rp && *lp != '\0' )
1005 { ++lp, ++rp, ++ret; }
1009 /** alias for \ref hasPrefix */
1010 inline bool startsWith( const C_Str & str_r, const C_Str & prefix_r )
1011 { return hasPrefix( str_r, prefix_r ); }
1012 /** alias for \ref hasSuffix */
1013 inline bool endsWith( const C_Str & str_r, const C_Str & prefix_r )
1014 { return hasSuffix( str_r, prefix_r ); }
1017 ///////////////////////////////////////////////////////////////////
1019 // drag into zypp:: namespace
1020 using str::asString;
1023 ///////////////////////////////////////////////////////////////////
1024 #endif // ZYPP_BASE_STRING_H