• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef LIBTEXTCLASSIFIER_UTIL_STRINGS_STRINGPIECE_H_
18 #define LIBTEXTCLASSIFIER_UTIL_STRINGS_STRINGPIECE_H_
19 
20 #include <stddef.h>
21 
22 #include <string>
23 
24 namespace libtextclassifier {
25 
26 // Read-only "view" of a piece of data.  Does not own the underlying data.
27 class StringPiece {
28  public:
StringPiece()29   StringPiece() : StringPiece(nullptr, 0) {}
30 
StringPiece(const char * str)31   StringPiece(const char *str)  // NOLINT(runtime/explicit)
32       : start_(str), size_(strlen(str)) {}
33 
StringPiece(const char * start,size_t size)34   StringPiece(const char *start, size_t size)
35       : start_(start), size_(size) {}
36 
37   // Intentionally no "explicit" keyword: in function calls, we want strings to
38   // be converted to StringPiece implicitly.
StringPiece(const std::string & s)39   StringPiece(const std::string &s)  // NOLINT(runtime/explicit)
40       : StringPiece(s.data(), s.size()) {}
41 
StringPiece(const std::string & s,int offset,int len)42   StringPiece(const std::string &s, int offset, int len)
43       : StringPiece(s.data() + offset, len) {}
44 
45   char operator[](size_t i) const { return start_[i]; }
46 
47   // Returns start address of underlying data.
data()48   const char *data() const { return start_; }
49 
50   // Returns number of bytes of underlying data.
size()51   size_t size() const { return size_; }
length()52   size_t length() const { return size_; }
53 
54   // Returns a std::string containing a copy of the underlying data.
ToString()55   std::string ToString() const {
56     return std::string(data(), size());
57   }
58 
59  private:
60   const char *start_;  // Not owned.
61   size_t size_;
62 };
63 
64 }  // namespace libtextclassifier
65 
66 #endif  // LIBTEXTCLASSIFIER_UTIL_STRINGS_STRINGPIECE_H_
67