1 // Copyright 2017 Google Inc. All Rights Reserved.
2 //
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 #include "string_piece_util.h"
16
17 #include <algorithm>
18 #include <string>
19 #include <vector>
20 using namespace std;
21
SplitStringPiece(StringPiece input,char sep)22 vector<StringPiece> SplitStringPiece(StringPiece input, char sep) {
23 vector<StringPiece> elems;
24 elems.reserve(count(input.begin(), input.end(), sep) + 1);
25
26 StringPiece::const_iterator pos = input.begin();
27
28 for (;;) {
29 const char* next_pos = find(pos, input.end(), sep);
30 if (next_pos == input.end()) {
31 elems.push_back(StringPiece(pos, input.end() - pos));
32 break;
33 }
34 elems.push_back(StringPiece(pos, next_pos - pos));
35 pos = next_pos + 1;
36 }
37
38 return elems;
39 }
40
JoinStringPiece(const vector<StringPiece> & list,char sep)41 string JoinStringPiece(const vector<StringPiece>& list, char sep) {
42 if (list.empty()) {
43 return "";
44 }
45
46 string ret;
47
48 {
49 size_t cap = list.size() - 1;
50 for (size_t i = 0; i < list.size(); ++i) {
51 cap += list[i].len_;
52 }
53 ret.reserve(cap);
54 }
55
56 for (size_t i = 0; i < list.size(); ++i) {
57 if (i != 0) {
58 ret += sep;
59 }
60 ret.append(list[i].str_, list[i].len_);
61 }
62
63 return ret;
64 }
65
EqualsCaseInsensitiveASCII(StringPiece a,StringPiece b)66 bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b) {
67 if (a.len_ != b.len_) {
68 return false;
69 }
70
71 for (size_t i = 0; i < a.len_; ++i) {
72 if (ToLowerASCII(a.str_[i]) != ToLowerASCII(b.str_[i])) {
73 return false;
74 }
75 }
76
77 return true;
78 }
79