1 // Copyright 2011 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 #ifndef NINJA_STRINGPIECE_H_ 16 #define NINJA_STRINGPIECE_H_ 17 18 #include <string> 19 20 using namespace std; 21 22 #include <string.h> 23 24 /// StringPiece represents a slice of a string whose memory is managed 25 /// externally. It is useful for reducing the number of std::strings 26 /// we need to allocate. 27 struct StringPiece { 28 typedef const char* const_iterator; 29 StringPieceStringPiece30 StringPiece() : str_(NULL), len_(0) {} 31 32 /// The constructors intentionally allow for implicit conversions. StringPieceStringPiece33 StringPiece(const string& str) : str_(str.data()), len_(str.size()) {} StringPieceStringPiece34 StringPiece(const char* str) : str_(str), len_(strlen(str)) {} 35 StringPieceStringPiece36 StringPiece(const char* str, size_t len) : str_(str), len_(len) {} 37 38 bool operator==(const StringPiece& other) const { 39 return len_ == other.len_ && memcmp(str_, other.str_, len_) == 0; 40 } 41 bool operator!=(const StringPiece& other) const { 42 return !(*this == other); 43 } 44 45 /// Convert the slice into a full-fledged std::string, copying the 46 /// data into a new string. AsStringStringPiece47 string AsString() const { 48 return len_ ? string(str_, len_) : string(); 49 } 50 beginStringPiece51 const_iterator begin() const { 52 return str_; 53 } 54 endStringPiece55 const_iterator end() const { 56 return str_ + len_; 57 } 58 59 char operator[](size_t pos) const { 60 return str_[pos]; 61 } 62 sizeStringPiece63 size_t size() const { 64 return len_; 65 } 66 67 const char* str_; 68 size_t len_; 69 }; 70 71 #endif // NINJA_STRINGPIECE_H_ 72