1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include "buffer_splitter.h" 17 BufferSplitter(const char * buf,int size)18BufferSplitter::BufferSplitter(const char* buf, int size) 19 { 20 next_ = const_cast<char*>(buf); 21 nextLine_ = const_cast<char*>(buf); 22 end_ = next_ + size; 23 if (size) { 24 next_[size - 1] = '\0'; 25 NextLine(); 26 } 27 } 28 NextLine()29bool BufferSplitter::NextLine() 30 { 31 char delimiter = '\n'; 32 curLine_ = nullptr; 33 curLineSize_ = 0; 34 curWord_ = nullptr; 35 curWordSize_ = 0; 36 37 if (next_ < end_) { 38 next_ = nextLine_; 39 } 40 for (; next_ < end_; next_++) { 41 if (*next_ == delimiter) { 42 continue; 43 } 44 curLine_ = next_; 45 while (true) { 46 if (++next_ >= end_) { 47 curLineSize_ = static_cast<size_t>(end_ - curLine_ - 1); 48 next_ = curLine_; 49 nextLine_ = end_; 50 break; 51 } 52 if (*next_ == delimiter) { 53 nextLine_ = ++next_; 54 next_ = curLine_; 55 curLineSize_ = static_cast<size_t>(nextLine_ - curLine_ - 1); 56 break; 57 } 58 } 59 if (curLineSize_ > 0) { 60 return true; 61 } 62 curLine_ = nullptr; 63 break; 64 } 65 return false; 66 } 67 NextWord(char delimiter)68bool BufferSplitter::NextWord(char delimiter) 69 { 70 char* nextBak = next_; 71 curWord_ = nullptr; 72 curWordSize_ = 0; 73 74 for (; next_ < nextLine_; next_++) { 75 if (isspace(*next_) || *next_ == delimiter) { 76 continue; 77 } 78 curWord_ = next_; 79 while (true) { 80 if (++next_ >= nextLine_) { 81 curWordSize_ = 0; 82 curWord_ = nullptr; 83 next_ = nextBak; 84 break; 85 } 86 87 if (*next_ == delimiter) { 88 curWordSize_ = static_cast<size_t>(next_ - curWord_); 89 ++next_; 90 break; 91 } 92 } 93 if (curWordSize_ > 0) { 94 return true; 95 } 96 break; 97 } 98 return false; 99 }