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>
23 #include "zypp/base/Easy.h"
24 #include "zypp/base/PtrTypes.h"
25 #include "zypp/base/Function.h"
27 ///////////////////////////////////////////////////////////////////
28 namespace boost { namespace logic { class tribool; } }
29 namespace zypp { typedef boost::logic::tribool TriBool; }
30 ///////////////////////////////////////////////////////////////////
32 ///////////////////////////////////////////////////////////////////
35 /** Request a human readable (translated) string representation of _Tp [_Tp.asUserString()]
36 * Classes may implement a default as member function.
39 std::string asUserString( const _Tp & val_r )
40 { return val_r.asUserString(); }
43 ///////////////////////////////////////////////////////////////////
45 ///////////////////////////////////////////////////////////////////
47 { /////////////////////////////////////////////////////////////////
49 struct MessageString : public std::string
52 MessageString( const char * str_r ) : std::string( str_r ? str_r : "" ) {}
53 MessageString( const std::string & str_r ) : std::string( str_r ) {}
54 // boost::format, std::ostringstream, str::Str ...
56 MessageString( const _Str & str_r ) : std::string( str_r.str() ) {}
59 /** Convenience \c char* constructible from \c std::string and \c char*,
60 * it maps \c (char*)0 to an empty string.
63 * bool hasPrefix( const std::string & str_r, const std::string & prefix_r )
64 * { return( ::strncmp( str_r.c_str(), prefix_r.c_str(), prefix_r.size() ) == 0 ); }
67 * Called with a plain \c char* as argument, the \c std::string is created form
68 * for nothing. The implementation actually does not use the \c std::string.
70 * Best would be to implement \c hasPrefix for each combination of \c char*
71 * and \c std::string arguments:
74 * bool hasPrefix( const std::string & str_r, const std::string & prefix_r )
75 * { return( ::strncmp( str_r.c_str(), prefix_r.c_str(), prefix_r.size() ) == 0 ); }
77 * bool hasPrefix( const std::string & str_r, const char * prefix_r )
78 * { return( !prefix_r || ::strncmp( str_r.c_str(), prefix_r, ::strlen(prefix_r) ) == 0 ); }
80 * bool hasPrefix( const char * str_r, const std::string & prefix_r )
81 * { return( str_r ? ::strncmp( str_r, prefix_r.c_str(), prefix_r.size() ) == 0 : prefix_r.empty() ); }
83 * bool hasPrefix( const char * str_r, const char * prefix_r )
84 * { return( str && prefix_r ? ::strncmp( str_r, prefix_r, ::strlen(prefix_r) ) == 0
85 * : !((str_r && *str_r) || (prefix_r && *prefix_r)); }
88 * This is where \ref C_Str can help. Constructible from \c std::string and \c char*,
89 * it \e reduces the \c std::string to it's \c char*. At the same time it converts
90 * \c (char*)0 into an \c "" string.
93 * bool hasPrefix( const C_Str & str_r, const C_Str & prefix_r )
94 * { return( ::strncmp( str_r, prefix_r, prefix_r.size() ) == 0 ); }
100 typedef std::string::size_type size_type;
103 C_Str() : _val( 0 ), _sze( 0 ) {}
104 C_Str( char * c_str_r ) : _val( c_str_r ), _sze( std::string::npos ) {}
105 C_Str( const char * c_str_r ) : _val( c_str_r ), _sze( std::string::npos ) {}
106 C_Str( const std::string & str_r ) : _val( str_r.c_str() ), _sze( str_r.size() ) {}
109 bool isNull() const { return !_val; }
110 bool empty() const { return !(_val && *_val); }
111 size_type size() const
113 if ( _sze == std::string::npos )
114 { _sze = _val ? ::strlen( _val ) : 0; }
118 operator const char *() const { return c_str(); }
119 const char * c_str() const { return _val ? _val : ""; }
122 const char *const _val;
123 mutable size_type _sze;
126 /** \relates C_Str Stream output */
127 inline std::ostream & operator<<( std::ostream & str, const C_Str & obj )
128 { return str << obj.c_str(); }
130 ///////////////////////////////////////////////////////////////////
131 /** String related utilities and \ref ZYPP_STR_REGEX.
132 \see \ref ZYPP_STR_REGEX
136 { /////////////////////////////////////////////////////////////////
138 ///////////////////////////////////////////////////////////////////
140 * Global asString() that works with std::string too
142 inline std::string asString( const std::string &t )
145 #ifndef SWIG // Swig treats it as syntax error
146 inline std::string asString( std::string && t )
147 { return std::move(t); }
150 inline std::string asString( const char * t )
153 inline std::string asString( char * t )
157 inline std::string asString( const _T &t )
158 { return t.asString(); }
161 inline std::string asString( const intrusive_ptr<_T> &p )
162 { return p->asString(); }
165 inline std::string asString( const weak_ptr<_T> &p )
166 { return p->asString(); }
169 inline std::string asString( const bool &t )
170 { return t ? "true" : "false"; }
172 ///////////////////////////////////////////////////////////////////
173 /** Printf style construction of std::string. */
174 std::string form( const char * format, ... )
175 __attribute__ ((format (printf, 1, 2)));
177 ///////////////////////////////////////////////////////////////////
178 /** Return string describing the \a error_r code.
179 * Like ::strerror, but the numerical value is included in
180 * the string as well.
182 std::string strerror( int errno_r );
184 ///////////////////////////////////////////////////////////////////
185 /** Assert \c free called for allocated <tt>char *</tt>.
189 * vasprintf( &safe._buf, format, ap );
190 * return safe.asString();
198 SafeBuf() : _buf( 0 ) {}
199 ~SafeBuf() { if ( _buf ) free( _buf ); }
200 std::string asString() const
201 { return _buf ? std::string(_buf) : std::string(); }
204 ///////////////////////////////////////////////////////////////////
206 /// \brief Convenient building of std::string via \ref std::ostringstream
207 /// Basically a \ref std::ostringstream autoconvertible to \ref std::string
208 /// for building string arguments.
210 /// void fnc( const std::string & txt_r );
211 /// fnc( str::Str() << "Hello " << 13 );
213 /// std::string txt( str::Str() << 45 );
215 ///////////////////////////////////////////////////////////////////
219 Str & operator<<( const Tp & val )
220 { _str << val; return *this; }
222 Str & operator<<( std::ostream& (*iomanip)( std::ostream& ) )
223 { _str << iomanip; return *this; }
225 operator std::string() const { return _str.str(); }
226 std::string asString() const { return _str.str(); }
227 std::string str() const { return _str.str(); }
229 const std::ostream & stream() const { return _str; }
230 std::ostream & stream() { return _str; }
232 void clear() { _str.str( std::string() ); }
235 std::ostringstream _str;
238 /** \relates Str Stream output */
239 inline std::ostream & operator<<( std::ostream & str, const Str & obj )
240 { return str << obj.str(); }
242 ///////////////////////////////////////////////////////////////////
244 /// \brief Convenient building of std::string with \ref boost::format.
245 /// Basically a \ref boost::format autoconvertible to \ref std::string
246 /// for building string arguments.
248 /// void fnc( const std::string & txt_r );
249 /// fnc( str::Format("Hello %1%") % 13 );
251 /// std::string txt( str::Format("Hello %1%") % 13 );
253 ///////////////////////////////////////////////////////////////////
257 Format( const std::string & format_r ) : _fmter( format_r ) {}
260 Format & operator%( Tp && arg )
261 { _fmter % std::forward<Tp>(arg); return *this; }
263 operator std::string() const { return _fmter.str(); }
264 std::string asString() const { return _fmter.str(); }
265 std::string str() const { return _fmter.str(); }
267 const boost::format & fmter() const { return _fmter; }
268 boost::format & fmter() { return _fmter; }
271 boost::format _fmter;
274 /** \relates Format Stream output */
275 inline std::ostream & operator<<( std::ostream & str, const Format & obj )
276 { return str << obj.fmter(); }
278 ///////////////////////////////////////////////////////////////////
280 /// \brief \ref Format with (N)o (A)rgument (C)heck.
281 /// It won't complain about missing or excess arguments. Sometimes
282 /// usefull when dealing with translations or classes providing a
283 /// default formater.
284 ///////////////////////////////////////////////////////////////////
285 struct FormatNAC : public Format
287 FormatNAC() { relax(); }
288 FormatNAC( const std::string & format_r ) : Format( format_r ) { relax(); }
293 using namespace boost::io;
294 _fmter.exceptions( all_error_bits ^ ( too_many_args_bit | too_few_args_bit ) );
297 ///////////////////////////////////////////////////////////////////
298 /** \name String representation of number.
300 * Optional second argument sets the minimal string width (' ' padded).
301 * Negative values will cause the number to be left adjusted within the string.
303 * Default width is 0.
305 * numstring(42) -> "42"
306 * numstring(42, 4) -> " 42"
307 * numstring(42,-4) -> "42 "
311 inline std::string numstring( char n, int w = 0 ) { return form( "%*hhd", w, n ); }
312 inline std::string numstring( unsigned char n, int w = 0 ) { return form( "%*hhu", w, n ); }
313 inline std::string numstring( short n, int w = 0 ) { return form( "%*hd", w, n ); }
314 inline std::string numstring( unsigned short n, int w = 0 ) { return form( "%*hu", w, n ); }
315 inline std::string numstring( int n, int w = 0 ) { return form( "%*d", w, n ); }
316 inline std::string numstring( unsigned n, int w = 0 ) { return form( "%*u", w, n ); }
317 inline std::string numstring( long n, int w = 0 ) { return form( "%*ld", w, n ); }
318 inline std::string numstring( unsigned long n, int w = 0 ) { return form( "%*lu", w, n ); }
319 inline std::string numstring( long long n, int w = 0 ) { return form( "%*lld", w, n ); }
320 inline std::string numstring( unsigned long long n, int w = 0 ) { return form( "%*llu", w, n ); }
322 template<> inline std::string asString( const char & t ) { return numstring( t ); }
323 template<> inline std::string asString( const unsigned char & t ) { return numstring( t ); }
324 template<> inline std::string asString( const short & t ) { return numstring( t ); }
325 template<> inline std::string asString( const unsigned short & t ) { return numstring( t ); }
326 template<> inline std::string asString( const int & t ) { return numstring( t ); }
327 template<> inline std::string asString( const unsigned & t ) { return numstring( t ); }
328 template<> inline std::string asString( const long & t ) { return numstring( t ); }
329 template<> inline std::string asString( const unsigned long & t ) { return numstring( t ); }
330 template<> inline std::string asString( const long long & t ) { return numstring( t ); }
331 template<> inline std::string asString( const unsigned long long & t ) { return numstring( t ); }
334 ///////////////////////////////////////////////////////////////////
335 /** \name String representation of number as hex value with leading '0x'.
336 * Optional second argument sets the minimal
337 * string width (0 padded). Negative values will cause the number to be left adjusted
338 * within the string. Default width is 10 (4 for char).
340 * hexstring(42) -> "0x0000002a"
341 * hexstring(42, 4) -> "0x2a"
342 * hexstring(42,-4) -> "0x2a"
346 inline std::string hexstring( char n, int w = 4 ) { return form( "%#0*hhx", w, n ); }
347 inline std::string hexstring( unsigned char n, int w = 4 ) { return form( "%#0*hhx", w, n ); }
348 inline std::string hexstring( short n, int w = 10 ){ return form( "%#0*hx", w, n ); }
349 inline std::string hexstring( unsigned short n, int w = 10 ){ return form( "%#0*hx", w, n ); }
350 inline std::string hexstring( int n, int w = 10 ){ return form( "%#0*x", w, n ); }
351 inline std::string hexstring( unsigned n, int w = 10 ){ return form( "%#0*x", w, n ); }
352 inline std::string hexstring( long n, int w = 10 ){ return form( "%#0*lx", w, n ); }
353 inline std::string hexstring( unsigned long n, int w = 10 ){ return form( "%#0*lx", w, n ); }
354 inline std::string hexstring( long long n, int w = 0 ) { return form( "%#0*llx", w, n ); }
355 inline std::string hexstring( unsigned long long n, int w = 0 ) { return form( "%#0*llx", w, n ); }
358 ///////////////////////////////////////////////////////////////////
359 /** \name String representation of number as octal value with leading '0'.
360 * Optional second argument sets the minimal
361 * string width (0 padded). Negative values will cause the number to be left adjusted
362 * within the string. Default width is 5 (4 for char).
364 * octstring(42) -> "00052"
365 * octstring(42, 4) -> "0052"
366 * octstring(42,-4) -> "052 "
370 inline std::string octstring( char n, int w = 4 ) { return form( "%#0*hho", w, n ); }
371 inline std::string octstring( unsigned char n, int w = 4 ) { return form( "%#0*hho", w, n ); }
372 inline std::string octstring( short n, int w = 5 ) { return form( "%#0*ho", w, n ); }
373 inline std::string octstring( unsigned short n, int w = 5 ) { return form( "%#0*ho", w, n ); }
374 inline std::string octstring( int n, int w = 5 ) { return form( "%#0*o", w, n ); }
375 inline std::string octstring( unsigned n, int w = 5 ) { return form( "%#0*o", w, n ); }
376 inline std::string octstring( long n, int w = 5 ) { return form( "%#0*lo", w, n ); }
377 inline std::string octstring( unsigned long n, int w = 5 ) { return form( "%#0*lo", w, n ); }
378 inline std::string octstring( long long n, int w = 0 ) { return form( "%#0*llo", w, n ); }
379 inline std::string octstring( unsigned long long n, int w = 0 ) { return form( "%#0*llo", w, n ); }
382 ///////////////////////////////////////////////////////////////////
383 /** Parsing numbers from string.
386 /** String to integer type determined by template arg.
387 * \note Only specializations are defined.
389 * time_t t = strtonum<time_t>( "42" );
392 template<typename _It>
393 _It strtonum( const C_Str & str );
396 inline short strtonum( const C_Str & str ) { return ::strtol ( str, NULL, 0 ); }
398 inline int strtonum( const C_Str & str ) { return ::strtol ( str, NULL, 0 ); }
400 inline long strtonum( const C_Str & str ) { return ::strtol ( str, NULL, 0 ); }
402 inline long long strtonum( const C_Str & str ) { return ::strtoll ( str, NULL, 0 ); }
405 inline unsigned short strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
407 inline unsigned strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
409 inline unsigned long strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
411 inline unsigned long long strtonum( const C_Str & str ) { return ::strtoull( str, NULL, 0 ); }
413 /** String to integer type detemined 2nd function arg \a i.
415 * time_t t; strtonum( "42", t );
418 template<typename _It>
419 inline _It strtonum( const C_Str & str, _It & i )
420 { return i = strtonum<_It>( str ); }
423 ///////////////////////////////////////////////////////////////////
424 /** Parsing boolean from string.
427 /** Return \c true if str is <tt>1, true, yes, on</tt> (or a nonzero number). */
428 bool strToTrue( const C_Str & str );
430 /** Return \c false if str is <tt>0, false, no, off</tt>. */
431 bool strToFalse( const C_Str & str );
433 /** Parse \c str into a bool depending on the default value.
434 * If the \c default is true, look for a legal \c false string.
435 * If the \c default is false, look for a legal \c true string.
437 inline bool strToBool( const C_Str & str, bool default_r )
438 { return( default_r ? strToFalse( str ) : strToTrue( str ) ); }
440 /** Parse \c str into a bool if it's a legal \c true or \c false string.
441 * If \c str is not a recognized \c true or \c false string, \a return_r
444 inline bool strToBoolNodefault( const C_Str & str, bool & return_r )
446 if ( strToTrue( str ) ) return (return_r = true);
447 if ( !strToFalse( str ) ) return (return_r = false);
451 /** Parse \c str into a bool if it's a legal \c true or \c false string; else \c indterminate. */
452 TriBool strToTriBool( const C_Str & str );
457 * \short Return a string with all occurrences of \c from_r replaced with \c to_r.
459 std::string gsub( const std::string & str_r, const std::string & from_r, const std::string & to_r );
461 /** \overload A function is called on demand to compute each replacement value.
463 std::string gsubFun( const std::string & str_r, const std::string & from_r, function<std::string()> to_r );
466 * \short Replace all occurrences of \c from_r with \c to_r in \c str_r (inplace).
467 * A reference to \c str_r is also returned for convenience.
469 std::string & replaceAll( std::string & str_r, const std::string & from_r, const std::string & to_r );
471 /** \overload A function is called on demand to compute each replacement value.
473 std::string & replaceAllFun( std::string & str_r, const std::string & from_r, function<std::string()> to_r );
475 /** Enhance readability: insert gaps at regular distance
478 * Key Fingerprint: 22C07BA534178CD02EFE22AAB88B2FD43DBDC284
480 * Key Fingerprint: 22C07BA5 34178CD0 2EFE22AA B88B2FD4 3DBDC284
482 * Key Fingerprint: 22C0 7BA5 3417 8CD0 2EFE 22AA B88B 2FD4 3DBD C284
484 * Key Fingerprint: 22C0-7BA5-3417-8CD0-2EFE-22AA-B88B-2FD4-3DBD-C284
487 inline std::string gapify( std::string inp_r, std::string::size_type gap_r = 1, char gapchar = ' ' )
489 if ( gap_r && inp_r.size() > gap_r )
491 inp_r.reserve( inp_r.size() + (inp_r.size()-1)/gap_r );
492 for ( std::string::size_type pos = gap_r; pos < inp_r.size(); pos += gap_r+1 )
493 inp_r.insert( pos, 1, gapchar );
498 ///////////////////////////////////////////////////////////////////
501 /** Split \a line_r into words.
502 * Any sequence of characters in \a sepchars_r is treated as
503 * delimiter. The words are passed to OutputIterator \a result_r.
505 * std::vector<std::string> words;
506 * str::split( "some line", std::back_inserter(words) )
510 template<class _OutputIterator>
511 unsigned split( const C_Str & line_r,
512 _OutputIterator result_r,
513 const C_Str & sepchars_r = " \t" )
515 const char * beg = line_r;
516 const char * cur = beg;
517 // skip leading sepchars
518 while ( *cur && ::strchr( sepchars_r, *cur ) )
521 for ( beg = cur; *beg; beg = cur, ++result_r, ++ret )
524 while( *cur && !::strchr( sepchars_r, *cur ) )
527 *result_r = std::string( beg, cur-beg );
529 while ( *cur && ::strchr( sepchars_r, *cur ) )
535 /** Split \a line_r into words with respect to escape delimeters.
536 * Any sequence of characters in \a sepchars_r is treated as
537 * delimiter if not inside \c "" or \c '' or escaped by \c \.
539 * \li A non-quoted backslash (\) preserves the literal value of the next character.
540 * \li Enclosing characters in single quotes preserves the literal value of each
541 * character within the quotes. A single quote may not occur between single
542 * quotes, even when preceded by a backslash.
543 * \li Enclosing characters in double quotes preserves the literal value of all
544 * characters within the quotes, with the exception of \c \. The backslash
545 * retains its special meaning only when followed by \c " or \c \.
547 * The words are passed to OutputIterator \a result_r.
549 * \see \ref splitEscaped
552 * std::vector<std::string> words;
553 * str::splitEscaped( "some line", std::back_inserter(words) )
557 * example splitted strings
558 * normal line -> 2 elements ( "normal", "line" )
559 * escaped\ line -> 1 element(escaped line)
560 * "quoted line" -> 1 element same as above
561 * 'quoted line' -> 1 element same as above
562 * "escaped quote\"" -> 1 element (escaped quote")
564 * \param line_r The string to parse.
566 * \param sepchars_r String of separator characters.
567 * \param withEmpty Whether to include empty fields between separators in the result.
571 template<class _OutputIterator>
572 unsigned splitEscaped( const C_Str & line_r,
573 _OutputIterator result_r,
574 const C_Str & sepchars_r = " \t",
575 bool withEmpty = false)
577 const char * beg = line_r;
578 const char * cur = beg;
581 // skip leading sepchars
582 while ( *cur && ::strchr( sepchars_r, *cur ) )
592 // there were only sepchars in the string
593 if (!*cur && withEmpty)
599 // after the leading sepchars
600 enum class Quote { None, Slash, Single, Double, DoubleSlash };
601 std::vector<char> buf;
602 Quote quoting = Quote::None;
603 for ( beg = cur; *beg; beg = cur, ++result_r, ++ret )
605 // read next value until unquoted sepchar
607 quoting = Quote::None;
614 case '\\': quoting = Quote::Slash; break;
615 case '\'': quoting = Quote::Single; break;
616 case '"': quoting = Quote::Double; break;
617 default: buf.push_back( *cur ); break;
622 buf.push_back( *cur );
623 quoting = Quote::None;
629 case '\'': quoting = Quote::None; break;
630 default: buf.push_back( *cur ); break;
637 case '\"': quoting = Quote::None; break;
638 case '\\': quoting = Quote::DoubleSlash; break;
639 default: buf.push_back( *cur ); break;
643 case Quote::DoubleSlash:
646 case '\"': /*fallthrough*/
647 case '\\': buf.push_back( *cur ); break;
649 buf.push_back( '\\' );
650 buf.push_back( *cur );
653 quoting = Quote::Double;
657 } while ( *cur && ( quoting != Quote::None || !::strchr( sepchars_r, *cur ) ) );
658 *result_r = std::string( buf.begin(), buf.end() );
662 if ( *cur && ::strchr( sepchars_r, *cur ) )
664 while ( *cur && ::strchr( sepchars_r, *cur ) )
673 // the last was a separator => one more field
674 if ( !*cur && withEmpty && ::strchr( sepchars_r, *(cur-1) ) )
683 /** Split \a line_r into fields.
684 * Any single character in \a sepchars_r is treated as a
685 * field separator unless \-escaped. The words are passed
692 * ":a" -> words 2 ||a|
693 * "a:" -> words 2 |a||
694 * ":a:" -> words 3 ||a||
699 * std::vector<std::string> words;
700 * str::split( "some line", std::back_inserter(words) )
704 template<class _OutputIterator>
705 unsigned splitFields( const C_Str & line_r,
706 _OutputIterator result_r,
707 const C_Str & sepchars_r = ":" )
709 const char * beg = line_r;
710 const char * cur = beg;
712 for ( beg = cur; *beg; beg = cur, ++result_r )
715 while( *cur && !::strchr( sepchars_r, *cur ) )
717 if ( *cur == '\\' && *(cur+1) )
722 *result_r = std::string( beg, cur-beg );
728 if ( ! *cur ) // ending with sepchar
730 *result_r = std::string(); // add final empty field
740 * Split \a line_r into fields handling also escaped separators.
743 * \see splitEscaped()
745 template<class _OutputIterator>
746 unsigned splitFieldsEscaped( const C_Str & line_r,
747 _OutputIterator result_r,
748 const C_Str & sepchars_r = ":" )
751 splitEscaped( line_r, result_r, sepchars_r, true /* withEmpty */ );
756 ///////////////////////////////////////////////////////////////////
759 /** Join strings using separator \a sep_r (defaults to BLANK). */
760 template <class _Iterator>
761 std::string join( _Iterator begin, _Iterator end,
762 const C_Str & sep_r = " " )
765 for ( _Iterator iter = begin; iter != end; ++ iter )
769 res += asString(*iter);
774 /** Join strings using separator \a sep_r (defaults to BLANK). */
775 template <class _Container>
776 std::string join( const _Container & cont_r,
777 const C_Str & sep_r = " " )
778 { return join( cont_r.begin(), cont_r.end(), sep_r ); }
780 /** Join strings using separator \a sep_r, quoting or escaping the values.
781 * Separator defaults to BLANK. Use \ref splitEscaped to restore the
784 template <class _Iterator>
785 std::string joinEscaped( _Iterator begin, _Iterator end,
786 const char sep_r = ' ' )
788 std::vector<char> buf;
789 for ( _Iterator iter = begin; iter != end; ++ iter )
792 buf.push_back( sep_r );
796 // empty string goes ""
797 buf.push_back( '"' );
798 buf.push_back( '"' );
802 std::string toadd( asString(*iter) );
803 for_( ch, toadd.begin(), toadd.end() )
810 buf.push_back( '\\' );
811 buf.push_back( *ch );
815 buf.push_back( '\\' );
816 buf.push_back( *ch );
821 return std::string( buf.begin(), buf.end() );
826 ///////////////////////////////////////////////////////////////////
829 /** Indent by string [" "] optionally wrap.
830 * Prints nothing for an empty string. Asserts a trainling '\n' on
831 * the last line. Optionally wrap lines at ' ' at a given length.
833 inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, const std::string & indent_r = " ", unsigned maxWitdh_r = 0 )
837 if ( indent_r.size() >= maxWitdh_r )
838 maxWitdh_r = 0; // nonsense: indent larger than line witdh
840 maxWitdh_r -= indent_r.size();
843 for ( const char * e = text_r.c_str(), * s = e; *e; s = ++e )
845 for ( ; *e && *e != '\n'; ++e ) ;/*searching*/
847 if ( maxWitdh_r && width > maxWitdh_r )
851 for ( e = s+width; e > s && *e != ' '; --e ) ;/*searching*/
853 width = e-s; // on a ' ', replaced by '\n'
855 e = s+width-1; // cut line;
858 str.write( s, width );
860 if ( !*e ) // on '\0'
865 /** \overload Indent by number of chars [' '] optionally wrap. */
866 inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, unsigned indent_r, char indentch_r = ' ', unsigned maxWitdh_r = 0 )
867 { return printIndented( str, text_r, std::string( indent_r, indentch_r ), maxWitdh_r ); }
868 /** \overload Indent by number of chars [' '] wrap. */
869 inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, unsigned indent_r, unsigned maxWitdh_r, char indentch_r = ' ' )
870 { return printIndented( str, text_r, std::string( indent_r, indentch_r ), maxWitdh_r ); }
872 /** Prefix lines by string computed by function taking line begin/end [std::string(const char*, const char*)]
873 * Prints nothing for an empty string. Asserts a trainling '\n' on the last line.
875 inline std::ostream & autoPrefix( std::ostream & str, const std::string & text_r, function<std::string(const char*, const char*)> fnc_r )
877 for ( const char * e = text_r.c_str(); *e; ++e )
880 for ( ; *e && *e != '\n'; ++e ) /*searching*/;
881 str << fnc_r( s, e );
884 if ( !*e ) // on '\0'
889 /** \overload Prefix lines by string generated by function [std::string()] */
890 inline std::ostream & autoPrefix0( std::ostream & str, const std::string & text_r, function<std::string()> fnc_r )
892 auto wrap = [&fnc_r]( const char*, const char* )-> std::string {
895 return autoPrefix( str, text_r, wrap );
898 ///////////////////////////////////////////////////////////////////
902 * Escape desired character \a c using a backslash.
904 * For use when printing \a c separated values, and where
905 * \ref joinEscaped() is too heavy.
907 std::string escape( const C_Str & str_r, const char c = ' ' );
909 /** Escape \a next_r and append it to \a str_r using separator \a sep_r. */
910 inline void appendEscaped( std::string & str_r, const C_Str & next_r, const char sep_r = ' ' )
912 if ( ! str_r.empty() )
914 if ( next_r.empty() )
917 str_r += escape( next_r, sep_r );
923 ///////////////////////////////////////////////////////////////////
924 ///////////////////////////////////////////////////////////////////
926 * Encode all characters other than [a-zA-Z0-9] as %XX.
927 * This includes the % character itself, which becomes %25.
930 /** Encode all characters other than [a-zA-Z0-9] as %XX.
931 * This includes the % character itself, which becomes %25.
933 std::string hexencode( const C_Str & str_r );
934 /** Decode hexencoded %XX sequences. */
935 std::string hexdecode( const C_Str & str_r );
937 ///////////////////////////////////////////////////////////////////
939 /** \name Case conversion. */
941 /** Return lowercase version of \a s
944 std::string toLower( const std::string & s );
946 inline std::string toLower( const char * s )
947 { return( s ? toLower( std::string(s) ) : std::string() ); }
949 /** Return uppercase version of \a s
952 std::string toUpper( const std::string & s );
954 inline std::string toUpper( const char * s )
955 { return( s ? toUpper( std::string(s) ) : std::string() ); }
959 /** \name Case insensitive comparison. */
961 inline int compareCI( const C_Str & lhs, const C_Str & rhs )
962 { return ::strcasecmp( lhs, rhs ); }
965 /** \name Locate substring. */
967 /** Locate substring case sensitive. */
968 inline bool contains( const C_Str & str_r, const C_Str & val_r )
969 { return ::strstr( str_r, val_r ); }
970 /** Locate substring case insensitive. */
971 inline bool containsCI( const C_Str & str_r, const C_Str & val_r )
972 { return ::strcasestr( str_r, val_r ); }
975 ///////////////////////////////////////////////////////////////////
976 /** \name Trimming whitepace.
977 * \todo optimize l/r trim.
980 /** To define how to trim. */
985 TRIM = (L_TRIM|R_TRIM)
988 std::string trim( const std::string & s, const Trim trim_r = TRIM );
990 inline std::string ltrim( const std::string & s )
991 { return trim( s, L_TRIM ); }
993 inline std::string rtrim( const std::string & s )
994 { return trim( s, R_TRIM ); }
997 std::string stripFirstWord( std::string & line, const bool ltrim_first = true );
999 std::string stripLastWord( std::string & line, const bool rtrim_first = true );
1001 /** Return stream content up to (but not returning) the next newline.
1002 * \see \ref receiveUpTo
1004 std::string getline( std::istream & str, bool trim = false );
1006 /** Return stream content up to (but not returning) the next newline.
1007 * \see \ref receiveUpTo
1009 std::string getline( std::istream & str, const Trim trim_r );
1011 /** Return stream content up to the next ocurrence of \c delim_r or EOF
1012 * \c delim_r, if found, is always read from the stream. Whether it is
1013 * also returned in the string depends on \c returnDelim_r.
1014 * If the stream status is \c good, \c delim_r was found in the stream.
1015 * If we reached EOF while looking for \c delim_r, \c eof is set; and
1016 * also \c fail, if we did not read any data before.
1018 std::string receiveUpTo( std::istream & str, const char delim_r, bool returnDelim_r = false );
1020 ///////////////////////////////////////////////////////////////////
1022 /** \name String prefix/suffix handling.
1025 /** Return whether \a str_r has prefix \a prefix_r. */
1026 inline bool hasPrefix( const C_Str & str_r, const C_Str & prefix_r )
1027 { return( ::strncmp( str_r, prefix_r, prefix_r.size() ) == 0 ); }
1029 /** Strip a \a prefix_r from \a str_r and return the resulting string. */
1030 inline std::string stripPrefix( const C_Str & str_r, const C_Str & prefix_r )
1031 { return( hasPrefix( str_r, prefix_r ) ? str_r + prefix_r.size() : str_r.c_str() ); }
1033 /** Return whether \a str_r has suffix \a suffix_r. */
1034 inline bool hasSuffix( const C_Str & str_r, const C_Str & suffix_r )
1035 { return( str_r.size() >= suffix_r.size() && ::strncmp( str_r + str_r.size() - suffix_r.size() , suffix_r, suffix_r.size() ) == 0 ); }
1037 /** Strip a \a suffix_r from \a str_r and return the resulting string. */
1038 inline std::string stripSuffix( const C_Str & str_r, const C_Str & suffix_r )
1040 if ( hasSuffix( str_r, suffix_r ) )
1041 return std::string( str_r, str_r.size() - suffix_r.size() );
1042 return str_r.c_str();
1044 /** Return size of the common prefix of \a lhs and \a rhs. */
1045 inline std::string::size_type commonPrefix( const C_Str & lhs, const C_Str & rhs )
1047 const char * lp = lhs.c_str();
1048 const char * rp = rhs.c_str();
1049 std::string::size_type ret = 0;
1050 while ( *lp == *rp && *lp != '\0' )
1051 { ++lp, ++rp, ++ret; }
1055 /** alias for \ref hasPrefix */
1056 inline bool startsWith( const C_Str & str_r, const C_Str & prefix_r )
1057 { return hasPrefix( str_r, prefix_r ); }
1058 /** alias for \ref hasSuffix */
1059 inline bool endsWith( const C_Str & str_r, const C_Str & prefix_r )
1060 { return hasSuffix( str_r, prefix_r ); }
1063 ///////////////////////////////////////////////////////////////////
1065 // drag into zypp:: namespace
1066 using str::asString;
1069 ///////////////////////////////////////////////////////////////////
1070 #endif // ZYPP_BASE_STRING_H