str_cat.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //
  2. // Copyright 2017 The Abseil Authors.
  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. // https://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. // File: str_cat.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // This package contains functions for efficiently concatenating and appending
  21. // strings: `StrCat()` and `StrAppend()`. Most of the work within these routines
  22. // is actually handled through use of a special AlphaNum type, which was
  23. // designed to be used as a parameter type that efficiently manages conversion
  24. // to strings and avoids copies in the above operations.
  25. //
  26. // Any routine accepting either a string or a number may accept `AlphaNum`.
  27. // The basic idea is that by accepting a `const AlphaNum &` as an argument
  28. // to your function, your callers will automagically convert bools, integers,
  29. // and floating point values to strings for you.
  30. //
  31. // NOTE: Use of `AlphaNum` outside of the //absl/strings package is unsupported
  32. // except for the specific case of function parameters of type `AlphaNum` or
  33. // `const AlphaNum &`. In particular, instantiating `AlphaNum` directly as a
  34. // stack variable is not supported.
  35. //
  36. // Conversion from 8-bit values is not accepted because, if it were, then an
  37. // attempt to pass ':' instead of ":" might result in a 58 ending up in your
  38. // result.
  39. //
  40. // Bools convert to "0" or "1". Pointers to types other than `char *` are not
  41. // valid inputs. No output is generated for null `char *` pointers.
  42. //
  43. // Floating point numbers are formatted with six-digit precision, which is
  44. // the default for "std::cout <<" or printf "%g" (the same as "%.6g").
  45. //
  46. // You can convert to hexadecimal output rather than decimal output using the
  47. // `Hex` type contained here. To do so, pass `Hex(my_int)` as a parameter to
  48. // `StrCat()` or `StrAppend()`. You may specify a minimum hex field width using
  49. // a `PadSpec` enum.
  50. //
  51. // -----------------------------------------------------------------------------
  52. #ifndef ABSL_STRINGS_STR_CAT_H_
  53. #define ABSL_STRINGS_STR_CAT_H_
  54. #include <array>
  55. #include <cstdint>
  56. #include <string>
  57. #include <type_traits>
  58. #include <vector>
  59. #include "absl/base/port.h"
  60. #include "absl/strings/numbers.h"
  61. #include "absl/strings/string_view.h"
  62. namespace absl {
  63. ABSL_NAMESPACE_BEGIN
  64. namespace strings_internal {
  65. // AlphaNumBuffer allows a way to pass a string to StrCat without having to do
  66. // memory allocation. It is simply a pair of a fixed-size character array, and
  67. // a size. Please don't use outside of absl, yet.
  68. template <size_t max_size>
  69. struct AlphaNumBuffer {
  70. std::array<char, max_size> data;
  71. size_t size;
  72. };
  73. } // namespace strings_internal
  74. // Enum that specifies the number of significant digits to return in a `Hex` or
  75. // `Dec` conversion and fill character to use. A `kZeroPad2` value, for example,
  76. // would produce hexadecimal strings such as "0a","0f" and a 'kSpacePad5' value
  77. // would produce hexadecimal strings such as " a"," f".
  78. enum PadSpec : uint8_t {
  79. kNoPad = 1,
  80. kZeroPad2,
  81. kZeroPad3,
  82. kZeroPad4,
  83. kZeroPad5,
  84. kZeroPad6,
  85. kZeroPad7,
  86. kZeroPad8,
  87. kZeroPad9,
  88. kZeroPad10,
  89. kZeroPad11,
  90. kZeroPad12,
  91. kZeroPad13,
  92. kZeroPad14,
  93. kZeroPad15,
  94. kZeroPad16,
  95. kZeroPad17,
  96. kZeroPad18,
  97. kZeroPad19,
  98. kZeroPad20,
  99. kSpacePad2 = kZeroPad2 + 64,
  100. kSpacePad3,
  101. kSpacePad4,
  102. kSpacePad5,
  103. kSpacePad6,
  104. kSpacePad7,
  105. kSpacePad8,
  106. kSpacePad9,
  107. kSpacePad10,
  108. kSpacePad11,
  109. kSpacePad12,
  110. kSpacePad13,
  111. kSpacePad14,
  112. kSpacePad15,
  113. kSpacePad16,
  114. kSpacePad17,
  115. kSpacePad18,
  116. kSpacePad19,
  117. kSpacePad20,
  118. };
  119. // -----------------------------------------------------------------------------
  120. // Hex
  121. // -----------------------------------------------------------------------------
  122. //
  123. // `Hex` stores a set of hexadecimal string conversion parameters for use
  124. // within `AlphaNum` string conversions.
  125. struct Hex {
  126. uint64_t value;
  127. uint8_t width;
  128. char fill;
  129. template <typename Int>
  130. explicit Hex(
  131. Int v, PadSpec spec = absl::kNoPad,
  132. typename std::enable_if<sizeof(Int) == 1 &&
  133. !std::is_pointer<Int>::value>::type* = nullptr)
  134. : Hex(spec, static_cast<uint8_t>(v)) {}
  135. template <typename Int>
  136. explicit Hex(
  137. Int v, PadSpec spec = absl::kNoPad,
  138. typename std::enable_if<sizeof(Int) == 2 &&
  139. !std::is_pointer<Int>::value>::type* = nullptr)
  140. : Hex(spec, static_cast<uint16_t>(v)) {}
  141. template <typename Int>
  142. explicit Hex(
  143. Int v, PadSpec spec = absl::kNoPad,
  144. typename std::enable_if<sizeof(Int) == 4 &&
  145. !std::is_pointer<Int>::value>::type* = nullptr)
  146. : Hex(spec, static_cast<uint32_t>(v)) {}
  147. template <typename Int>
  148. explicit Hex(
  149. Int v, PadSpec spec = absl::kNoPad,
  150. typename std::enable_if<sizeof(Int) == 8 &&
  151. !std::is_pointer<Int>::value>::type* = nullptr)
  152. : Hex(spec, static_cast<uint64_t>(v)) {}
  153. template <typename Pointee>
  154. explicit Hex(Pointee* v, PadSpec spec = absl::kNoPad)
  155. : Hex(spec, reinterpret_cast<uintptr_t>(v)) {}
  156. private:
  157. Hex(PadSpec spec, uint64_t v)
  158. : value(v),
  159. width(spec == absl::kNoPad
  160. ? 1
  161. : spec >= absl::kSpacePad2 ? spec - absl::kSpacePad2 + 2
  162. : spec - absl::kZeroPad2 + 2),
  163. fill(spec >= absl::kSpacePad2 ? ' ' : '0') {}
  164. };
  165. // -----------------------------------------------------------------------------
  166. // Dec
  167. // -----------------------------------------------------------------------------
  168. //
  169. // `Dec` stores a set of decimal string conversion parameters for use
  170. // within `AlphaNum` string conversions. Dec is slower than the default
  171. // integer conversion, so use it only if you need padding.
  172. struct Dec {
  173. uint64_t value;
  174. uint8_t width;
  175. char fill;
  176. bool neg;
  177. template <typename Int>
  178. explicit Dec(Int v, PadSpec spec = absl::kNoPad,
  179. typename std::enable_if<(sizeof(Int) <= 8)>::type* = nullptr)
  180. : value(v >= 0 ? static_cast<uint64_t>(v)
  181. : uint64_t{0} - static_cast<uint64_t>(v)),
  182. width(spec == absl::kNoPad
  183. ? 1
  184. : spec >= absl::kSpacePad2 ? spec - absl::kSpacePad2 + 2
  185. : spec - absl::kZeroPad2 + 2),
  186. fill(spec >= absl::kSpacePad2 ? ' ' : '0'),
  187. neg(v < 0) {}
  188. };
  189. // -----------------------------------------------------------------------------
  190. // AlphaNum
  191. // -----------------------------------------------------------------------------
  192. //
  193. // The `AlphaNum` class acts as the main parameter type for `StrCat()` and
  194. // `StrAppend()`, providing efficient conversion of numeric, boolean, and
  195. // hexadecimal values (through the `Hex` type) into strings.
  196. class AlphaNum {
  197. public:
  198. // No bool ctor -- bools convert to an integral type.
  199. // A bool ctor would also convert incoming pointers (bletch).
  200. AlphaNum(int x) // NOLINT(runtime/explicit)
  201. : piece_(digits_,
  202. numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0]) {}
  203. AlphaNum(unsigned int x) // NOLINT(runtime/explicit)
  204. : piece_(digits_,
  205. numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0]) {}
  206. AlphaNum(long x) // NOLINT(*)
  207. : piece_(digits_,
  208. numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0]) {}
  209. AlphaNum(unsigned long x) // NOLINT(*)
  210. : piece_(digits_,
  211. numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0]) {}
  212. AlphaNum(long long x) // NOLINT(*)
  213. : piece_(digits_,
  214. numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0]) {}
  215. AlphaNum(unsigned long long x) // NOLINT(*)
  216. : piece_(digits_,
  217. numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0]) {}
  218. AlphaNum(float f) // NOLINT(runtime/explicit)
  219. : piece_(digits_, numbers_internal::SixDigitsToBuffer(f, digits_)) {}
  220. AlphaNum(double f) // NOLINT(runtime/explicit)
  221. : piece_(digits_, numbers_internal::SixDigitsToBuffer(f, digits_)) {}
  222. AlphaNum(Hex hex); // NOLINT(runtime/explicit)
  223. AlphaNum(Dec dec); // NOLINT(runtime/explicit)
  224. template <size_t size>
  225. AlphaNum( // NOLINT(runtime/explicit)
  226. const strings_internal::AlphaNumBuffer<size>& buf)
  227. : piece_(&buf.data[0], buf.size) {}
  228. AlphaNum(const char* c_str) : piece_(c_str) {} // NOLINT(runtime/explicit)
  229. AlphaNum(absl::string_view pc) : piece_(pc) {} // NOLINT(runtime/explicit)
  230. template <typename Allocator>
  231. AlphaNum( // NOLINT(runtime/explicit)
  232. const std::basic_string<char, std::char_traits<char>, Allocator>& str)
  233. : piece_(str) {}
  234. // Use string literals ":" instead of character literals ':'.
  235. AlphaNum(char c) = delete; // NOLINT(runtime/explicit)
  236. AlphaNum(const AlphaNum&) = delete;
  237. AlphaNum& operator=(const AlphaNum&) = delete;
  238. absl::string_view::size_type size() const { return piece_.size(); }
  239. const char* data() const { return piece_.data(); }
  240. absl::string_view Piece() const { return piece_; }
  241. // Normal enums are already handled by the integer formatters.
  242. // This overload matches only scoped enums.
  243. template <typename T,
  244. typename = typename std::enable_if<
  245. std::is_enum<T>{} && !std::is_convertible<T, int>{}>::type>
  246. AlphaNum(T e) // NOLINT(runtime/explicit)
  247. : AlphaNum(static_cast<typename std::underlying_type<T>::type>(e)) {}
  248. // vector<bool>::reference and const_reference require special help to
  249. // convert to `AlphaNum` because it requires two user defined conversions.
  250. template <
  251. typename T,
  252. typename std::enable_if<
  253. std::is_class<T>::value &&
  254. (std::is_same<T, std::vector<bool>::reference>::value ||
  255. std::is_same<T, std::vector<bool>::const_reference>::value)>::type* =
  256. nullptr>
  257. AlphaNum(T e) : AlphaNum(static_cast<bool>(e)) {} // NOLINT(runtime/explicit)
  258. private:
  259. absl::string_view piece_;
  260. char digits_[numbers_internal::kFastToBufferSize];
  261. };
  262. // -----------------------------------------------------------------------------
  263. // StrCat()
  264. // -----------------------------------------------------------------------------
  265. //
  266. // Merges given strings or numbers, using no delimiter(s), returning the merged
  267. // result as a string.
  268. //
  269. // `StrCat()` is designed to be the fastest possible way to construct a string
  270. // out of a mix of raw C strings, string_views, strings, bool values,
  271. // and numeric values.
  272. //
  273. // Don't use `StrCat()` for user-visible strings. The localization process
  274. // works poorly on strings built up out of fragments.
  275. //
  276. // For clarity and performance, don't use `StrCat()` when appending to a
  277. // string. Use `StrAppend()` instead. In particular, avoid using any of these
  278. // (anti-)patterns:
  279. //
  280. // str.append(StrCat(...))
  281. // str += StrCat(...)
  282. // str = StrCat(str, ...)
  283. //
  284. // The last case is the worst, with a potential to change a loop
  285. // from a linear time operation with O(1) dynamic allocations into a
  286. // quadratic time operation with O(n) dynamic allocations.
  287. //
  288. // See `StrAppend()` below for more information.
  289. namespace strings_internal {
  290. // Do not call directly - this is not part of the public API.
  291. std::string CatPieces(std::initializer_list<absl::string_view> pieces);
  292. void AppendPieces(std::string* dest,
  293. std::initializer_list<absl::string_view> pieces);
  294. } // namespace strings_internal
  295. ABSL_MUST_USE_RESULT inline std::string StrCat() { return std::string(); }
  296. ABSL_MUST_USE_RESULT inline std::string StrCat(const AlphaNum& a) {
  297. return std::string(a.data(), a.size());
  298. }
  299. ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b);
  300. ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b,
  301. const AlphaNum& c);
  302. ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b,
  303. const AlphaNum& c, const AlphaNum& d);
  304. // Support 5 or more arguments
  305. template <typename... AV>
  306. ABSL_MUST_USE_RESULT inline std::string StrCat(
  307. const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d,
  308. const AlphaNum& e, const AV&... args) {
  309. return strings_internal::CatPieces(
  310. {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(),
  311. static_cast<const AlphaNum&>(args).Piece()...});
  312. }
  313. // -----------------------------------------------------------------------------
  314. // StrAppend()
  315. // -----------------------------------------------------------------------------
  316. //
  317. // Appends a string or set of strings to an existing string, in a similar
  318. // fashion to `StrCat()`.
  319. //
  320. // WARNING: `StrAppend(&str, a, b, c, ...)` requires that none of the
  321. // a, b, c, parameters be a reference into str. For speed, `StrAppend()` does
  322. // not try to check each of its input arguments to be sure that they are not
  323. // a subset of the string being appended to. That is, while this will work:
  324. //
  325. // std::string s = "foo";
  326. // s += s;
  327. //
  328. // This output is undefined:
  329. //
  330. // std::string s = "foo";
  331. // StrAppend(&s, s);
  332. //
  333. // This output is undefined as well, since `absl::string_view` does not own its
  334. // data:
  335. //
  336. // std::string s = "foobar";
  337. // absl::string_view p = s;
  338. // StrAppend(&s, p);
  339. inline void StrAppend(std::string*) {}
  340. void StrAppend(std::string* dest, const AlphaNum& a);
  341. void StrAppend(std::string* dest, const AlphaNum& a, const AlphaNum& b);
  342. void StrAppend(std::string* dest, const AlphaNum& a, const AlphaNum& b,
  343. const AlphaNum& c);
  344. void StrAppend(std::string* dest, const AlphaNum& a, const AlphaNum& b,
  345. const AlphaNum& c, const AlphaNum& d);
  346. // Support 5 or more arguments
  347. template <typename... AV>
  348. inline void StrAppend(std::string* dest, const AlphaNum& a, const AlphaNum& b,
  349. const AlphaNum& c, const AlphaNum& d, const AlphaNum& e,
  350. const AV&... args) {
  351. strings_internal::AppendPieces(
  352. dest, {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(),
  353. static_cast<const AlphaNum&>(args).Piece()...});
  354. }
  355. // Helper function for the future StrCat default floating-point format, %.6g
  356. // This is fast.
  357. inline strings_internal::AlphaNumBuffer<
  358. numbers_internal::kSixDigitsToBufferSize>
  359. SixDigits(double d) {
  360. strings_internal::AlphaNumBuffer<numbers_internal::kSixDigitsToBufferSize>
  361. result;
  362. result.size = numbers_internal::SixDigitsToBuffer(d, &result.data[0]);
  363. return result;
  364. }
  365. ABSL_NAMESPACE_END
  366. } // namespace absl
  367. #endif // ABSL_STRINGS_STR_CAT_H_