1 /*
2 * Copyright (C) 2024 The Android Open Source Project
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 * http://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 #include "perfetto/ext/base/string_view_splitter.h"
18
19 #include <utility>
20
21 #include "perfetto/base/logging.h"
22
23 namespace perfetto {
24 namespace base {
25
StringViewSplitter(base::StringView str,char delimiter,EmptyTokenMode empty_token_mode)26 StringViewSplitter::StringViewSplitter(base::StringView str,
27 char delimiter,
28 EmptyTokenMode empty_token_mode)
29 : str_(std::move(str)),
30 delimiter_(delimiter),
31 empty_token_mode_(empty_token_mode) {
32 Initialize(str);
33 }
34
StringViewSplitter(StringViewSplitter * outer,char delimiter,EmptyTokenMode empty_token_mode)35 StringViewSplitter::StringViewSplitter(StringViewSplitter* outer,
36 char delimiter,
37 EmptyTokenMode empty_token_mode)
38 : delimiter_(delimiter), empty_token_mode_(empty_token_mode) {
39 Initialize(outer->cur_token());
40 }
41
Initialize(base::StringView str)42 void StringViewSplitter::Initialize(base::StringView str) {
43 next_ = str;
44 cur_ = "";
45 end_of_input_ = false;
46 }
47
Next()48 bool StringViewSplitter::Next() {
49 if (end_of_input_) {
50 cur_ = next_ = "";
51 return false;
52 }
53
54 size_t substr_start = 0;
55 if (empty_token_mode_ == EmptyTokenMode::DISALLOW_EMPTY_TOKENS) {
56 while (substr_start < next_.size() &&
57 next_.at(substr_start) == delimiter_) {
58 substr_start++;
59 }
60 }
61
62 if (substr_start >= next_.size()) {
63 end_of_input_ = true;
64 cur_ = next_ = "";
65 return !cur_.empty() ||
66 empty_token_mode_ == EmptyTokenMode::ALLOW_EMPTY_TOKENS;
67 }
68
69 size_t delimiter_start = next_.find(delimiter_, substr_start);
70 if (delimiter_start == base::StringView::npos) {
71 cur_ = next_.substr(substr_start);
72 next_ = "";
73 end_of_input_ = true;
74 return !cur_.empty() ||
75 empty_token_mode_ == EmptyTokenMode::ALLOW_EMPTY_TOKENS;
76 }
77
78 size_t delimiter_end = delimiter_start + 1;
79
80 if (empty_token_mode_ == EmptyTokenMode::DISALLOW_EMPTY_TOKENS) {
81 while (delimiter_end < next_.size() &&
82 next_.at(delimiter_end) == delimiter_) {
83 delimiter_end++;
84 }
85 if (delimiter_end >= next_.size()) {
86 end_of_input_ = true;
87 }
88 }
89
90 cur_ = next_.substr(substr_start, delimiter_start - substr_start);
91 next_ = next_.substr(delimiter_end);
92
93 return !cur_.empty() ||
94 empty_token_mode_ == EmptyTokenMode::ALLOW_EMPTY_TOKENS;
95 }
96
97 } // namespace base
98 } // namespace perfetto
99