|
1 // Copyright 2013 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 // |
|
16 // A StringPiece points to part or all of a string, double-quoted string |
|
17 // literal, or other string-like object. A StringPiece does *not* own the |
|
18 // string to which it points. A StringPiece is not null-terminated. [subset] |
|
19 // |
|
20 |
|
21 #ifndef STRINGS_STRINGPIECE_H_ |
|
22 #define STRINGS_STRINGPIECE_H_ |
|
23 |
|
24 #include <string.h> |
|
25 #include <string> |
|
26 |
|
27 |
|
28 typedef int stringpiece_ssize_type; |
|
29 |
|
30 class StringPiece { |
|
31 private: |
|
32 const char* ptr_; |
|
33 stringpiece_ssize_type length_; |
|
34 |
|
35 public: |
|
36 // We provide non-explicit singleton constructors so users can pass |
|
37 // in a "const char*" or a "string" wherever a "StringPiece" is |
|
38 // expected. |
|
39 StringPiece() : ptr_(NULL), length_(0) {} |
|
40 |
|
41 StringPiece(const char* str) // NOLINT(runtime/explicit) |
|
42 : ptr_(str), length_(0) { |
|
43 if (str != NULL) { |
|
44 length_ = strlen(str); |
|
45 } |
|
46 } |
|
47 |
|
48 StringPiece(const std::string& str) // NOLINT(runtime/explicit) |
|
49 : ptr_(str.data()), length_(0) { |
|
50 length_ = str.size(); |
|
51 } |
|
52 |
|
53 StringPiece(const char* offset, stringpiece_ssize_type len) |
|
54 : ptr_(offset), length_(len) { |
|
55 } |
|
56 |
|
57 void remove_prefix(stringpiece_ssize_type n) { |
|
58 ptr_ += n; |
|
59 length_ -= n; |
|
60 } |
|
61 |
|
62 void remove_suffix(stringpiece_ssize_type n) { |
|
63 length_ -= n; |
|
64 } |
|
65 |
|
66 // data() may return a pointer to a buffer with embedded NULs, and the |
|
67 // returned buffer may or may not be null terminated. Therefore it is |
|
68 // typically a mistake to pass data() to a routine that expects a NUL |
|
69 // terminated string. |
|
70 const char* data() const { return ptr_; } |
|
71 stringpiece_ssize_type size() const { return length_; } |
|
72 stringpiece_ssize_type length() const { return length_; } |
|
73 bool empty() const { return length_ == 0; } |
|
74 }; |
|
75 |
|
76 class StringPiece; |
|
77 |
|
78 #endif // STRINGS_STRINGPIECE_H__ |