• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #ifndef BASE_STRINGS_STRING_TOKENIZER_H_
11 #define BASE_STRINGS_STRING_TOKENIZER_H_
12 
13 #include <algorithm>
14 #include <optional>
15 #include <string>
16 #include <string_view>
17 
18 #include "base/check.h"
19 #include "base/strings/string_util.h"
20 
21 namespace base {
22 
23 // StringTokenizerT is a simple string tokenizer class.  It works like an
24 // iterator that with each step (see the Advance method) updates members that
25 // refer to the next token in the input string.  The user may optionally
26 // configure the tokenizer to return delimiters. For the optional
27 // WhitespacePolicy parameter, kSkipOver will cause the tokenizer to skip
28 // over whitespace characters. The tokenizer never stops on a whitespace
29 // character.
30 //
31 // EXAMPLE 1:
32 //
33 //   char input[] = "this is a test";
34 //   CStringTokenizer t(input, " ");
35 //   while (std::optional<std::string_view> token = t.GetNextTokenView()) {
36 //     LOG(ERROR) << token.value();
37 //   }
38 //
39 // Output sans logging metadata:
40 //
41 //   this
42 //   is
43 //   a
44 //   test
45 //
46 //
47 // EXAMPLE 2:
48 //
49 //   std::string input = "no-cache=\"foo, bar\", private";
50 //   StringTokenizer t(input, ", ");
51 //   t.set_quote_chars("\"");
52 //   while (std::optional<std::string_view> token = t.GetNextTokenView()) {
53 //     LOG(ERROR) << token.value();
54 //   }
55 //
56 // Output sans logging metadata:
57 //
58 //   no-cache="foo, bar"
59 //   private
60 //
61 //
62 // EXAMPLE 3:
63 //
64 //   bool next_is_option = false, next_is_value = false;
65 //   std::string input = "text/html; charset=UTF-8; foo=bar";
66 //   StringTokenizer t(input, "; =");
67 //   t.set_options(StringTokenizer::RETURN_DELIMS);
68 //   while (std::optional<std::string_view> token = t.GetNextTokenView()) {
69 //     if (t.token_is_delim()) {
70 //       switch (token.value().front()) {
71 //         case ';':
72 //           next_is_option = true;
73 //           break;
74 //         case '=':
75 //           next_is_value = true;
76 //           break;
77 //       }
78 //     } else {
79 //       const char* label;
80 //       if (next_is_option) {
81 //         label = "option-name";
82 //         next_is_option = false;
83 //       } else if (next_is_value) {
84 //         label = "option-value";
85 //         next_is_value = false;
86 //       } else {
87 //         label = "mime-type";
88 //       }
89 //       LOG(ERROR) << label << " " << token.value();
90 //     }
91 //   }
92 //
93 //
94 // EXAMPLE 4:
95 //
96 //   std::string input = "this, \t is, \t a, \t test";
97 //   StringTokenizer t(input, ",",
98 //       StringTokenizer::WhitespacePolicy::kSkipOver);
99 //   while (std::optional<std::string_view> token = t.GetNextTokenView()) {
100 //     LOG(ERROR) << token.value();
101 //   }
102 //
103 // Output sans logging metadata:
104 //
105 //   this
106 //   is
107 //   a
108 //   test
109 //
110 //
111 // TODO(danakj): This class is templated on the container and the iterator type,
112 // but it strictly only needs to care about the `CharType`. However many users
113 // expect to work with string and string::iterator for historical reasons. When
114 // they are all working with `string_view`, then this class can be made to
115 // unconditionally use `std::basic_string_view<CharType>` and vend iterators of
116 // that type, and we can drop the `str` and `const_iterator` aliases.
117 template <class str, class const_iterator>
118 class StringTokenizerT {
119  public:
120   using char_type = typename str::value_type;
121   using owning_str = std::basic_string<char_type>;
122 
123   // Options that may be pass to set_options()
124   enum {
125     // Specifies the delimiters should be returned as tokens
126     RETURN_DELIMS = 1 << 0,
127 
128     // Specifies that empty tokens should be returned. Treats the beginning and
129     // ending of the string as implicit delimiters, though doesn't return them
130     // as tokens if RETURN_DELIMS is also used.
131     RETURN_EMPTY_TOKENS = 1 << 1,
132   };
133 
134   // Policy indicating what to do with whitespace characters. Whitespace is
135   // defined to be the characters indicated here:
136   // https://www.w3schools.com/jsref/jsref_regexp_whitespace.asp
137   enum class WhitespacePolicy {
138     // Whitespace should be treated the same as any other non-delimiter
139     // character.
140     kIncludeInTokens,
141     // Whitespace is skipped over and not included in the resulting token.
142     // Whitespace will also delimit other tokens, however it is never returned
143     // even if RETURN_DELIMS is set. If quote chars are set (See set_quote_chars
144     // below) Whitespace will be included in a token when processing quotes.
145     kSkipOver,
146   };
147 
148   // The string object must live longer than the tokenizer. In particular, this
149   // should not be constructed with a temporary. The deleted rvalue constructor
150   // blocks the most obvious instances of this (e.g. passing a string literal to
151   // the constructor), but caution must still be exercised.
152   StringTokenizerT(
153       const str& string,
154       const owning_str& delims,
155       WhitespacePolicy whitespace_policy = WhitespacePolicy::kIncludeInTokens) {
156     Init(string.begin(), string.end(), delims, whitespace_policy);
157   }
158 
159   // Don't allow temporary strings to be used with string tokenizer, since
160   // Init() would otherwise save iterators to a temporary string.
161   StringTokenizerT(str&&, const str& delims) = delete;
162 
163   StringTokenizerT(
164       const_iterator string_begin,
165       const_iterator string_end,
166       const owning_str& delims,
167       WhitespacePolicy whitespace_policy = WhitespacePolicy::kIncludeInTokens) {
168     Init(string_begin, string_end, delims, whitespace_policy);
169   }
170 
171   // Set the options for this tokenizer.  By default, this is 0.
set_options(int options)172   void set_options(int options) { options_ = options; }
173 
174   // Set the characters to regard as quotes.  By default, this is empty.  When
175   // a quote char is encountered, the tokenizer will switch into a mode where
176   // it ignores delimiters that it finds.  It switches out of this mode once it
177   // finds another instance of the quote char.  If a backslash is encountered
178   // within a quoted string, then the next character is skipped.
set_quote_chars(const owning_str & quotes)179   void set_quote_chars(const owning_str& quotes) { quotes_ = quotes; }
180 
181   // Advance the tokenizer to the next delimiter and return the token value. If
182   // the tokenizer is complete, this returns std::nullopt.
GetNextTokenView()183   std::optional<std::basic_string_view<char_type>> GetNextTokenView() {
184     if (!GetNext()) {
185       return std::nullopt;
186     }
187 
188     return token_piece();
189   }
190 
191   // Call this method to advance the tokenizer to the next delimiter.  This
192   // returns false if the tokenizer is complete.  This method must be called
193   // before calling any of the token* methods.
GetNext()194   bool GetNext() {
195     if (quotes_.empty() && options_ == 0)
196       return QuickGetNext();
197     else
198       return FullGetNext();
199   }
200 
201   // Start iterating through tokens from the beginning of the string.
Reset()202   void Reset() {
203     token_end_ = start_pos_;
204   }
205 
206   // Returns true if token is a delimiter.  When the tokenizer is constructed
207   // with the RETURN_DELIMS option, this method can be used to check if the
208   // returned token is actually a delimiter. Returns true before the first
209   // time GetNext() has been called, and after GetNext() returns false.
token_is_delim()210   bool token_is_delim() const { return token_is_delim_; }
211 
212   // If GetNext() returned true, then these methods may be used to read the
213   // value of the token.
token_begin()214   const_iterator token_begin() const { return token_begin_; }
token_end()215   const_iterator token_end() const { return token_end_; }
token()216   str token() const { return str(token_begin_, token_end_); }
token_piece()217   std::basic_string_view<char_type> token_piece() const {
218     return MakeBasicStringPiece<char_type>(token_begin_, token_end_);
219   }
220 
221  private:
Init(const_iterator string_begin,const_iterator string_end,const owning_str & delims,WhitespacePolicy whitespace_policy)222   void Init(const_iterator string_begin,
223             const_iterator string_end,
224             const owning_str& delims,
225             WhitespacePolicy whitespace_policy) {
226     start_pos_ = string_begin;
227     token_begin_ = string_begin;
228     token_end_ = string_begin;
229     end_ = string_end;
230     delims_ = delims;
231     options_ = 0;
232     token_is_delim_ = true;
233     whitespace_policy_ = whitespace_policy;
234   }
235 
ShouldSkip(char_type c)236   bool ShouldSkip(char_type c) const {
237     return whitespace_policy_ == WhitespacePolicy::kSkipOver &&
238            IsAsciiWhitespace(c);
239   }
240 
241   // Skip over any contiguous whitespace characters according to the whitespace
242   // policy.
SkipWhitespace()243   void SkipWhitespace() {
244     while (token_end_ != end_ && ShouldSkip(*token_end_))
245       ++token_end_;
246   }
247 
248   // Implementation of GetNext() for when we have no quote characters. We have
249   // two separate implementations because AdvanceOne() is a hot spot in large
250   // text files with large tokens.
QuickGetNext()251   bool QuickGetNext() {
252     token_is_delim_ = false;
253     for (;;) {
254       token_begin_ = token_end_;
255       if (token_end_ == end_) {
256         token_is_delim_ = true;
257         return false;
258       }
259       ++token_end_;
260       if (delims_.find(*token_begin_) == str::npos &&
261           !ShouldSkip(*token_begin_)) {
262         break;
263       }
264       // else skip over delimiter or skippable character.
265     }
266     while (token_end_ != end_ && delims_.find(*token_end_) == str::npos &&
267            !ShouldSkip(*token_end_)) {
268       ++token_end_;
269     }
270     return true;
271   }
272 
273   // Implementation of GetNext() for when we have to take quotes into account.
FullGetNext()274   bool FullGetNext() {
275     AdvanceState state;
276 
277     SkipWhitespace();
278     for (;;) {
279       if (token_is_delim_) {
280         // Last token was a delimiter. Note: This is also the case at the start.
281         //
282         //    ... D T T T T D ...
283         //        ^ ^
284         //        | |
285         //        | |token_end_| : The next character to look at or |end_|.
286         //        |
287         //        |token_begin_| : Points to delimiter or |token_end_|.
288         //
289         // The next token is always a non-delimiting token. It could be empty,
290         // however.
291         token_is_delim_ = false;
292         token_begin_ = token_end_;
293 
294         // Slurp all non-delimiter characters into the token.
295         while (token_end_ != end_ && AdvanceOne(&state, *token_end_)) {
296           ++token_end_;
297         }
298 
299         // If it's non-empty, or empty tokens were requested, return the token.
300         if (token_begin_ != token_end_ || (options_ & RETURN_EMPTY_TOKENS))
301           return true;
302       }
303 
304       DCHECK(!token_is_delim_);
305       // Last token was a regular token.
306       //
307       //    ... T T T D T T ...
308       //        ^     ^
309       //        |     |
310       //        |     token_end_ : The next character to look at. Always one
311       //        |                  char beyond the token boundary.
312       //        |
313       //        token_begin_ : Points to beginning of token. Note: token could
314       //                       be empty, in which case
315       //                       token_begin_ == token_end_.
316       //
317       // The next token is always a delimiter. It could be |end_| however, but
318       // |end_| is also an implicit delimiter.
319       token_is_delim_ = true;
320       token_begin_ = token_end_;
321 
322       if (token_end_ == end_)
323         return false;
324 
325       // Look at the delimiter.
326       ++token_end_;
327       if (options_ & RETURN_DELIMS)
328         return true;
329     }
330 
331     return false;
332   }
333 
IsDelim(char_type c)334   bool IsDelim(char_type c) const {
335     return delims_.find(c) != owning_str::npos;
336   }
337 
IsQuote(char_type c)338   bool IsQuote(char_type c) const {
339     return quotes_.find(c) != owning_str::npos;
340   }
341 
342   struct AdvanceState {
343     bool in_quote;
344     bool in_escape;
345     char_type quote_char;
AdvanceStateAdvanceState346     AdvanceState() : in_quote(false), in_escape(false), quote_char('\0') {}
347   };
348 
349   // Returns true if a delimiter or, depending on policy, whitespace was not
350   // hit.
AdvanceOne(AdvanceState * state,char_type c)351   bool AdvanceOne(AdvanceState* state, char_type c) {
352     if (state->in_quote) {
353       if (state->in_escape) {
354         state->in_escape = false;
355       } else if (c == '\\') {
356         state->in_escape = true;
357       } else if (c == state->quote_char) {
358         state->in_quote = false;
359       }
360     } else {
361       if (IsDelim(c) || ShouldSkip(c))
362         return false;
363       state->in_quote = IsQuote(state->quote_char = c);
364     }
365     return true;
366   }
367 
368   const_iterator start_pos_;
369   const_iterator token_begin_;
370   const_iterator token_end_;
371   const_iterator end_;
372   owning_str delims_;
373   owning_str quotes_;
374   int options_;
375   bool token_is_delim_;
376   WhitespacePolicy whitespace_policy_;
377 };
378 
379 typedef StringTokenizerT<std::string, std::string::const_iterator>
380     StringTokenizer;
381 typedef StringTokenizerT<std::string_view, std::string_view::const_iterator>
382     StringViewTokenizer;
383 typedef StringTokenizerT<std::u16string, std::u16string::const_iterator>
384     String16Tokenizer;
385 typedef StringTokenizerT<std::string, const char*> CStringTokenizer;
386 
387 }  // namespace base
388 
389 #endif  // BASE_STRINGS_STRING_TOKENIZER_H_
390