• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/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)26 StringSplitter::StringSplitter(std::string str, char delimiter)
27     : str_(std::move(str)), delimiter_(delimiter) {
28   // It's legal to access str[str.size()] in C++11 (it always returns \0),
29   // hence the +1 (which becomes just size() after the -1 in Initialize()).
30   Initialize(&str_[0], str_.size() + 1);
31 }
32 
StringSplitter(char * str,size_t size,char delimiter)33 StringSplitter::StringSplitter(char* str, size_t size, char delimiter)
34     : delimiter_(delimiter) {
35   Initialize(str, size);
36 }
37 
StringSplitter(StringSplitter * outer,char delimiter)38 StringSplitter::StringSplitter(StringSplitter* outer, char delimiter)
39     : delimiter_(delimiter) {
40   Initialize(outer->cur_token(), outer->cur_token_size() + 1);
41 }
42 
Initialize(char * str,size_t size)43 void StringSplitter::Initialize(char* str, size_t size) {
44   PERFETTO_DCHECK(!size || str);
45   next_ = str;
46   end_ = str + size;
47   cur_ = nullptr;
48   cur_size_ = 0;
49   if (size)
50     next_[size - 1] = '\0';
51 }
52 
Next()53 bool StringSplitter::Next() {
54   for (; next_ < end_; next_++) {
55     if (*next_ == delimiter_)
56       continue;
57     cur_ = next_;
58     for (;; next_++) {
59       if (*next_ == delimiter_) {
60         cur_size_ = static_cast<size_t>(next_ - cur_);
61         *(next_++) = '\0';
62         break;
63       }
64       if (*next_ == '\0') {
65         cur_size_ = static_cast<size_t>(next_ - cur_);
66         next_ = end_;
67         break;
68       }
69     }
70     if (*cur_)
71       return true;
72     break;
73   }
74   cur_ = nullptr;
75   cur_size_ = 0;
76   return false;
77 }
78 
79 }  // namespace base
80 }  // namespace perfetto
81