strings join
[folly.git] / folly / String.h
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_BASE_STRING_H_
18 #define FOLLY_BASE_STRING_H_
19
20 #include <string>
21 #include <boost/type_traits.hpp>
22
23 #ifdef __GNUC__
24 # include <ext/hash_set>
25 # include <ext/hash_map>
26 #endif
27
28 #include "folly/Conv.h"
29 #include "folly/FBString.h"
30 #include "folly/FBVector.h"
31 #include "folly/Range.h"
32 #include "folly/ScopeGuard.h"
33
34 // Compatibility function, to make sure toStdString(s) can be called
35 // to convert a std::string or fbstring variable s into type std::string
36 // with very little overhead if s was already std::string
37 namespace folly {
38
39 inline
40 std::string toStdString(const folly::fbstring& s) {
41   return std::string(s.data(), s.size());
42 }
43
44 inline
45 const std::string& toStdString(const std::string& s) {
46   return s;
47 }
48
49 // If called with a temporary, the compiler will select this overload instead
50 // of the above, so we don't return a (lvalue) reference to a temporary.
51 inline
52 std::string&& toStdString(std::string&& s) {
53   return std::move(s);
54 }
55
56 /**
57  * C-Escape a string, making it suitable for representation as a C string
58  * literal.  Appends the result to the output string.
59  *
60  * Backslashes all occurrences of backslash and double-quote:
61  *   "  ->  \"
62  *   \  ->  \\
63  *
64  * Replaces all non-printable ASCII characters with backslash-octal
65  * representation:
66  *   <ASCII 254> -> \376
67  *
68  * Note that we use backslash-octal instead of backslash-hex because the octal
69  * representation is guaranteed to consume no more than 3 characters; "\3760"
70  * represents two characters, one with value 254, and one with value 48 ('0'),
71  * whereas "\xfe0" represents only one character (with value 4064, which leads
72  * to implementation-defined behavior).
73  */
74 template <class String>
75 void cEscape(StringPiece str, String& out);
76
77 /**
78  * Similar to cEscape above, but returns the escaped string.
79  */
80 template <class String>
81 String cEscape(StringPiece str) {
82   String out;
83   cEscape(str, out);
84   return out;
85 }
86
87 /**
88  * C-Unescape a string; the opposite of cEscape above.  Appends the result
89  * to the output string.
90  *
91  * Recognizes the standard C escape sequences:
92  *
93  * \' \" \? \\ \a \b \f \n \r \t \v
94  * \[0-7]+
95  * \x[0-9a-fA-F]+
96  *
97  * In strict mode (default), throws std::invalid_argument if it encounters
98  * an unrecognized escape sequence.  In non-strict mode, it leaves
99  * the escape sequence unchanged.
100  */
101 template <class String>
102 void cUnescape(StringPiece str, String& out, bool strict = true);
103
104 /**
105  * Similar to cUnescape above, but returns the escaped string.
106  */
107 template <class String>
108 String cUnescape(StringPiece str, bool strict = true) {
109   String out;
110   cUnescape(str, out, strict);
111   return out;
112 }
113
114 /**
115  * stringPrintf is much like printf but deposits its result into a
116  * string. Two signatures are supported: the first simply returns the
117  * resulting string, and the second appends the produced characters to
118  * the specified string and returns a reference to it.
119  */
120 std::string stringPrintf(const char* format, ...)
121   __attribute__ ((format (printf, 1, 2)));
122
123 /** Similar to stringPrintf, with different signiture.
124   */
125 void stringPrintf(std::string* out, const char* fmt, ...)
126   __attribute__ ((format (printf, 2, 3)));
127
128 std::string& stringAppendf(std::string* output, const char* format, ...)
129   __attribute__ ((format (printf, 2, 3)));
130
131 /**
132  * Backslashify a string, that is, replace non-printable characters
133  * with C-style (but NOT C compliant) "\xHH" encoding.  If hex_style
134  * is false, then shorthand notations like "\0" will be used instead
135  * of "\x00" for the most common backslash cases.
136  *
137  * There are two forms, one returning the input string, and one
138  * creating output in the specified output string.
139  *
140  * This is mainly intended for printing to a terminal, so it is not
141  * particularly optimized.
142  *
143  * Do *not* use this in situations where you expect to be able to feed
144  * the string to a C or C++ compiler, as there are nuances with how C
145  * parses such strings that lead to failures.  This is for display
146  * purposed only.  If you want a string you can embed for use in C or
147  * C++, use cEscape instead.  This function is for display purposes
148  * only.
149  */
150 template <class String1, class String2>
151 void backslashify(const String1& input, String2& output, bool hex_style=false);
152
153 template <class String>
154 String backslashify(const String& input, bool hex_style=false) {
155   String output;
156   backslashify(input, output, hex_style);
157   return output;
158 }
159
160 /**
161  * Take a string and "humanify" it -- that is, make it look better.
162  * Since "better" is subjective, caveat emptor.  The basic approach is
163  * to count the number of unprintable characters.  If there are none,
164  * then the output is the input.  If there are relatively few, or if
165  * there is a long "enough" prefix of printable characters, use
166  * backslashify.  If it is mostly binary, then simply hex encode.
167  *
168  * This is an attempt to make a computer smart, and so likely is wrong
169  * most of the time.
170  */
171 template <class String1, class String2>
172 void humanify(const String1& input, String2& output);
173
174 template <class String>
175 String humanify(const String& input) {
176   String output;
177   humanify(input, output);
178   return output;
179 }
180
181 /**
182  * Same functionality as Python's binascii.hexlify.  Returns true
183  * on successful conversion.
184  *
185  * If append_output is true, append data to the output rather than
186  * replace it.
187  */
188 template<class InputString, class OutputString>
189 bool hexlify(const InputString& input, OutputString& output,
190              bool append=false);
191
192 /**
193  * Same functionality as Python's binascii.unhexlify.  Returns true
194  * on successful conversion.
195  */
196 template<class InputString, class OutputString>
197 bool unhexlify(const InputString& input, OutputString& output);
198
199 /*
200  * A pretty-printer for numbers that appends suffixes of units of the
201  * given type.  It prints 4 sig-figs of value with the most
202  * appropriate unit.
203  *
204  * If `addSpace' is true, we put a space between the units suffix and
205  * the value.
206  *
207  * Current types are:
208  *   PRETTY_TIME         - s, ms, us, ns, etc.
209  *   PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
210  *   PRETTY_BYTES        - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
211  *   PRETTY_BYTES_IEC    - KiB, MiB, GiB, etc
212  *   PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
213  *   PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
214  *   PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
215  *
216  * @author Mark Rabkin <mrabkin@fb.com>
217  */
218 enum PrettyType {
219   PRETTY_TIME,
220
221   PRETTY_BYTES_METRIC,
222   PRETTY_BYTES_BINARY,
223   PRETTY_BYTES = PRETTY_BYTES_BINARY,
224   PRETTY_BYTES_BINARY_IEC,
225   PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
226
227   PRETTY_UNITS_METRIC,
228   PRETTY_UNITS_BINARY,
229   PRETTY_UNITS_BINARY_IEC,
230
231   PRETTY_NUM_TYPES
232 };
233
234 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
235
236 /**
237  * Write a hex dump of size bytes starting at ptr to out.
238  *
239  * The hex dump is formatted as follows:
240  *
241  * for the string "abcdefghijklmnopqrstuvwxyz\x02"
242 00000000  61 62 63 64 65 66 67 68  69 6a 6b 6c 6d 6e 6f 70  |abcdefghijklmnop|
243 00000010  71 72 73 74 75 76 77 78  79 7a 02                 |qrstuvwxyz.     |
244  *
245  * that is, we write 16 bytes per line, both as hex bytes and as printable
246  * characters.  Non-printable characters are replaced with '.'
247  * Lines are written to out one by one (one StringPiece at a time) without
248  * delimiters.
249  */
250 template <class OutIt>
251 void hexDump(const void* ptr, size_t size, OutIt out);
252
253 /**
254  * Return the hex dump of size bytes starting at ptr as a string.
255  */
256 std::string hexDump(const void* ptr, size_t size);
257
258 /**
259  * Return a fbstring containing the description of the given errno value.
260  * Takes care not to overwrite the actual system errno, so calling
261  * errnoStr(errno) is valid.
262  */
263 fbstring errnoStr(int err);
264
265 /**
266  * Return the demangled (prettyfied) version of a C++ type.
267  *
268  * This function tries to produce a human-readable type, but the type name will
269  * be returned unchanged in case of error or if demangling isn't supported on
270  * your system.
271  *
272  * Use for debugging -- do not rely on demangle() returning anything useful.
273  *
274  * This function may allocate memory (and therefore throw).
275  */
276 fbstring demangle(const char* name);
277 inline fbstring demangle(const std::type_info& type) {
278   return demangle(type.name());
279 }
280
281 /**
282  * Debug string for an exception: include type and what().
283  */
284 inline fbstring exceptionStr(const std::exception& e) {
285   return folly::to<fbstring>(demangle(typeid(e)), ": ", e.what());
286 }
287
288 /*
289  * Split a string into a list of tokens by delimiter.
290  *
291  * The split interface here supports different output types, selected
292  * at compile time: StringPiece, fbstring, or std::string.  If you are
293  * using a vector to hold the output, it detects the type based on
294  * what your vector contains.  If the output vector is not empty, split
295  * will append to the end of the vector.
296  *
297  * You can also use splitTo() to write the output to an arbitrary
298  * OutputIterator (e.g. std::inserter() on a std::set<>), in which
299  * case you have to tell the function the type.  (Rationale:
300  * OutputIterators don't have a value_type, so we can't detect the
301  * type in splitTo without being told.)
302  *
303  * Examples:
304  *
305  *   std::vector<folly::StringPiece> v;
306  *   folly::split(":", "asd:bsd", v);
307  *
308  *   std::set<StringPiece> s;
309  *   folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
310  *    std::inserter(s, s.begin()));
311  *
312  * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
313  * delimiters should be treated as one single separator (ignoring empty tokens)
314  * or not (generating empty tokens).
315  */
316
317 template<class Delim, class String, class OutputType>
318 void split(const Delim& delimiter,
319            const String& input,
320            std::vector<OutputType>& out,
321            bool ignoreEmpty = false);
322
323 template<class Delim, class String, class OutputType>
324 void split(const Delim& delimiter,
325            const String& input,
326            folly::fbvector<OutputType>& out,
327            bool ignoreEmpty = false);
328
329 template<class OutputValueType, class Delim, class String,
330          class OutputIterator>
331 void splitTo(const Delim& delimiter,
332              const String& input,
333              OutputIterator out,
334              bool ignoreEmpty = false);
335
336 /*
337  * Join list of tokens.
338  *
339  * Stores a string representation of tokens in the same order with
340  * deliminer between each element.
341  */
342
343 template <class Delim, class Iterator, class String>
344 void join(const Delim& delimiter,
345           Iterator begin,
346           Iterator end,
347           String& output);
348
349 template <class Delim, class Container, class String>
350 void join(const Delim& delimiter,
351           const Container& container,
352           String& output) {
353   join(delimiter, container.begin(), container.end(), output);
354 }
355
356 } // namespace folly
357
358 // Hash functions for string and fbstring usable with e.g. hash_map
359 #ifdef __GNUC__
360 namespace __gnu_cxx {
361
362 template <class C>
363 struct hash<folly::basic_fbstring<C> > : private hash<const C*> {
364   size_t operator()(const folly::basic_fbstring<C> & s) const {
365     return hash<const C*>::operator()(s.c_str());
366   }
367 };
368
369 template <class C>
370 struct hash<std::basic_string<C> > : private hash<const C*> {
371   size_t operator()(const std::basic_string<C> & s) const {
372     return hash<const C*>::operator()(s.c_str());
373   }
374 };
375
376 } // namespace __gnu_cxx
377 #endif
378
379 // Hook into boost's type traits
380 namespace boost {
381 template <class T>
382 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
383   enum { value = true };
384 };
385 } // namespace boost
386
387 #include "folly/String-inl.h"
388
389 #endif