Ninja
string_piece.h
Go to the documentation of this file.
00001 // Copyright 2011 Google Inc. All Rights Reserved.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //     http://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 
00015 #ifndef NINJA_STRINGPIECE_H_
00016 #define NINJA_STRINGPIECE_H_
00017 
00018 #include <string>
00019 
00020 using namespace std;
00021 
00022 #include <string.h>
00023 
00024 /// StringPiece represents a slice of a string whose memory is managed
00025 /// externally.  It is useful for reducing the number of std::strings
00026 /// we need to allocate.
00027 struct StringPiece {
00028   StringPiece() : str_(NULL), len_(0) {}
00029 
00030   /// The constructors intentionally allow for implicit conversions.
00031   StringPiece(const string& str) : str_(str.data()), len_(str.size()) {}
00032   StringPiece(const char* str) : str_(str), len_(strlen(str)) {}
00033 
00034   StringPiece(const char* str, size_t len) : str_(str), len_(len) {}
00035 
00036   bool operator==(const StringPiece& other) const {
00037     return len_ == other.len_ && memcmp(str_, other.str_, len_) == 0;
00038   }
00039   bool operator!=(const StringPiece& other) const {
00040     return !(*this == other);
00041   }
00042 
00043   /// Convert the slice into a full-fledged std::string, copying the
00044   /// data into a new string.
00045   string AsString() const {
00046     return len_ ? string(str_, len_) : string();
00047   }
00048 
00049   const char* str_;
00050   size_t len_;
00051 };
00052 
00053 #endif  // NINJA_STRINGPIECE_H_