9145e909121862d3d558495a94928f5ad975efa5
[platform/upstream/libzypp.git] / zypp / base / String.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/base/String.h
10  *
11 */
12 #ifndef ZYPP_BASE_STRING_H
13 #define ZYPP_BASE_STRING_H
14
15 #include <cstring>
16
17 #include <iosfwd>
18 #include <vector>
19 #include <string>
20 #include <sstream>
21 #include <boost/format.hpp>
22
23 #include "zypp/base/Easy.h"
24 #include "zypp/base/PtrTypes.h"
25 #include "zypp/base/Function.h"
26
27
28 ///////////////////////////////////////////////////////////////////
29 namespace boost
30 {
31   /** A formater with (N)o (A)rgument (C)heck.
32    * It won't complain about missing or excess arguments. Sometimes
33    * usefull when dealing with translations or classes providing a
34    * default formater.
35    */
36   inline format formatNAC( const std::string & string_r ) {
37     using namespace boost::io;
38     format fmter( string_r );
39     fmter.exceptions( all_error_bits ^ ( too_many_args_bit | too_few_args_bit ) );
40     return fmter;
41   }
42 } // namespace boost
43 ///////////////////////////////////////////////////////////////////
44
45 ///////////////////////////////////////////////////////////////////
46 namespace zypp
47 {
48   /** Request a human readable (translated) string representation of _Tp [_Tp.asUserString()]
49    * Classes may implement a default as member function.
50    */
51   template <class _Tp>
52   std::string asUserString( const _Tp & val_r )
53   { return val_r.asUserString(); }
54
55 }// namespace zypp
56 ///////////////////////////////////////////////////////////////////
57
58 ///////////////////////////////////////////////////////////////////
59 namespace zypp
60 { /////////////////////////////////////////////////////////////////
61
62   /** Convenience \c char* constructible from \c std::string and \c char*,
63    *  it maps \c (char*)0 to an empty string.
64    *
65    * \code
66    * bool hasPrefix( const std::string & str_r, const std::string & prefix_r )
67    * { return( ::strncmp( str_r.c_str(), prefix_r.c_str(), prefix_r.size() ) == 0 ); }
68    * \endcode
69    *
70    * Called with a plain \c char* as argument, the \c std::string is created form
71    * for nothing. The implementation actually does not use the \c std::string.
72    *
73    * Best would be to implement \c hasPrefix for each combination of \c char*
74    * and \c std::string arguments:
75    *
76    * \code
77    * bool hasPrefix( const std::string & str_r, const std::string & prefix_r )
78    * { return( ::strncmp( str_r.c_str(), prefix_r.c_str(), prefix_r.size() ) == 0 ); }
79    *
80    * bool hasPrefix( const std::string & str_r, const char * prefix_r )
81    * { return( !prefix_r || ::strncmp( str_r.c_str(), prefix_r, ::strlen(prefix_r) ) == 0 ); }
82    *
83    * bool hasPrefix( const char * str_r, const std::string & prefix_r )
84    * { return( str_r ? ::strncmp( str_r, prefix_r.c_str(), prefix_r.size() ) == 0 : prefix_r.empty() ); }
85    *
86    * bool hasPrefix( const char * str_r, const char * prefix_r )
87    * { return( str && prefix_r ? ::strncmp( str_r, prefix_r, ::strlen(prefix_r) ) == 0
88    *                           : !((str_r && *str_r) || (prefix_r && *prefix_r)); }
89    * \endcode
90    *
91    * This is where \ref C_Str can help. Constructible from \c std::string and \c char*,
92    * it \e reduces the \c std::string to it's \c char*. At the same time it converts
93    * \c (char*)0 into an \c "" string.
94    *
95    * \code
96    * bool hasPrefix( const C_Str & str_r, const C_Str & prefix_r )
97    * { return( ::strncmp( str_r, prefix_r, prefix_r.size() ) == 0 ); }
98    * \endcode
99    */
100   class C_Str
101   {
102     public:
103       typedef std::string::size_type size_type;
104
105     public:
106       C_Str()                            : _val( 0 ),             _sze( 0 ) {}
107       C_Str( char * c_str_r )            : _val( c_str_r ),       _sze( std::string::npos ) {}
108       C_Str( const char * c_str_r )      : _val( c_str_r ),       _sze( std::string::npos ) {}
109       C_Str( const std::string & str_r ) : _val( str_r.c_str() ), _sze( str_r.size() ) {}
110
111     public:
112       bool      isNull()       const { return !_val; }
113       bool      empty()        const { return !(_val && *_val); }
114       size_type size()         const
115       {
116         if ( _sze == std::string::npos )
117         { _sze = _val ? ::strlen( _val ) : 0; }
118         return _sze;
119       };
120
121       operator const char *() const { return c_str(); }
122       const char * c_str()    const { return _val ? _val : ""; }
123
124     private:
125       const char *const _val;
126       mutable size_type _sze;
127   };
128
129   /** \relates C_Str Stream output */
130   inline std::ostream & operator<<( std::ostream & str, const C_Str & obj )
131   { return str << obj.c_str(); }
132
133   ///////////////////////////////////////////////////////////////////
134   /** String related utilities and \ref ZYPP_STR_REGEX.
135    \see \ref ZYPP_STR_REGEX
136   */
137   namespace str
138   { /////////////////////////////////////////////////////////////////
139
140     ///////////////////////////////////////////////////////////////////
141     /**
142      * Global asString() that works with std::string too
143      */
144     inline std::string asString( const std::string &t )
145     { return t; }
146
147 #ifndef SWIG // Swig treats it as syntax error
148     inline std::string asString( std::string && t )
149     { return std::move(t); }
150 #endif
151
152     inline std::string asString( const char * t )
153     { return t; }
154
155     inline std::string asString( char * t )
156     { return t; }
157
158     template<class _T>
159         inline std::string asString( const _T &t )
160         { return t.asString(); }
161
162     template<class _T>
163         inline std::string asString( const intrusive_ptr<_T> &p )
164         { return p->asString(); }
165
166     template<class _T>
167         inline std::string asString( const weak_ptr<_T> &p )
168         { return p->asString(); }
169
170     template<>
171         inline std::string asString( const bool &t )
172         { return t ? "true" : "false"; }
173
174     ///////////////////////////////////////////////////////////////////
175     /** Printf style construction of std::string. */
176     std::string form( const char * format, ... )
177     __attribute__ ((format (printf, 1, 2)));
178
179     ///////////////////////////////////////////////////////////////////
180     /** Return string describing the \a error_r code.
181      * Like ::strerror, but the numerical value is included in
182      * the string as well.
183     */
184     std::string strerror( int errno_r );
185
186     ///////////////////////////////////////////////////////////////////
187     /** Assert \c free called for allocated <tt>char *</tt>.
188      * \code
189      * ...
190      * SafeBuf safe;
191      * vasprintf( &safe._buf, format, ap );
192      * return safe.asString();
193      * \endcode
194      *
195      * \ingroup g_RAII
196     */
197     struct SafeBuf
198     {
199       char * _buf;
200       SafeBuf() : _buf( 0 ) {}
201       ~SafeBuf() { if ( _buf ) free( _buf ); }
202       std::string asString() const
203       { return _buf ? std::string(_buf) : std::string(); }
204     };
205
206     ///////////////////////////////////////////////////////////////////
207     /** Convenient building of std::string via std::ostream::operator<<.
208      * Basically this is an \ref ostringstream which is autocenvertible
209      * into a \ref string.
210      * \code
211      *  void fnc( const std::string & txt_r );
212      *  fnc( str::Str() << "Hello " << 13 );
213      *
214      *  std::string txt( str::Str() << 45 );
215      * \endcode
216     */
217     struct Str
218     {
219       template<class _Tp>
220       Str & operator<<( const _Tp & val )
221       { _str << val; return *this; }
222
223       operator std::string() const
224       { return _str.str(); }
225
226       std::ostream & stream()
227       { return _str; }
228
229       void clear()
230       { _str.str( std::string() ); }
231
232       std::ostringstream _str;
233     };
234
235     inline std::ostream & operator<<( std::ostream & str, const Str & obj )
236     { return str << (std::string)obj; }
237
238     ///////////////////////////////////////////////////////////////////
239     /** \name String representation of number.
240      *
241      * Optional second argument sets the minimal string width (' ' padded).
242      * Negative values will cause the number to be left adjusted within the string.
243      *
244      * Default width is 0.
245      * \code
246      * numstring(42)           -> "42"
247      * numstring(42, 4)        -> "  42"
248      * numstring(42,-4)        -> "42  "
249      * \endcode
250      **/
251     //@{
252     inline std::string numstring( char n,               int w = 0 ) { return form( "%*hhd",  w, n ); }
253     inline std::string numstring( unsigned char n,      int w = 0 ) { return form( "%*hhu",  w, n ); }
254     inline std::string numstring( short n,              int w = 0 ) { return form( "%*hd",   w, n ); }
255     inline std::string numstring( unsigned short n,     int w = 0 ) { return form( "%*hu",   w, n ); }
256     inline std::string numstring( int n,                int w = 0 ) { return form( "%*d",    w, n ); }
257     inline std::string numstring( unsigned n,           int w = 0 ) { return form( "%*u",    w, n ); }
258     inline std::string numstring( long n,               int w = 0 ) { return form( "%*ld",   w, n ); }
259     inline std::string numstring( unsigned long n,      int w = 0 ) { return form( "%*lu",   w, n ); }
260     inline std::string numstring( long long n,          int w = 0 ) { return form( "%*lld",  w, n ); }
261     inline std::string numstring( unsigned long long n, int w = 0 ) { return form( "%*llu",  w, n ); }
262
263     template<> inline std::string asString( const char & t )                    { return numstring( t ); }
264     template<> inline std::string asString( const unsigned char & t )           { return numstring( t ); }
265     template<> inline std::string asString( const short & t )                   { return numstring( t ); }
266     template<> inline std::string asString( const unsigned short & t )          { return numstring( t ); }
267     template<> inline std::string asString( const int & t )                     { return numstring( t ); }
268     template<> inline std::string asString( const unsigned & t )                { return numstring( t ); }
269     template<> inline std::string asString( const long & t )                    { return numstring( t ); }
270     template<> inline std::string asString( const unsigned long & t )           { return numstring( t ); }
271     template<> inline std::string asString( const long long & t )               { return numstring( t ); }
272     template<> inline std::string asString( const unsigned long long & t )      { return numstring( t ); }
273     //@}
274
275     ///////////////////////////////////////////////////////////////////
276     /** \name String representation of number as hex value with leading '0x'.
277      * Optional second argument sets the minimal
278      * string width (0 padded). Negative values will cause the number to be left adjusted
279      * within the string. Default width is 10 (4 for char).
280      * <PRE>
281      * hexstring(42)           -> "0x0000002a"
282      * hexstring(42, 4)        -> "0x2a"
283      * hexstring(42,-4)        -> "0x2a"
284      * </PRE>
285      **/
286     //@{
287     inline std::string hexstring( char n,               int w = 4 ) { return form( "%#0*hhx", w, n ); }
288     inline std::string hexstring( unsigned char n,      int w = 4 ) { return form( "%#0*hhx", w, n ); }
289     inline std::string hexstring( short n,              int w = 10 ){ return form( "%#0*hx",  w, n ); }
290     inline std::string hexstring( unsigned short n,     int w = 10 ){ return form( "%#0*hx",  w, n ); }
291     inline std::string hexstring( int n,                int w = 10 ){ return form( "%#0*x",   w, n ); }
292     inline std::string hexstring( unsigned n,           int w = 10 ){ return form( "%#0*x",   w, n ); }
293     inline std::string hexstring( long n,               int w = 10 ){ return form( "%#0*lx",  w, n ); }
294     inline std::string hexstring( unsigned long n,      int w = 10 ){ return form( "%#0*lx",  w, n ); }
295     inline std::string hexstring( long long n,          int w = 0 ) { return form( "%#0*llx", w, n ); }
296     inline std::string hexstring( unsigned long long n, int w = 0 ) { return form( "%#0*llx", w, n ); }
297     //@}
298
299     ///////////////////////////////////////////////////////////////////
300     /** \name String representation of number as octal value with leading '0'.
301      * Optional second argument sets the minimal
302      * string width (0 padded). Negative values will cause the number to be left adjusted
303      * within the string. Default width is 5 (4 for char).
304      * <PRE>
305      * octstring(42)           -> "00052"
306      * octstring(42, 4)        -> "0052"
307      * octstring(42,-4)        -> "052 "
308      * </PRE>
309      **/
310     //@{
311     inline std::string octstring( char n,               int w = 4 ) { return form( "%#0*hho",  w, n ); }
312     inline std::string octstring( unsigned char n,      int w = 4 ) { return form( "%#0*hho",  w, n ); }
313     inline std::string octstring( short n,              int w = 5 ) { return form( "%#0*ho",   w, n ); }
314     inline std::string octstring( unsigned short n,     int w = 5 ) { return form( "%#0*ho",   w, n ); }
315     inline std::string octstring( int n,                int w = 5 ) { return form( "%#0*o",    w, n ); }
316     inline std::string octstring( unsigned n,           int w = 5 ) { return form( "%#0*o",    w, n ); }
317     inline std::string octstring( long n,               int w = 5 ) { return form( "%#0*lo",   w, n ); }
318     inline std::string octstring( unsigned long n,      int w = 5 ) { return form( "%#0*lo",   w, n ); }
319     inline std::string octstring( long long n,          int w = 0 ) { return form( "%#0*llo",  w, n ); }
320     inline std::string octstring( unsigned long long n, int w = 0 ) { return form( "%#0*llo",  w, n ); }
321     //@}
322
323     ///////////////////////////////////////////////////////////////////
324     /** Parsing numbers from string.
325     */
326     //@{
327     /** String to integer type determined by template arg.
328      * \note Only specializations are defined.
329      * \code
330      * time_t t = strtonum<time_t>( "42" );
331      * \endcode
332     */
333     template<typename _It>
334       _It strtonum( const C_Str & str );
335
336     template<>
337       inline short              strtonum( const C_Str & str ) { return ::strtol  ( str, NULL, 0 ); }
338     template<>
339       inline int                strtonum( const C_Str & str ) { return ::strtol  ( str, NULL, 0 ); }
340     template<>
341       inline long               strtonum( const C_Str & str ) { return ::strtol  ( str, NULL, 0 ); }
342     template<>
343       inline long long          strtonum( const C_Str & str ) { return ::strtoll ( str, NULL, 0 ); }
344
345     template<>
346       inline unsigned short     strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
347     template<>
348       inline unsigned           strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
349     template<>
350       inline unsigned long      strtonum( const C_Str & str ) { return ::strtoul ( str, NULL, 0 ); }
351     template<>
352       inline unsigned long long strtonum( const C_Str & str ) { return ::strtoull( str, NULL, 0 ); }
353
354     /** String to integer type detemined 2nd function arg \a i.
355      * \code
356      * time_t t; strtonum( "42", t );
357      * \endcode
358     */
359     template<typename _It>
360       inline _It strtonum( const C_Str & str, _It & i )
361       { return i = strtonum<_It>( str ); }
362     //@}
363
364     ///////////////////////////////////////////////////////////////////
365     /** Parsing boolean from string.
366     */
367     //@{
368     /** Return \c true if str is <tt>1, true, yes, on</tt> (or a nonzero number). */
369     bool strToTrue( const C_Str & str );
370
371     /** Return \c false if str is <tt>0, false, no, off</tt>. */
372     bool strToFalse( const C_Str & str );
373
374     /** Parse \c str into a bool depending on the default value.
375      * If the \c default is true, look for a legal \c false string.
376      * If the \c default is false, look for a legal \c true string.
377      */
378     inline bool strToBool( const C_Str & str, bool default_r )
379     { return( default_r ? strToFalse( str ) : strToTrue( str ) ); }
380
381     /** Parse \c str into a bool if it's a legal \c true or \c false string.
382      * If \c str is not a recognized \c true or \c false string, \a return_r
383      * is left unchanged.
384      */
385     inline bool strToBoolNodefault( const C_Str & str, bool & return_r )
386     {
387       if ( strToTrue( str ) ) return (return_r = true);
388       if ( !strToFalse( str ) ) return (return_r = false);
389       return return_r;
390     }
391
392     //@}
393
394     /**
395      * \short Return a string with all occurrences of \c from_r replaced with \c to_r.
396      */
397     std::string gsub( const std::string & str_r, const std::string & from_r, const std::string & to_r );
398
399     /** \overload A function is called on demand to compute each replacement value.
400      */
401     std::string gsubFun( const std::string & str_r, const std::string & from_r, function<std::string()> to_r );
402
403     /**
404      * \short Replace all occurrences of \c from_r with \c to_r in \c str_r (inplace).
405      * A reference to \c str_r is also returned for convenience.
406      */
407     std::string & replaceAll( std::string & str_r, const std::string & from_r, const std::string & to_r );
408
409     /** \overload A function is called on demand to compute each replacement value.
410      */
411     std::string & replaceAllFun( std::string & str_r, const std::string & from_r, function<std::string()> to_r );
412
413
414     ///////////////////////////////////////////////////////////////////
415     /** \name Split. */
416     //@{
417     /** Split \a line_r into words.
418      * Any sequence of characters in \a sepchars_r is treated as
419      * delimiter. The words are passed to OutputIterator \a result_r.
420      * \code
421      * std::vector<std::string> words;
422      * str::split( "some line", std::back_inserter(words) )
423      * \endcode
424      *
425     */
426     template<class _OutputIterator>
427       unsigned split( const C_Str &   line_r,
428                       _OutputIterator result_r,
429                       const C_Str &   sepchars_r = " \t" )
430       {
431         const char * beg = line_r;
432         const char * cur = beg;
433         // skip leading sepchars
434         while ( *cur && ::strchr( sepchars_r, *cur ) )
435           ++cur;
436         unsigned ret = 0;
437         for ( beg = cur; *beg; beg = cur, ++result_r, ++ret )
438           {
439             // skip non sepchars
440             while( *cur && !::strchr( sepchars_r, *cur ) )
441               ++cur;
442             // build string
443             *result_r = std::string( beg, cur-beg );
444             // skip sepchars
445             while ( *cur && ::strchr( sepchars_r, *cur ) )
446               ++cur;
447           }
448         return ret;
449       }
450
451     /** Split \a line_r into words with respect to escape delimeters.
452      * Any sequence of characters in \a sepchars_r is treated as
453      * delimiter if not inside "" or "" or escaped by \, but not \\.
454      * The words are passed to OutputIterator \a result_r.
455      *
456      * \see \ref splitEscaped
457      *
458      * \code
459      * std::vector<std::string> words;
460      * str::splitEscaped( "some line", std::back_inserter(words) )
461      * \endcode
462      *
463      * \code
464      * example splitted strings
465      * normal line -> 2 elements ( "normal", "line" )
466      * escaped\ line -> 1 element( "escaped line" )
467      * "quoted line" -> 1 element same as above
468      * 'quoted line' -> 1 element same as above
469      * "escaped quote\'" -> 1 element ( "escaped quote'" )
470      *
471      * \param line_r   The string to parse.
472      * \param result_r
473      * \param sepchars_r  String of separator characters.
474      * \param withEmpty   Whether to include empty fields between separators in the result.
475      *
476      * \endcode
477      */
478     template<class _OutputIterator>
479       unsigned splitEscaped( const C_Str &   line_r,
480                       _OutputIterator result_r,
481                       const C_Str &   sepchars_r = " \t",
482                       bool withEmpty = false)
483       {
484         const char * beg = line_r;
485         const char * cur = beg;
486         unsigned ret = 0;
487
488         // skip leading sepchars
489         while ( *cur && ::strchr( sepchars_r, *cur ) )
490         {
491           ++cur;
492           if (withEmpty)
493           {
494             *result_r = "";
495             ++ret;
496           }
497         }
498
499         // there were only sepchars in the string
500         if (!*cur && withEmpty)
501         {
502           *result_r = "";
503           return ++ret;
504         }
505
506         // after the leading sepchars
507         for ( beg = cur; *beg; beg = cur, ++result_r, ++ret )
508           {
509             if ( *cur == '"'  || *cur == '\'' )
510             {
511               char closeChar = *cur;
512               ++cur;
513               bool cont = true;
514               while (cont)
515               {
516                 while ( *cur && *cur != closeChar)
517                   ++cur;
518                 if ( *cur == '\0' )
519                 {
520                   return ret; //TODO parsing exception no closing quote
521                 }
522                 int escCount = 0;
523                 const char * esc = cur-1;
524                 while ( esc != beg && *esc == '\\' )
525                 {
526                   escCount++;
527                   --esc;
528                 }
529                 cont = (escCount % 2 == 1); // find some non escaped escape char
530                 cur++; //skip quote
531               }
532
533               std::string s( beg+1, cur-beg-2 ); //without quotes
534               //transform escaped escape
535               replaceAll( s, "\\\\", "\\" );
536               //transform escaped quotes (only same as open
537               char tmpn[2] = { closeChar, 0 };
538               char tmpo[3] = { '\\', closeChar, 0 };
539               replaceAll( s, tmpo, tmpn );
540
541               *result_r = s;
542             }
543             else
544             {
545               // skip non sepchars
546               while( *cur && !::strchr( sepchars_r, *cur ) )
547               {
548                 //ignore char after backslash
549                 if ( *cur == '\\' )
550                 {
551                   ++cur;
552                 }
553                 ++cur;
554               }
555               // build string
556               std::string s( beg, cur-beg );
557               //transform escaped escape
558               replaceAll( s, "\\\\", "\\" );
559
560               const char *delimeter = sepchars_r;
561               while ( *delimeter )
562               {
563                 std::string ds("\\");
564                 const char tmp[2] = { *delimeter, '\0' };
565                 std::string del(tmp);
566                 ds+= del;
567                 replaceAll( s, ds, del );
568                 ++delimeter;
569               }
570
571               *result_r = s;
572             }
573             // skip sepchars
574             if ( *cur && ::strchr( sepchars_r, *cur ) )
575               ++cur;
576             while ( *cur && ::strchr( sepchars_r, *cur ) )
577             {
578               ++cur;
579               if (withEmpty)
580               {
581                 *result_r = "";
582                 ++ret;
583               }
584             }
585             // the last was a separator => one more field
586             if ( !*cur && withEmpty && ::strchr( sepchars_r, *(cur-1) ) )
587             {
588               *result_r = "";
589               ++ret;
590             }
591           }
592         return ret;
593       }
594
595     /** Split \a line_r into fields.
596      * Any single character in \a sepchars_r is treated as a
597      * field separator unless \-escaped. The words are passed
598      * to OutputIterator.
599      * \a result_r.
600      * \code
601      * ""        -> words 0
602      * ":"       -> words 2  |||
603      * "a"       -> words 1  |a|
604      * ":a"      -> words 2  ||a|
605      * "a:"      -> words 2  |a||
606      * ":a:"     -> words 3  ||a||
607      *
608      * \endcode
609      *
610      * \code
611      * std::vector<std::string> words;
612      * str::split( "some line", std::back_inserter(words) )
613      * \endcode
614      *
615     */
616     template<class _OutputIterator>
617       unsigned splitFields( const C_Str &   line_r,
618                             _OutputIterator result_r,
619                             const C_Str &   sepchars_r = ":" )
620       {
621         const char * beg = line_r;
622         const char * cur = beg;
623         unsigned ret = 0;
624         for ( beg = cur; *beg; beg = cur, ++result_r )
625           {
626             // skip non sepchars
627             while( *cur && !::strchr( sepchars_r, *cur ) )
628             {
629               if ( *cur == '\\' && *(cur+1) )
630                 ++cur;
631               ++cur;
632             }
633             // build string
634             *result_r = std::string( beg, cur-beg );
635             ++ret;
636             // skip sepchar
637             if ( *cur )
638             {
639               ++cur;
640               if ( ! *cur )                // ending with sepchar
641               {
642                 *result_r = std::string(); // add final empty field
643                 ++ret;
644                 break;
645               }
646             }
647           }
648         return ret;
649       }
650
651     /**
652      * Split \a line_r into fields handling also escaped separators.
653      *
654      * \see splitFields()
655      * \see splitEscaped()
656      */
657     template<class _OutputIterator>
658       unsigned splitFieldsEscaped( const C_Str &   line_r,
659                             _OutputIterator result_r,
660                             const C_Str &   sepchars_r = ":" )
661       {
662         return
663           splitEscaped( line_r, result_r, sepchars_r, true /* withEmpty */ );
664       }
665
666     //@}
667
668     ///////////////////////////////////////////////////////////////////
669     /** \name Join. */
670     //@{
671     /** Join strings using separator \a sep_r (defaults to BLANK). */
672     template <class _Iterator>
673       std::string join( _Iterator begin, _Iterator end,
674                         const C_Str & sep_r = " " )
675       {
676         std::string res;
677         for ( _Iterator iter = begin; iter != end; ++ iter )
678           {
679             if ( iter != begin )
680               res += sep_r;
681             res += asString(*iter);
682           }
683         return res;
684       }
685
686     /** Join strings using separator \a sep_r (defaults to BLANK). */
687     template <class _Container>
688       std::string join( const _Container & cont_r,
689                         const C_Str & sep_r = " " )
690       { return join( cont_r.begin(), cont_r.end(), sep_r ); }
691
692     /** Join strings using separator \a sep_r, quoting or escaping the values.
693      * Separator defaults to BLANK. Use \ref splitEscaped to restore the
694      * values.
695      */
696     template <class _Iterator>
697       std::string joinEscaped( _Iterator begin, _Iterator end,
698                                const char sep_r = ' ' )
699       {
700         std::vector<char> buf;
701         for ( _Iterator iter = begin; iter != end; ++ iter )
702         {
703           if ( iter != begin )
704             buf.push_back( sep_r );
705
706           if ( iter->empty() )
707           {
708             // empty string goes ""
709             buf.push_back( '"' );
710             buf.push_back( '"' );
711           }
712           else
713           {
714             std::string toadd( asString(*iter) );
715             for_( ch, toadd.begin(), toadd.end() )
716             {
717               switch ( *ch )
718               {
719                 case '"':
720                 case '\'':
721                 case '\\':
722                   buf.push_back( '\\' );
723                   buf.push_back( *ch );
724                   break;
725                 default:
726                   if ( *ch == sep_r )
727                     buf.push_back( '\\' );
728                   buf.push_back( *ch );
729               }
730             }
731           }
732         }
733         return std::string( buf.begin(), buf.end() );
734       }
735     //@}
736
737
738     ///////////////////////////////////////////////////////////////////
739     /** \name Indent. */
740     //@{
741       /** Indent by string ["  "] optionally wrap.
742        * Prints nothing for an empty string. Asserts a trainling '\n' on
743        * the last line. Optionally wrap lines at ' ' at a given length.
744        */
745       inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, const std::string & indent_r = "  ", unsigned maxWitdh_r = 0 )
746       {
747         if ( maxWitdh_r )
748         {
749           if ( indent_r.size() >= maxWitdh_r )
750             maxWitdh_r = 0;     // nonsense: indent larger than line witdh
751           else
752             maxWitdh_r -= indent_r.size();
753         }
754         unsigned width = 0;
755         for ( const char * e = text_r.c_str(), * s = e; *e; s = ++e )
756         {
757           for ( ; *e && *e != '\n'; ++e ) ;/*searching*/
758           width = e-s;
759           if ( maxWitdh_r && width > maxWitdh_r )
760           {
761             // must break line
762             width = maxWitdh_r;
763             for ( e = s+width; e > s && *e != ' '; --e ) ;/*searching*/
764             if ( e > s )
765               width = e-s;      // on a ' ', replaced by '\n'
766             else
767               e = s+width-1;    // cut line;
768           }
769           str << indent_r;
770           str.write( s, width );
771           str << "\n";
772           if ( !*e )    // on '\0'
773             break;
774         }
775         return str;
776       }
777       /** \overload Indent by number of chars [' '] optionally wrap. */
778       inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, unsigned indent_r, char indentch_r = ' ', unsigned maxWitdh_r = 0 )
779       { return printIndented( str, text_r, std::string( indent_r, indentch_r ), maxWitdh_r ); }
780       /** \overload Indent by number of chars [' '] wrap. */
781       inline std::ostream & printIndented( std::ostream & str, const std::string & text_r, unsigned indent_r, unsigned maxWitdh_r, char indentch_r = ' ' )
782       { return printIndented( str, text_r, std::string( indent_r, indentch_r ), maxWitdh_r ); }
783
784       /** Prefix lines by string computed by function taking line begin/end [std::string(const char*, const char*)]
785        * Prints nothing for an empty string. Asserts a trainling '\n' on the last line.
786        */
787       inline std::ostream & autoPrefix( std::ostream & str, const std::string & text_r, function<std::string(const char*, const char*)> fnc_r )
788       {
789         for ( const char * e = text_r.c_str(); *e; ++e )
790         {
791           const char * s = e;
792           for ( ; *e && *e != '\n'; ++e ) /*searching*/;
793           str << fnc_r( s, e );
794           str.write( s, e-s );
795           str << "\n";
796           if ( !*e )    // on '\0'
797             break;
798         }
799         return str;
800       }
801       /** \overload Prefix lines by string generated by function [std::string()] */
802       inline std::ostream & autoPrefix0( std::ostream & str, const std::string & text_r, function<std::string()> fnc_r )
803       {
804         auto wrap = [&fnc_r]( const char*, const char* )-> std::string {
805           return fnc_r();
806         };
807         return autoPrefix( str, text_r, wrap );
808       }
809     //@}
810     ///////////////////////////////////////////////////////////////////
811     /** \name Escape. */
812     //@{
813       /**
814        * Escape desired character \a c using a backslash.
815        *
816        * For use when printing \a c separated values, and where
817        * \ref joinEscaped() is too heavy.
818        */
819       std::string escape( const C_Str & str_r, const char c = ' ' );
820
821       /** Escape \a next_r and append it to \a str_r using separator \a sep_r. */
822       inline void appendEscaped( std::string & str_r, const C_Str & next_r, const char sep_r = ' ' )
823       {
824         if ( ! str_r.empty() )
825           str_r += sep_r;
826         if ( next_r.empty() )
827           str_r += "\"\"";
828         else
829           str_r += escape( next_r, sep_r );
830       }
831
832       //! \todo unsecape()
833
834     //@}
835     ///////////////////////////////////////////////////////////////////
836     ///////////////////////////////////////////////////////////////////
837     /** \name Hexencode.
838      * Encode all characters other than [a-zA-Z0-9] as %XX.
839      * This includes the % character itself, which becomes %25.
840      */
841     //@{
842     /** Encode all characters other than [a-zA-Z0-9] as %XX.
843      * This includes the % character itself, which becomes %25.
844      */
845     std::string hexencode( const C_Str & str_r );
846     /** Decode hexencoded %XX sequences. */
847     std::string hexdecode( const C_Str & str_r );
848     //@}
849     ///////////////////////////////////////////////////////////////////
850
851     /** \name Case conversion. */
852     //@{
853     /** Return lowercase version of \a s
854      * \todo improve
855     */
856     std::string toLower( const std::string & s );
857     /** \overload */
858     inline std::string toLower( const char * s )
859     { return( s ? toLower( std::string(s) ) : std::string() ); }
860
861     /** Return uppercase version of \a s
862      * \todo improve
863     */
864     std::string toUpper( const std::string & s );
865     /** \overload */
866     inline std::string toUpper( const char * s )
867     { return( s ? toUpper( std::string(s) ) : std::string() ); }
868     //@}
869
870
871     /** \name Case insensitive comparison. */
872     //@{
873     inline int compareCI( const C_Str & lhs, const C_Str & rhs )
874     { return ::strcasecmp( lhs, rhs ); }
875     //@}
876
877     /** \name Locate substring. */
878     //@{
879     /** Locate substring case sensitive. */
880     inline bool contains( const C_Str & str_r, const C_Str & val_r )
881     { return ::strstr( str_r, val_r ); }
882     /** Locate substring case insensitive. */
883     inline bool containsCI( const C_Str & str_r, const C_Str & val_r )
884     { return ::strcasestr( str_r, val_r ); }
885     //@}
886
887     ///////////////////////////////////////////////////////////////////
888     /** \name Trimming whitepace.
889      * \todo optimize l/r trim.
890     */
891     //@{
892     /** To define how to trim. */
893     enum Trim {
894       NO_TRIM = 0x00,
895       L_TRIM  = 0x01,
896       R_TRIM  = 0x02,
897       TRIM    = (L_TRIM|R_TRIM)
898     };
899
900     std::string trim( const std::string & s, const Trim trim_r = TRIM );
901
902     inline std::string ltrim( const std::string & s )
903     { return trim( s, L_TRIM ); }
904
905     inline std::string rtrim( const std::string & s )
906     { return trim( s, R_TRIM ); }
907     //@}
908
909     std::string stripFirstWord( std::string & line, const bool ltrim_first = true );
910
911     std::string stripLastWord( std::string & line, const bool rtrim_first = true );
912
913     /** Return stream content up to (but not returning) the next newline.
914      * \see \ref receiveUpTo
915      */
916     std::string getline( std::istream & str, bool trim = false );
917
918     /** Return stream content up to (but not returning) the next newline.
919      * \see \ref receiveUpTo
920      */
921     std::string getline( std::istream & str, const Trim trim_r );
922
923     /** Return stream content up to the next ocurrence of \c delim_r or EOF
924      * \c delim_r, if found, is always read from the stream. Whether it is
925      * also returned in the string depends on \c returnDelim_r.
926      * If the stream status is \c good, \c delim_r was found in the stream.
927      * If we reached EOF while looking for \c delim_r, \c eof is set; and
928      * also \c fail, if we did not read any data before.
929      */
930     std::string receiveUpTo( std::istream & str, const char delim_r, bool returnDelim_r = false );
931
932     ///////////////////////////////////////////////////////////////////
933
934     /** \name String prefix/suffix handling.
935      */
936     //@{
937     /** Return whether \a str_r has prefix \a prefix_r. */
938     inline bool hasPrefix( const C_Str & str_r, const C_Str & prefix_r )
939     { return( ::strncmp( str_r, prefix_r, prefix_r.size() ) == 0 ); }
940
941     /** Strip a \a prefix_r from \a str_r and return the resulting string. */
942     inline std::string stripPrefix( const C_Str & str_r, const C_Str & prefix_r )
943     { return( hasPrefix( str_r, prefix_r ) ? str_r + prefix_r.size() : str_r.c_str() ); }
944
945     /** Return whether \a str_r has suffix \a suffix_r. */
946     inline bool hasSuffix( const C_Str & str_r, const C_Str & suffix_r )
947     { return( str_r.size() >= suffix_r.size() && ::strncmp( str_r + str_r.size() - suffix_r.size() , suffix_r, suffix_r.size() ) == 0 ); }
948
949     /** Strip a \a suffix_r from \a str_r and return the resulting string. */
950     inline std::string stripSuffix( const C_Str & str_r, const C_Str & suffix_r )
951     {
952       if ( hasSuffix( str_r, suffix_r ) )
953         return std::string( str_r, str_r.size() - suffix_r.size() );
954       return str_r.c_str();
955     }
956     /** Return size of the common prefix of \a lhs and \a rhs. */
957     inline std::string::size_type commonPrefix( const C_Str & lhs, const C_Str & rhs )
958     {
959       const char * lp = lhs.c_str();
960       const char * rp = rhs.c_str();
961       std::string::size_type ret = 0;
962       while ( *lp == *rp && *lp != '\0' )
963       { ++lp, ++rp, ++ret; }
964       return ret;
965     }
966
967     /** alias for \ref hasPrefix */
968     inline bool startsWith( const C_Str & str_r, const C_Str & prefix_r )
969     { return hasPrefix( str_r, prefix_r ); }
970     /** alias for \ref hasSuffix */
971     inline bool endsWith( const C_Str & str_r, const C_Str & prefix_r )
972     { return hasSuffix( str_r, prefix_r ); }
973     //@}
974     /////////////////////////////////////////////////////////////////
975   } // namespace str
976   ///////////////////////////////////////////////////////////////////
977   /////////////////////////////////////////////////////////////////
978 } // namespace zypp
979 ///////////////////////////////////////////////////////////////////
980 #endif // ZYPP_BASE_STRING_H