proxygen
String.h
Go to the documentation of this file.
1 /*
2  * Copyright 2011-present 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 #pragma once
18 #define FOLLY_STRING_H_
19 
20 #include <cstdarg>
21 #include <exception>
22 #include <string>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <vector>
26 
27 #include <folly/Conv.h>
28 #include <folly/ExceptionString.h>
29 #include <folly/FBString.h>
30 #include <folly/FBVector.h>
31 #include <folly/Portability.h>
32 #include <folly/Range.h>
33 #include <folly/ScopeGuard.h>
34 #include <folly/Traits.h>
35 
36 // Compatibility function, to make sure toStdString(s) can be called
37 // to convert a std::string or fbstring variable s into type std::string
38 // with very little overhead if s was already std::string
39 namespace folly {
40 
42  return std::string(s.data(), s.size());
43 }
44 
45 inline 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.
52  return std::move(s);
53 }
54 
73 template <class String>
74 void cEscape(StringPiece str, String& out);
75 
79 template <class String>
80 String cEscape(StringPiece str) {
81  String out;
82  cEscape(str, out);
83  return out;
84 }
85 
100 template <class String>
101 void cUnescape(StringPiece str, String& out, bool strict = true);
102 
106 template <class String>
107 String cUnescape(StringPiece str, bool strict = true) {
108  String out;
109  cUnescape(str, out, strict);
110  return out;
111 }
112 
121 enum class UriEscapeMode : unsigned char {
122  // The values are meaningful, see generate_escape_tables.py
123  ALL = 0,
124  QUERY = 1,
125  PATH = 2
126 };
127 template <class String>
128 void uriEscape(
129  StringPiece str,
130  String& out,
132 
136 template <class String>
138  String out;
139  uriEscape(str, out, mode);
140  return out;
141 }
142 
149 template <class String>
150 void uriUnescape(
151  StringPiece str,
152  String& out,
154 
158 template <class String>
160  String out;
161  uriUnescape(str, out, mode);
162  return out;
163 }
164 
173 
174 /* Similar to stringPrintf, with different signature. */
175 void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
177 
180  FOLLY_PRINTF_FORMAT const char* format,
181  ...) FOLLY_PRINTF_FORMAT_ATTR(2, 3);
182 
189 std::string stringVPrintf(const char* format, va_list ap);
190 void stringVPrintf(std::string* out, const char* format, va_list ap);
191 std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
192 
212 template <class OutputString>
213 void backslashify(
214  folly::StringPiece input,
215  OutputString& output,
216  bool hex_style = false);
217 
218 template <class OutputString = std::string>
219 OutputString backslashify(StringPiece input, bool hex_style = false) {
220  OutputString output;
221  backslashify(input, output, hex_style);
222  return output;
223 }
224 
236 template <class String1, class String2>
237 void humanify(const String1& input, String2& output);
238 
239 template <class String>
240 String humanify(const String& input) {
241  String output;
242  humanify(input, output);
243  return output;
244 }
245 
253 template <class InputString, class OutputString>
254 bool hexlify(
255  const InputString& input,
256  OutputString& output,
257  bool append = false);
258 
259 template <class OutputString = std::string>
260 OutputString hexlify(ByteRange input) {
261  OutputString output;
262  if (!hexlify(input, output)) {
263  // hexlify() currently always returns true, so this can't really happen
264  throw std::runtime_error("hexlify failed");
265  }
266  return output;
267 }
268 
269 template <class OutputString = std::string>
270 OutputString hexlify(StringPiece input) {
271  return hexlify<OutputString>(ByteRange{input});
272 }
273 
278 template <class InputString, class OutputString>
279 bool unhexlify(const InputString& input, OutputString& output);
280 
281 template <class OutputString = std::string>
282 OutputString unhexlify(StringPiece input) {
283  OutputString output;
284  if (!unhexlify(input, output)) {
285  // unhexlify() fails if the input has non-hexidecimal characters,
286  // or if it doesn't consist of a whole number of bytes
287  throw std::domain_error("unhexlify() called with non-hex input");
288  }
289  return output;
290 }
291 
317 
323 
327 
330 };
331 
332 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
333 
350 double prettyToDouble(
351  folly::StringPiece* const prettyString,
352  const PrettyType type);
353 
359 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
360 
375 template <class OutIt>
376 void hexDump(const void* ptr, size_t size, OutIt out);
377 
381 std::string hexDump(const void* ptr, size_t size);
382 
388 fbstring errnoStr(int err);
389 
390 /*
391  * Split a string into a list of tokens by delimiter.
392  *
393  * The split interface here supports different output types, selected
394  * at compile time: StringPiece, fbstring, or std::string. If you are
395  * using a vector to hold the output, it detects the type based on
396  * what your vector contains. If the output vector is not empty, split
397  * will append to the end of the vector.
398  *
399  * You can also use splitTo() to write the output to an arbitrary
400  * OutputIterator (e.g. std::inserter() on a std::set<>), in which
401  * case you have to tell the function the type. (Rationale:
402  * OutputIterators don't have a value_type, so we can't detect the
403  * type in splitTo without being told.)
404  *
405  * Examples:
406  *
407  * std::vector<folly::StringPiece> v;
408  * folly::split(":", "asd:bsd", v);
409  *
410  * std::set<StringPiece> s;
411  * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
412  * std::inserter(s, s.begin()));
413  *
414  * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
415  * delimiters should be treated as one single separator (ignoring empty tokens)
416  * or not (generating empty tokens).
417  */
418 
419 template <class Delim, class String, class OutputType>
420 void split(
421  const Delim& delimiter,
422  const String& input,
423  std::vector<OutputType>& out,
424  const bool ignoreEmpty = false);
425 
426 template <class Delim, class String, class OutputType>
427 void split(
428  const Delim& delimiter,
429  const String& input,
431  const bool ignoreEmpty = false);
432 
433 template <
434  class OutputValueType,
435  class Delim,
436  class String,
437  class OutputIterator>
438 void splitTo(
439  const Delim& delimiter,
440  const String& input,
441  OutputIterator out,
442  const bool ignoreEmpty = false);
443 
444 /*
445  * Split a string into a fixed number of string pieces and/or numeric types
446  * by delimiter. Conversions are supported for any type which folly:to<> can
447  * target, including all overloads of parseTo(). Returns 'true' if the fields
448  * were all successfully populated. Returns 'false' if there were too few
449  * fields in the input, or too many fields if exact=true. Casting exceptions
450  * will not be caught.
451  *
452  * Examples:
453  *
454  * folly::StringPiece name, key, value;
455  * if (folly::split('\t', line, name, key, value))
456  * ...
457  *
458  * folly::StringPiece name;
459  * double value;
460  * int id;
461  * if (folly::split('\t', line, name, value, id))
462  * ...
463  *
464  * The 'exact' template parameter specifies how the function behaves when too
465  * many fields are present in the input string. When 'exact' is set to its
466  * default value of 'true', a call to split will fail if the number of fields in
467  * the input string does not exactly match the number of output parameters
468  * passed. If 'exact' is overridden to 'false', all remaining fields will be
469  * stored, unsplit, in the last field, as shown below:
470  *
471  * folly::StringPiece x, y.
472  * if (folly::split<false>(':', "a:b:c", x, y))
473  * assert(x == "a" && y == "b:c");
474  *
475  * Note that this will likely not work if the last field's target is of numeric
476  * type, in which case folly::to<> will throw an exception.
477  */
478 namespace detail {
479 template <typename Void, typename OutputType>
481 
482 template <>
483 struct IsConvertible<void, decltype(std::ignore)> : std::true_type {};
484 
485 template <typename OutputType>
487  void_t<decltype(parseTo(StringPiece{}, std::declval<OutputType&>()))>,
489 } // namespace detail
490 template <typename OutputType>
491 struct IsConvertible : detail::IsConvertible<void, OutputType> {};
492 
493 template <bool exact = true, class Delim, class... OutputTypes>
494 typename std::enable_if<
496  sizeof...(OutputTypes) >= 1,
497  bool>::type
498 split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
499 
500 /*
501  * Join list of tokens.
502  *
503  * Stores a string representation of tokens in the same order with
504  * deliminer between each element.
505  */
506 
507 template <class Delim, class Iterator, class String>
508 void join(const Delim& delimiter, Iterator begin, Iterator end, String& output);
509 
510 template <class Delim, class Container, class String>
511 void join(const Delim& delimiter, const Container& container, String& output) {
512  join(delimiter, container.begin(), container.end(), output);
513 }
514 
515 template <class Delim, class Value, class String>
516 void join(
517  const Delim& delimiter,
518  const std::initializer_list<Value>& values,
519  String& output) {
520  join(delimiter, values.begin(), values.end(), output);
521 }
522 
523 template <class Delim, class Container>
524 std::string join(const Delim& delimiter, const Container& container) {
526  join(delimiter, container.begin(), container.end(), output);
527  return output;
528 }
529 
530 template <class Delim, class Value>
532  const Delim& delimiter,
533  const std::initializer_list<Value>& values) {
535  join(delimiter, values.begin(), values.end(), output);
536  return output;
537 }
538 
539 template <
540  class Delim,
541  class Iterator,
542  typename std::enable_if<std::is_base_of<
543  std::forward_iterator_tag,
544  typename std::iterator_traits<Iterator>::iterator_category>::value>::
545  type* = nullptr>
546 std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
548  join(delimiter, begin, end, output);
549  return output;
550 }
551 
557 
563 
569  return ltrimWhitespace(rtrimWhitespace(sp));
570 }
571 
578  return ltrimWhitespace(sp);
579 }
580 
591 
599 void toLowerAscii(char* str, size_t length);
600 
602  toLowerAscii(str.begin(), str.size());
603 }
604 
605 inline void toLowerAscii(std::string& str) {
606  // str[0] is legal also if the string is empty.
607  toLowerAscii(&str[0], str.size());
608 }
609 
610 } // namespace folly
611 
612 #include <folly/String-inl.h>
StringPiece ltrimWhitespace(StringPiece sp)
Definition: String.cpp:131
void * ptr
size_type size() const
Definition: FBString.h:1337
void splitTo(const Delim &delimiter, const String &input, OutputIterator out, bool ignoreEmpty)
Definition: String-inl.h:412
bool unhexlify(const InputString &input, OutputString &output)
Definition: String-inl.h:616
#define FOLLY_PRINTF_FORMAT
Definition: Portability.h:47
UriEscapeMode
Definition: String.h:121
void uriUnescape(StringPiece str, String &out, UriEscapeMode mode)
Definition: String-inl.h:201
PskType type
StringPiece skipWhitespace(StringPiece sp)
Definition: String.h:577
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::string stringVPrintf(const char *format, va_list ap)
Definition: String.cpp:232
STL namespace.
void append(std::unique_ptr< IOBuf > &buf, StringPiece str)
Definition: IOBufTest.cpp:37
constexpr size_type size() const
Definition: Range.h:431
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
double val
Definition: String.cpp:273
std::string stringPrintf(const char *format,...)
Definition: String.cpp:223
std::string & stringVAppendf(std::string *output, const char *format, va_list ap)
Definition: String.cpp:250
void humanify(const String1 &input, String2 &output)
Definition: String-inl.h:552
FOLLY_NODISCARD std::enable_if< std::is_arithmetic< Tgt >::value, Expected< StringPiece, ConversionCode > >::type parseTo(StringPiece src, Tgt &out)
Definition: Conv.h:1182
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
std::string toStdString(const folly::fbstring &s)
Definition: String.h:41
void split(const Delim &delimiter, const String &input, std::vector< OutputType > &out, bool ignoreEmpty)
Definition: String-inl.h:382
bool_constant< true > true_type
Definition: gtest-port.h:2210
std::string prettyPrint(double val, PrettyType type, bool addSpace)
Definition: String.cpp:386
std::string stripLeftMargin(std::string s)
Definition: String.cpp:704
folly::Optional< PskKeyExchangeMode > mode
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
const value_type * data() const
Definition: FBString.h:1716
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
void uriEscape(StringPiece str, String &out, UriEscapeMode mode)
Definition: String-inl.h:166
void cUnescape(StringPiece str, String &out, bool strict)
Definition: String-inl.h:86
StringPiece rtrimWhitespace(StringPiece sp)
Definition: String.cpp:149
void hexDump(const void *ptr, size_t size, OutIt out)
Definition: String-inl.h:645
type_t< void, Ts... > void_t
Definition: Traits.h:302
std::string & stringAppendf(std::string *output, const char *format,...)
Definition: String.cpp:240
fbstring errnoStr(int err)
Definition: String.cpp:463
double prettyToDouble(folly::StringPiece *const prettyString, const PrettyType type)
Definition: String.cpp:416
constexpr Iter begin() const
Definition: Range.h:452
void toLowerAscii(char *str, size_t length)
Definition: String.cpp:601
void backslashify(folly::StringPiece input, OutputString &output, bool hex_style)
Definition: String-inl.h:507
const char * string
Definition: Conv.cpp:212
static set< string > s
StringPiece trimWhitespace(StringPiece sp)
Definition: String.h:568
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
bool_constant< false > false_type
Definition: gtest-port.h:2209
void join(const Delim &delimiter, Iterator begin, Iterator end, String &output)
Definition: String-inl.h:498
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
#define FOLLY_PRINTF_FORMAT_ATTR(format_param, dots_param)
Definition: Portability.h:48
bool hexlify(const InputString &input, OutputString &output, bool append_output)
Definition: String-inl.h:596
std::vector< int > values(1'000)
void cEscape(StringPiece str, String &out)
Definition: String-inl.h:39