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