1 /*
2 * Copyright (C) 2018 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_splitter.h"
18
19 #include <utility>
20
21 #include "perfetto/base/logging.h"
22
23 namespace perfetto {
24 namespace base {
25
StringSplitter(std::string str,char delimiter,EmptyTokenMode empty_token_mode)26 StringSplitter::StringSplitter(std::string 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 // It's legal to access str[str.size()] in C++11 (it always returns \0),
33 // hence the +1 (which becomes just size() after the -1 in Initialize()).
34 Initialize(&str_[0], str_.size() + 1);
35 }
36
StringSplitter(char * str,size_t size,char delimiter,EmptyTokenMode empty_token_mode)37 StringSplitter::StringSplitter(char* str,
38 size_t size,
39 char delimiter,
40 EmptyTokenMode empty_token_mode)
41 : delimiter_(delimiter), empty_token_mode_(empty_token_mode) {
42 Initialize(str, size);
43 }
44
StringSplitter(StringSplitter * outer,char delimiter,EmptyTokenMode empty_token_mode)45 StringSplitter::StringSplitter(StringSplitter* outer,
46 char delimiter,
47 EmptyTokenMode empty_token_mode)
48 : delimiter_(delimiter), empty_token_mode_(empty_token_mode) {
49 Initialize(outer->cur_token(), outer->cur_token_size() + 1);
50 }
51
Initialize(char * str,size_t size)52 void StringSplitter::Initialize(char* str, size_t size) {
53 PERFETTO_DCHECK(!size || str);
54 next_ = str;
55 end_ = str + size;
56 cur_ = nullptr;
57 cur_size_ = 0;
58 if (size)
59 next_[size - 1] = '\0';
60 }
61
Next()62 bool StringSplitter::Next() {
63 for (; next_ < end_; next_++) {
64 if (*next_ == delimiter_ &&
65 empty_token_mode_ == EmptyTokenMode::DISALLOW_EMPTY_TOKENS) {
66 // If empty tokens are disallowed, find fist non-delimiter character.
67 continue;
68 }
69 cur_ = next_;
70 for (;; next_++) {
71 if (*next_ == delimiter_) {
72 cur_size_ = static_cast<size_t>(next_ - cur_);
73 *(next_++) = '\0';
74 break;
75 }
76 if (*next_ == '\0') {
77 cur_size_ = static_cast<size_t>(next_ - cur_);
78 next_ = end_;
79 break;
80 }
81 }
82 if (*cur_ || empty_token_mode_ == EmptyTokenMode::ALLOW_EMPTY_TOKENS)
83 return true;
84 break;
85 }
86 cur_ = nullptr;
87 cur_size_ = 0;
88 return false;
89 }
90
91 } // namespace base
92 } // namespace perfetto
93