2 * Copyright 2012 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_BASE_STRING_H_
18 #define FOLLY_BASE_STRING_H_
21 #include <boost/type_traits.hpp>
24 # include <ext/hash_set>
25 # include <ext/hash_map>
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"
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
40 std::string toStdString(const folly::fbstring& s) {
41 return std::string(s.data(), s.size());
45 const std::string& toStdString(const std::string& s) {
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.
52 std::string&& toStdString(std::string&& s) {
57 * C-Escape a string, making it suitable for representation as a C string
58 * literal. Appends the result to the output string.
60 * Backslashes all occurrences of backslash and double-quote:
64 * Replaces all non-printable ASCII characters with backslash-octal
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).
74 template <class String>
75 void cEscape(StringPiece str, String& out);
78 * Similar to cEscape above, but returns the escaped string.
80 template <class String>
81 String cEscape(StringPiece str) {
88 * C-Unescape a string; the opposite of cEscape above. Appends the result
89 * to the output string.
91 * Recognizes the standard C escape sequences:
93 * \' \" \? \\ \a \b \f \n \r \t \v
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.
101 template <class String>
102 void cUnescape(StringPiece str, String& out, bool strict = true);
105 * Similar to cUnescape above, but returns the escaped string.
107 template <class String>
108 String cUnescape(StringPiece str, bool strict = true) {
110 cUnescape(str, out, strict);
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.
120 std::string stringPrintf(const char* format, ...)
121 __attribute__ ((format (printf, 1, 2)));
123 /** Similar to stringPrintf, with different signiture.
125 void stringPrintf(std::string* out, const char* fmt, ...)
126 __attribute__ ((format (printf, 2, 3)));
128 std::string& stringAppendf(std::string* output, const char* format, ...)
129 __attribute__ ((format (printf, 2, 3)));
132 * A pretty-printer for numbers that appends suffixes of units of the
133 * given type. It prints 4 sig-figs of value with the most
136 * If `addSpace' is true, we put a space between the units suffix and
140 * PRETTY_TIME - s, ms, us, ns, etc.
141 * PRETTY_BYTES - kb, MB, GB, etc (goes up by 2^10 = 1024 each time)
142 * PRETTY_BYTES_METRIC - kb, MB, GB, etc (goes up by 10^3 = 1000 each time)
143 * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
144 * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
146 * @author Mark Rabkin <mrabkin@fb.com>
158 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
161 * Write a hex dump of size bytes starting at ptr to out.
163 * The hex dump is formatted as follows:
165 * for the string "abcdefghijklmnopqrstuvwxyz\x02"
166 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
167 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
169 * that is, we write 16 bytes per line, both as hex bytes and as printable
170 * characters. Non-printable characters are replaced with '.'
171 * Lines are written to out one by one (one StringPiece at a time) without
174 template <class OutIt>
175 void hexDump(const void* ptr, size_t size, OutIt out);
178 * Return the hex dump of size bytes starting at ptr as a string.
180 std::string hexDump(const void* ptr, size_t size);
183 * Return a fbstring containing the description of the given errno value.
184 * Takes care not to overwrite the actual system errno, so calling
185 * errnoStr(errno) is valid.
187 fbstring errnoStr(int err);
190 * Return the demangled (prettyfied) version of a C++ type.
192 * This function tries to produce a human-readable type, but the type name will
193 * be returned unchanged in case of error or if demangling isn't supported on
196 * Use for debugging -- do not rely on demangle() returning anything useful.
198 * This function may allocate memory (and therefore throw).
200 fbstring demangle(const char* name);
201 inline fbstring demangle(const std::type_info& type) {
202 return demangle(type.name());
206 * Debug string for an exception: include type and what().
208 inline fbstring exceptionStr(const std::exception& e) {
209 return folly::to<fbstring>(demangle(typeid(e)), ": ", e.what());
213 * Split a string into a list of tokens by delimiter.
215 * The split interface here supports different output types, selected
216 * at compile time: StringPiece, fbstring, or std::string. If you are
217 * using a vector to hold the output, it detects the type based on
218 * what your vector contains.
220 * You can also use splitTo() to write the output to an arbitrary
221 * OutputIterator (e.g. std::inserter() on a std::set<>), in which
222 * case you have to tell the function the type. (Rationale:
223 * OutputIterators don't have a value_type, so we can't detect the
224 * type in split without being told.)
228 * std::vector<folly::StringPiece> v;
229 * folly::split(":", "asd:bsd", v);
231 * std::set<StringPiece> s;
232 * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
233 * std::inserter(s, s.begin()));
235 * Split also takes a flag (ignoreEmpty) that indicates whether
236 * adjacent tokens should be treated as one separator or not. Note
237 * that unlikely strtok() the default is to treat them as separators.
240 template<class Delim, class String, class OutputType>
241 void split(const Delim& delimiter,
243 std::vector<OutputType>& out,
244 bool ignoreEmpty = false);
246 template<class Delim, class String, class OutputType>
247 void split(const Delim& delimiter,
249 folly::fbvector<OutputType>& out,
250 bool ignoreEmpty = false);
252 template<class OutputValueType, class Delim, class String,
253 class OutputIterator>
254 void splitTo(const Delim& delimiter,
257 bool ignoreEmpty = false);
261 // Hash functions for string and fbstring usable with e.g. hash_map
263 namespace __gnu_cxx {
266 struct hash<folly::basic_fbstring<C> > : private hash<const C*> {
267 size_t operator()(const folly::basic_fbstring<C> & s) const {
268 return hash<const C*>::operator()(s.c_str());
273 struct hash<std::basic_string<C> > : private hash<const C*> {
274 size_t operator()(const std::basic_string<C> & s) const {
275 return hash<const C*>::operator()(s.c_str());
279 } // namespace __gnu_cxx
282 // Hook into boost's type traits
285 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
286 enum { value = true };
290 #include "folly/String-inl.h"