string_tokenizer.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_STRINGS_STRING_TOKENIZER_H_
  5. #define BASE_STRINGS_STRING_TOKENIZER_H_
  6. #include <algorithm>
  7. #include <string>
  8. #include "base/strings/string_piece.h"
  9. namespace base {
  10. // StringTokenizerT is a simple string tokenizer class. It works like an
  11. // iterator that with each step (see the Advance method) updates members that
  12. // refer to the next token in the input string. The user may optionally
  13. // configure the tokenizer to return delimiters.
  14. //
  15. // EXAMPLE 1:
  16. //
  17. // char input[] = "this is a test";
  18. // CStringTokenizer t(input, input + strlen(input), " ");
  19. // while (t.GetNext()) {
  20. // printf("%s\n", t.token().c_str());
  21. // }
  22. //
  23. // Output:
  24. //
  25. // this
  26. // is
  27. // a
  28. // test
  29. //
  30. //
  31. // EXAMPLE 2:
  32. //
  33. // std::string input = "no-cache=\"foo, bar\", private";
  34. // StringTokenizer t(input, ", ");
  35. // t.set_quote_chars("\"");
  36. // while (t.GetNext()) {
  37. // printf("%s\n", t.token().c_str());
  38. // }
  39. //
  40. // Output:
  41. //
  42. // no-cache="foo, bar"
  43. // private
  44. //
  45. //
  46. // EXAMPLE 3:
  47. //
  48. // bool next_is_option = false, next_is_value = false;
  49. // std::string input = "text/html; charset=UTF-8; foo=bar";
  50. // StringTokenizer t(input, "; =");
  51. // t.set_options(StringTokenizer::RETURN_DELIMS);
  52. // while (t.GetNext()) {
  53. // if (t.token_is_delim()) {
  54. // switch (*t.token_begin()) {
  55. // case ';':
  56. // next_is_option = true;
  57. // break;
  58. // case '=':
  59. // next_is_value = true;
  60. // break;
  61. // }
  62. // } else {
  63. // const char* label;
  64. // if (next_is_option) {
  65. // label = "option-name";
  66. // next_is_option = false;
  67. // } else if (next_is_value) {
  68. // label = "option-value";
  69. // next_is_value = false;
  70. // } else {
  71. // label = "mime-type";
  72. // }
  73. // printf("%s: %s\n", label, t.token().c_str());
  74. // }
  75. // }
  76. //
  77. //
  78. template <class str, class const_iterator>
  79. class StringTokenizerT {
  80. public:
  81. typedef typename str::value_type char_type;
  82. // Options that may be pass to set_options()
  83. enum {
  84. // Specifies the delimiters should be returned as tokens
  85. RETURN_DELIMS = 1 << 0,
  86. // Specifies that empty tokens should be returned. Treats the beginning and
  87. // ending of the string as implicit delimiters, though doesn't return them
  88. // as tokens if RETURN_DELIMS is also used.
  89. RETURN_EMPTY_TOKENS = 1 << 1,
  90. };
  91. // The string object must live longer than the tokenizer. In particular, this
  92. // should not be constructed with a temporary. The deleted rvalue constructor
  93. // blocks the most obvious instances of this (e.g. passing a string literal to
  94. // the constructor), but caution must still be exercised.
  95. StringTokenizerT(const str& string,
  96. const str& delims) {
  97. Init(string.begin(), string.end(), delims);
  98. }
  99. // Don't allow temporary strings to be used with string tokenizer, since
  100. // Init() would otherwise save iterators to a temporary string.
  101. StringTokenizerT(str&&, const str& delims) = delete;
  102. StringTokenizerT(const_iterator string_begin,
  103. const_iterator string_end,
  104. const str& delims) {
  105. Init(string_begin, string_end, delims);
  106. }
  107. // Set the options for this tokenizer. By default, this is 0.
  108. void set_options(int options) { options_ = options; }
  109. // Set the characters to regard as quotes. By default, this is empty. When
  110. // a quote char is encountered, the tokenizer will switch into a mode where
  111. // it ignores delimiters that it finds. It switches out of this mode once it
  112. // finds another instance of the quote char. If a backslash is encountered
  113. // within a quoted string, then the next character is skipped.
  114. void set_quote_chars(const str& quotes) { quotes_ = quotes; }
  115. // Call this method to advance the tokenizer to the next delimiter. This
  116. // returns false if the tokenizer is complete. This method must be called
  117. // before calling any of the token* methods.
  118. bool GetNext() {
  119. if (quotes_.empty() && options_ == 0)
  120. return QuickGetNext();
  121. else
  122. return FullGetNext();
  123. }
  124. // Start iterating through tokens from the beginning of the string.
  125. void Reset() {
  126. token_end_ = start_pos_;
  127. }
  128. // Returns true if token is a delimiter. When the tokenizer is constructed
  129. // with the RETURN_DELIMS option, this method can be used to check if the
  130. // returned token is actually a delimiter. Returns true before the first
  131. // time GetNext() has been called, and after GetNext() returns false.
  132. bool token_is_delim() const { return token_is_delim_; }
  133. // If GetNext() returned true, then these methods may be used to read the
  134. // value of the token.
  135. const_iterator token_begin() const { return token_begin_; }
  136. const_iterator token_end() const { return token_end_; }
  137. str token() const { return str(token_begin_, token_end_); }
  138. BasicStringPiece<str> token_piece() const {
  139. return BasicStringPiece<str>(&*token_begin_,
  140. std::distance(token_begin_, token_end_));
  141. }
  142. private:
  143. void Init(const_iterator string_begin,
  144. const_iterator string_end,
  145. const str& delims) {
  146. start_pos_ = string_begin;
  147. token_begin_ = string_begin;
  148. token_end_ = string_begin;
  149. end_ = string_end;
  150. delims_ = delims;
  151. options_ = 0;
  152. token_is_delim_ = true;
  153. }
  154. // Implementation of GetNext() for when we have no quote characters. We have
  155. // two separate implementations because AdvanceOne() is a hot spot in large
  156. // text files with large tokens.
  157. bool QuickGetNext() {
  158. token_is_delim_ = false;
  159. for (;;) {
  160. token_begin_ = token_end_;
  161. if (token_end_ == end_) {
  162. token_is_delim_ = true;
  163. return false;
  164. }
  165. ++token_end_;
  166. if (delims_.find(*token_begin_) == str::npos)
  167. break;
  168. // else skip over delimiter.
  169. }
  170. while (token_end_ != end_ && delims_.find(*token_end_) == str::npos)
  171. ++token_end_;
  172. return true;
  173. }
  174. // Implementation of GetNext() for when we have to take quotes into account.
  175. bool FullGetNext() {
  176. AdvanceState state;
  177. for (;;) {
  178. if (token_is_delim_) {
  179. // Last token was a delimiter. Note: This is also the case at the start.
  180. //
  181. // ... D T T T T D ...
  182. // ^ ^
  183. // | |
  184. // | |token_end_| : The next character to look at or |end_|.
  185. // |
  186. // |token_begin_| : Points to delimiter or |token_end_|.
  187. //
  188. // The next token is always a non-delimiting token. It could be empty,
  189. // however.
  190. token_is_delim_ = false;
  191. token_begin_ = token_end_;
  192. // Slurp all non-delimiter characters into the token.
  193. while (token_end_ != end_ && AdvanceOne(&state, *token_end_)) {
  194. ++token_end_;
  195. }
  196. // If it's non-empty, or empty tokens were requested, return the token.
  197. if (token_begin_ != token_end_ || (options_ & RETURN_EMPTY_TOKENS))
  198. return true;
  199. }
  200. DCHECK(!token_is_delim_);
  201. // Last token was a regular token.
  202. //
  203. // ... T T T D T T ...
  204. // ^ ^
  205. // | |
  206. // | token_end_ : The next character to look at. Always one
  207. // | char beyond the token boundary.
  208. // |
  209. // token_begin_ : Points to beginning of token. Note: token could
  210. // be empty, in which case
  211. // token_begin_ == token_end_.
  212. //
  213. // The next token is always a delimiter. It could be |end_| however, but
  214. // |end_| is also an implicit delimiter.
  215. token_is_delim_ = true;
  216. token_begin_ = token_end_;
  217. if (token_end_ == end_)
  218. return false;
  219. // Look at the delimiter.
  220. ++token_end_;
  221. if (options_ & RETURN_DELIMS)
  222. return true;
  223. }
  224. return false;
  225. }
  226. bool IsDelim(char_type c) const {
  227. return delims_.find(c) != str::npos;
  228. }
  229. bool IsQuote(char_type c) const {
  230. return quotes_.find(c) != str::npos;
  231. }
  232. struct AdvanceState {
  233. bool in_quote;
  234. bool in_escape;
  235. char_type quote_char;
  236. AdvanceState() : in_quote(false), in_escape(false), quote_char('\0') {}
  237. };
  238. // Returns true if a delimiter was not hit.
  239. bool AdvanceOne(AdvanceState* state, char_type c) {
  240. if (state->in_quote) {
  241. if (state->in_escape) {
  242. state->in_escape = false;
  243. } else if (c == '\\') {
  244. state->in_escape = true;
  245. } else if (c == state->quote_char) {
  246. state->in_quote = false;
  247. }
  248. } else {
  249. if (IsDelim(c))
  250. return false;
  251. state->in_quote = IsQuote(state->quote_char = c);
  252. }
  253. return true;
  254. }
  255. const_iterator start_pos_;
  256. const_iterator token_begin_;
  257. const_iterator token_end_;
  258. const_iterator end_;
  259. str delims_;
  260. str quotes_;
  261. int options_;
  262. bool token_is_delim_;
  263. };
  264. typedef StringTokenizerT<std::string, std::string::const_iterator>
  265. StringTokenizer;
  266. typedef StringTokenizerT<string16, string16::const_iterator> String16Tokenizer;
  267. typedef StringTokenizerT<std::string, const char*> CStringTokenizer;
  268. } // namespace base
  269. #endif // BASE_STRINGS_STRING_TOKENIZER_H_