str_split.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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_split.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // This file contains functions for splitting strings. It defines the main
  21. // `StrSplit()` function, several delimiters for determining the boundaries on
  22. // which to split the string, and predicates for filtering delimited results.
  23. // `StrSplit()` adapts the returned collection to the type specified by the
  24. // caller.
  25. //
  26. // Example:
  27. //
  28. // // Splits the given string on commas. Returns the results in a
  29. // // vector of strings.
  30. // std::vector<TString> v = y_absl::StrSplit("a,b,c", ',');
  31. // // Can also use ","
  32. // // v[0] == "a", v[1] == "b", v[2] == "c"
  33. //
  34. // See StrSplit() below for more information.
  35. #ifndef Y_ABSL_STRINGS_STR_SPLIT_H_
  36. #define Y_ABSL_STRINGS_STR_SPLIT_H_
  37. #include <algorithm>
  38. #include <cstddef>
  39. #include <map>
  40. #include <set>
  41. #include <util/generic/string.h>
  42. #include <utility>
  43. #include <vector>
  44. #include "y_absl/base/internal/raw_logging.h"
  45. #include "y_absl/base/macros.h"
  46. #include "y_absl/strings/internal/str_split_internal.h"
  47. #include "y_absl/strings/string_view.h"
  48. #include "y_absl/strings/strip.h"
  49. namespace y_absl {
  50. Y_ABSL_NAMESPACE_BEGIN
  51. //------------------------------------------------------------------------------
  52. // Delimiters
  53. //------------------------------------------------------------------------------
  54. //
  55. // `StrSplit()` uses delimiters to define the boundaries between elements in the
  56. // provided input. Several `Delimiter` types are defined below. If a string
  57. // (`const char*`, `TString`, or `y_absl::string_view`) is passed in place of
  58. // an explicit `Delimiter` object, `StrSplit()` treats it the same way as if it
  59. // were passed a `ByString` delimiter.
  60. //
  61. // A `Delimiter` is an object with a `Find()` function that knows how to find
  62. // the first occurrence of itself in a given `y_absl::string_view`.
  63. //
  64. // The following `Delimiter` types are available for use within `StrSplit()`:
  65. //
  66. // - `ByString` (default for string arguments)
  67. // - `ByChar` (default for a char argument)
  68. // - `ByAnyChar`
  69. // - `ByLength`
  70. // - `MaxSplits`
  71. //
  72. // A Delimiter's `Find()` member function will be passed an input `text` that is
  73. // to be split and a position (`pos`) to begin searching for the next delimiter
  74. // in `text`. The returned y_absl::string_view should refer to the next occurrence
  75. // (after `pos`) of the represented delimiter; this returned y_absl::string_view
  76. // represents the next location where the input `text` should be broken.
  77. //
  78. // The returned y_absl::string_view may be zero-length if the Delimiter does not
  79. // represent a part of the string (e.g., a fixed-length delimiter). If no
  80. // delimiter is found in the input `text`, a zero-length y_absl::string_view
  81. // referring to `text.end()` should be returned (e.g.,
  82. // `text.substr(text.size())`). It is important that the returned
  83. // y_absl::string_view always be within the bounds of the input `text` given as an
  84. // argument--it must not refer to a string that is physically located outside of
  85. // the given string.
  86. //
  87. // The following example is a simple Delimiter object that is created with a
  88. // single char and will look for that char in the text passed to the `Find()`
  89. // function:
  90. //
  91. // struct SimpleDelimiter {
  92. // const char c_;
  93. // explicit SimpleDelimiter(char c) : c_(c) {}
  94. // y_absl::string_view Find(y_absl::string_view text, size_t pos) {
  95. // auto found = text.find(c_, pos);
  96. // if (found == y_absl::string_view::npos)
  97. // return text.substr(text.size());
  98. //
  99. // return text.substr(found, 1);
  100. // }
  101. // };
  102. // ByString
  103. //
  104. // A sub-string delimiter. If `StrSplit()` is passed a string in place of a
  105. // `Delimiter` object, the string will be implicitly converted into a
  106. // `ByString` delimiter.
  107. //
  108. // Example:
  109. //
  110. // // Because a string literal is converted to an `y_absl::ByString`,
  111. // // the following two splits are equivalent.
  112. //
  113. // std::vector<TString> v1 = y_absl::StrSplit("a, b, c", ", ");
  114. //
  115. // using y_absl::ByString;
  116. // std::vector<TString> v2 = y_absl::StrSplit("a, b, c",
  117. // ByString(", "));
  118. // // v[0] == "a", v[1] == "b", v[2] == "c"
  119. class ByString {
  120. public:
  121. explicit ByString(y_absl::string_view sp);
  122. y_absl::string_view Find(y_absl::string_view text, size_t pos) const;
  123. private:
  124. const TString delimiter_;
  125. };
  126. // ByChar
  127. //
  128. // A single character delimiter. `ByChar` is functionally equivalent to a
  129. // 1-char string within a `ByString` delimiter, but slightly more efficient.
  130. //
  131. // Example:
  132. //
  133. // // Because a char literal is converted to a y_absl::ByChar,
  134. // // the following two splits are equivalent.
  135. // std::vector<TString> v1 = y_absl::StrSplit("a,b,c", ',');
  136. // using y_absl::ByChar;
  137. // std::vector<TString> v2 = y_absl::StrSplit("a,b,c", ByChar(','));
  138. // // v[0] == "a", v[1] == "b", v[2] == "c"
  139. //
  140. // `ByChar` is also the default delimiter if a single character is given
  141. // as the delimiter to `StrSplit()`. For example, the following calls are
  142. // equivalent:
  143. //
  144. // std::vector<TString> v = y_absl::StrSplit("a-b", '-');
  145. //
  146. // using y_absl::ByChar;
  147. // std::vector<TString> v = y_absl::StrSplit("a-b", ByChar('-'));
  148. //
  149. class ByChar {
  150. public:
  151. explicit ByChar(char c) : c_(c) {}
  152. y_absl::string_view Find(y_absl::string_view text, size_t pos) const;
  153. private:
  154. char c_;
  155. };
  156. // ByAnyChar
  157. //
  158. // A delimiter that will match any of the given byte-sized characters within
  159. // its provided string.
  160. //
  161. // Note: this delimiter works with single-byte string data, but does not work
  162. // with variable-width encodings, such as UTF-8.
  163. //
  164. // Example:
  165. //
  166. // using y_absl::ByAnyChar;
  167. // std::vector<TString> v = y_absl::StrSplit("a,b=c", ByAnyChar(",="));
  168. // // v[0] == "a", v[1] == "b", v[2] == "c"
  169. //
  170. // If `ByAnyChar` is given the empty string, it behaves exactly like
  171. // `ByString` and matches each individual character in the input string.
  172. //
  173. class ByAnyChar {
  174. public:
  175. explicit ByAnyChar(y_absl::string_view sp);
  176. y_absl::string_view Find(y_absl::string_view text, size_t pos) const;
  177. private:
  178. const TString delimiters_;
  179. };
  180. // ByLength
  181. //
  182. // A delimiter for splitting into equal-length strings. The length argument to
  183. // the constructor must be greater than 0.
  184. //
  185. // Note: this delimiter works with single-byte string data, but does not work
  186. // with variable-width encodings, such as UTF-8.
  187. //
  188. // Example:
  189. //
  190. // using y_absl::ByLength;
  191. // std::vector<TString> v = y_absl::StrSplit("123456789", ByLength(3));
  192. // // v[0] == "123", v[1] == "456", v[2] == "789"
  193. //
  194. // Note that the string does not have to be a multiple of the fixed split
  195. // length. In such a case, the last substring will be shorter.
  196. //
  197. // using y_absl::ByLength;
  198. // std::vector<TString> v = y_absl::StrSplit("12345", ByLength(2));
  199. //
  200. // // v[0] == "12", v[1] == "34", v[2] == "5"
  201. class ByLength {
  202. public:
  203. explicit ByLength(ptrdiff_t length);
  204. y_absl::string_view Find(y_absl::string_view text, size_t pos) const;
  205. private:
  206. const ptrdiff_t length_;
  207. };
  208. namespace strings_internal {
  209. // A traits-like metafunction for selecting the default Delimiter object type
  210. // for a particular Delimiter type. The base case simply exposes type Delimiter
  211. // itself as the delimiter's Type. However, there are specializations for
  212. // string-like objects that map them to the ByString delimiter object.
  213. // This allows functions like y_absl::StrSplit() and y_absl::MaxSplits() to accept
  214. // string-like objects (e.g., ',') as delimiter arguments but they will be
  215. // treated as if a ByString delimiter was given.
  216. template <typename Delimiter>
  217. struct SelectDelimiter {
  218. using type = Delimiter;
  219. };
  220. template <>
  221. struct SelectDelimiter<char> {
  222. using type = ByChar;
  223. };
  224. template <>
  225. struct SelectDelimiter<char*> {
  226. using type = ByString;
  227. };
  228. template <>
  229. struct SelectDelimiter<const char*> {
  230. using type = ByString;
  231. };
  232. template <>
  233. struct SelectDelimiter<y_absl::string_view> {
  234. using type = ByString;
  235. };
  236. template <>
  237. struct SelectDelimiter<TString> {
  238. using type = ByString;
  239. };
  240. // Wraps another delimiter and sets a max number of matches for that delimiter.
  241. template <typename Delimiter>
  242. class MaxSplitsImpl {
  243. public:
  244. MaxSplitsImpl(Delimiter delimiter, int limit)
  245. : delimiter_(delimiter), limit_(limit), count_(0) {}
  246. y_absl::string_view Find(y_absl::string_view text, size_t pos) {
  247. if (count_++ == limit_) {
  248. return y_absl::string_view(text.data() + text.size(),
  249. 0); // No more matches.
  250. }
  251. return delimiter_.Find(text, pos);
  252. }
  253. private:
  254. Delimiter delimiter_;
  255. const int limit_;
  256. int count_;
  257. };
  258. } // namespace strings_internal
  259. // MaxSplits()
  260. //
  261. // A delimiter that limits the number of matches which can occur to the passed
  262. // `limit`. The last element in the returned collection will contain all
  263. // remaining unsplit pieces, which may contain instances of the delimiter.
  264. // The collection will contain at most `limit` + 1 elements.
  265. // Example:
  266. //
  267. // using y_absl::MaxSplits;
  268. // std::vector<TString> v = y_absl::StrSplit("a,b,c", MaxSplits(',', 1));
  269. //
  270. // // v[0] == "a", v[1] == "b,c"
  271. template <typename Delimiter>
  272. inline strings_internal::MaxSplitsImpl<
  273. typename strings_internal::SelectDelimiter<Delimiter>::type>
  274. MaxSplits(Delimiter delimiter, int limit) {
  275. typedef
  276. typename strings_internal::SelectDelimiter<Delimiter>::type DelimiterType;
  277. return strings_internal::MaxSplitsImpl<DelimiterType>(
  278. DelimiterType(delimiter), limit);
  279. }
  280. //------------------------------------------------------------------------------
  281. // Predicates
  282. //------------------------------------------------------------------------------
  283. //
  284. // Predicates filter the results of a `StrSplit()` by determining whether or not
  285. // a resultant element is included in the result set. A predicate may be passed
  286. // as an optional third argument to the `StrSplit()` function.
  287. //
  288. // Predicates are unary functions (or functors) that take a single
  289. // `y_absl::string_view` argument and return a bool indicating whether the
  290. // argument should be included (`true`) or excluded (`false`).
  291. //
  292. // Predicates are useful when filtering out empty substrings. By default, empty
  293. // substrings may be returned by `StrSplit()`, which is similar to the way split
  294. // functions work in other programming languages.
  295. // AllowEmpty()
  296. //
  297. // Always returns `true`, indicating that all strings--including empty
  298. // strings--should be included in the split output. This predicate is not
  299. // strictly needed because this is the default behavior of `StrSplit()`;
  300. // however, it might be useful at some call sites to make the intent explicit.
  301. //
  302. // Example:
  303. //
  304. // std::vector<TString> v = y_absl::StrSplit(" a , ,,b,", ',', AllowEmpty());
  305. //
  306. // // v[0] == " a ", v[1] == " ", v[2] == "", v[3] = "b", v[4] == ""
  307. struct AllowEmpty {
  308. bool operator()(y_absl::string_view) const { return true; }
  309. };
  310. // SkipEmpty()
  311. //
  312. // Returns `false` if the given `y_absl::string_view` is empty, indicating that
  313. // `StrSplit()` should omit the empty string.
  314. //
  315. // Example:
  316. //
  317. // std::vector<TString> v = y_absl::StrSplit(",a,,b,", ',', SkipEmpty());
  318. //
  319. // // v[0] == "a", v[1] == "b"
  320. //
  321. // Note: `SkipEmpty()` does not consider a string containing only whitespace
  322. // to be empty. To skip such whitespace as well, use the `SkipWhitespace()`
  323. // predicate.
  324. struct SkipEmpty {
  325. bool operator()(y_absl::string_view sp) const { return !sp.empty(); }
  326. };
  327. // SkipWhitespace()
  328. //
  329. // Returns `false` if the given `y_absl::string_view` is empty *or* contains only
  330. // whitespace, indicating that `StrSplit()` should omit the string.
  331. //
  332. // Example:
  333. //
  334. // std::vector<TString> v = y_absl::StrSplit(" a , ,,b,",
  335. // ',', SkipWhitespace());
  336. // // v[0] == " a ", v[1] == "b"
  337. //
  338. // // SkipEmpty() would return whitespace elements
  339. // std::vector<TString> v = y_absl::StrSplit(" a , ,,b,", ',', SkipEmpty());
  340. // // v[0] == " a ", v[1] == " ", v[2] == "b"
  341. struct SkipWhitespace {
  342. bool operator()(y_absl::string_view sp) const {
  343. sp = y_absl::StripAsciiWhitespace(sp);
  344. return !sp.empty();
  345. }
  346. };
  347. template <typename T>
  348. using EnableSplitIfString =
  349. typename std::enable_if<std::is_same<T, TString>::value ||
  350. std::is_same<T, const TString>::value,
  351. int>::type;
  352. //------------------------------------------------------------------------------
  353. // StrSplit()
  354. //------------------------------------------------------------------------------
  355. // StrSplit()
  356. //
  357. // Splits a given string based on the provided `Delimiter` object, returning the
  358. // elements within the type specified by the caller. Optionally, you may pass a
  359. // `Predicate` to `StrSplit()` indicating whether to include or exclude the
  360. // resulting element within the final result set. (See the overviews for
  361. // Delimiters and Predicates above.)
  362. //
  363. // Example:
  364. //
  365. // std::vector<TString> v = y_absl::StrSplit("a,b,c,d", ',');
  366. // // v[0] == "a", v[1] == "b", v[2] == "c", v[3] == "d"
  367. //
  368. // You can also provide an explicit `Delimiter` object:
  369. //
  370. // Example:
  371. //
  372. // using y_absl::ByAnyChar;
  373. // std::vector<TString> v = y_absl::StrSplit("a,b=c", ByAnyChar(",="));
  374. // // v[0] == "a", v[1] == "b", v[2] == "c"
  375. //
  376. // See above for more information on delimiters.
  377. //
  378. // By default, empty strings are included in the result set. You can optionally
  379. // include a third `Predicate` argument to apply a test for whether the
  380. // resultant element should be included in the result set:
  381. //
  382. // Example:
  383. //
  384. // std::vector<TString> v = y_absl::StrSplit(" a , ,,b,",
  385. // ',', SkipWhitespace());
  386. // // v[0] == " a ", v[1] == "b"
  387. //
  388. // See above for more information on predicates.
  389. //
  390. //------------------------------------------------------------------------------
  391. // StrSplit() Return Types
  392. //------------------------------------------------------------------------------
  393. //
  394. // The `StrSplit()` function adapts the returned collection to the collection
  395. // specified by the caller (e.g. `std::vector` above). The returned collections
  396. // may contain `TString`, `y_absl::string_view` (in which case the original
  397. // string being split must ensure that it outlives the collection), or any
  398. // object that can be explicitly created from an `y_absl::string_view`. This
  399. // behavior works for:
  400. //
  401. // 1) All standard STL containers including `std::vector`, `std::list`,
  402. // `std::deque`, `std::set`,`std::multiset`, 'std::map`, and `std::multimap`
  403. // 2) `std::pair` (which is not actually a container). See below.
  404. //
  405. // Example:
  406. //
  407. // // The results are returned as `y_absl::string_view` objects. Note that we
  408. // // have to ensure that the input string outlives any results.
  409. // std::vector<y_absl::string_view> v = y_absl::StrSplit("a,b,c", ',');
  410. //
  411. // // Stores results in a std::set<TString>, which also performs
  412. // // de-duplication and orders the elements in ascending order.
  413. // std::set<TString> a = y_absl::StrSplit("b,a,c,a,b", ',');
  414. // // v[0] == "a", v[1] == "b", v[2] = "c"
  415. //
  416. // // `StrSplit()` can be used within a range-based for loop, in which case
  417. // // each element will be of type `y_absl::string_view`.
  418. // std::vector<TString> v;
  419. // for (const auto sv : y_absl::StrSplit("a,b,c", ',')) {
  420. // if (sv != "b") v.emplace_back(sv);
  421. // }
  422. // // v[0] == "a", v[1] == "c"
  423. //
  424. // // Stores results in a map. The map implementation assumes that the input
  425. // // is provided as a series of key/value pairs. For example, the 0th element
  426. // // resulting from the split will be stored as a key to the 1st element. If
  427. // // an odd number of elements are resolved, the last element is paired with
  428. // // a default-constructed value (e.g., empty string).
  429. // std::map<TString, TString> m = y_absl::StrSplit("a,b,c", ',');
  430. // // m["a"] == "b", m["c"] == "" // last component value equals ""
  431. //
  432. // Splitting to `std::pair` is an interesting case because it can hold only two
  433. // elements and is not a collection type. When splitting to a `std::pair` the
  434. // first two split strings become the `std::pair` `.first` and `.second`
  435. // members, respectively. The remaining split substrings are discarded. If there
  436. // are less than two split substrings, the empty string is used for the
  437. // corresponding `std::pair` member.
  438. //
  439. // Example:
  440. //
  441. // // Stores first two split strings as the members in a std::pair.
  442. // std::pair<TString, TString> p = y_absl::StrSplit("a,b,c", ',');
  443. // // p.first == "a", p.second == "b" // "c" is omitted.
  444. //
  445. // The `StrSplit()` function can be used multiple times to perform more
  446. // complicated splitting logic, such as intelligently parsing key-value pairs.
  447. //
  448. // Example:
  449. //
  450. // // The input string "a=b=c,d=e,f=,g" becomes
  451. // // { "a" => "b=c", "d" => "e", "f" => "", "g" => "" }
  452. // std::map<TString, TString> m;
  453. // for (y_absl::string_view sp : y_absl::StrSplit("a=b=c,d=e,f=,g", ',')) {
  454. // m.insert(y_absl::StrSplit(sp, y_absl::MaxSplits('=', 1)));
  455. // }
  456. // EXPECT_EQ("b=c", m.find("a")->second);
  457. // EXPECT_EQ("e", m.find("d")->second);
  458. // EXPECT_EQ("", m.find("f")->second);
  459. // EXPECT_EQ("", m.find("g")->second);
  460. //
  461. // WARNING: Due to a legacy bug that is maintained for backward compatibility,
  462. // splitting the following empty string_views produces different results:
  463. //
  464. // y_absl::StrSplit(y_absl::string_view(""), '-'); // {""}
  465. // y_absl::StrSplit(y_absl::string_view(), '-'); // {}, but should be {""}
  466. //
  467. // Try not to depend on this distinction because the bug may one day be fixed.
  468. template <typename Delimiter>
  469. strings_internal::Splitter<
  470. typename strings_internal::SelectDelimiter<Delimiter>::type, AllowEmpty,
  471. y_absl::string_view>
  472. StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d) {
  473. using DelimiterType =
  474. typename strings_internal::SelectDelimiter<Delimiter>::type;
  475. return strings_internal::Splitter<DelimiterType, AllowEmpty,
  476. y_absl::string_view>(
  477. text.value(), DelimiterType(d), AllowEmpty());
  478. }
  479. template <typename Delimiter, typename StringType,
  480. EnableSplitIfString<StringType> = 0>
  481. strings_internal::Splitter<
  482. typename strings_internal::SelectDelimiter<Delimiter>::type, AllowEmpty,
  483. TString>
  484. StrSplit(StringType&& text, Delimiter d) {
  485. using DelimiterType =
  486. typename strings_internal::SelectDelimiter<Delimiter>::type;
  487. return strings_internal::Splitter<DelimiterType, AllowEmpty, TString>(
  488. std::move(text), DelimiterType(d), AllowEmpty());
  489. }
  490. template <typename Delimiter, typename Predicate>
  491. strings_internal::Splitter<
  492. typename strings_internal::SelectDelimiter<Delimiter>::type, Predicate,
  493. y_absl::string_view>
  494. StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d,
  495. Predicate p) {
  496. using DelimiterType =
  497. typename strings_internal::SelectDelimiter<Delimiter>::type;
  498. return strings_internal::Splitter<DelimiterType, Predicate,
  499. y_absl::string_view>(
  500. text.value(), DelimiterType(d), std::move(p));
  501. }
  502. template <typename Delimiter, typename Predicate, typename StringType,
  503. EnableSplitIfString<StringType> = 0>
  504. strings_internal::Splitter<
  505. typename strings_internal::SelectDelimiter<Delimiter>::type, Predicate,
  506. TString>
  507. StrSplit(StringType&& text, Delimiter d, Predicate p) {
  508. using DelimiterType =
  509. typename strings_internal::SelectDelimiter<Delimiter>::type;
  510. return strings_internal::Splitter<DelimiterType, Predicate, TString>(
  511. std::move(text), DelimiterType(d), std::move(p));
  512. }
  513. Y_ABSL_NAMESPACE_END
  514. } // namespace y_absl
  515. #endif // Y_ABSL_STRINGS_STR_SPLIT_H_