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