Home | History | Annotate | Download | only in strings
      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 libtextclassifier2 {
     25 
     26 // Read-only "view" of a piece of data.  Does not own the underlying data.
     27 class StringPiece {
     28  public:
     29   StringPiece() : StringPiece(nullptr, 0) {}
     30 
     31   StringPiece(const char *str)  // NOLINT(runtime/explicit)
     32       : start_(str), size_(strlen(str)) {}
     33 
     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.
     39   StringPiece(const std::string &s)  // NOLINT(runtime/explicit)
     40       : StringPiece(s.data(), s.size()) {}
     41 
     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.
     48   const char *data() const { return start_; }
     49 
     50   // Returns number of bytes of underlying data.
     51   size_t size() const { return size_; }
     52   size_t length() const { return size_; }
     53 
     54   bool empty() const { return size_ == 0; }
     55 
     56   // Returns a std::string containing a copy of the underlying data.
     57   std::string ToString() const {
     58     return std::string(data(), size());
     59   }
     60 
     61  private:
     62   const char *start_;  // Not owned.
     63   size_t size_;
     64 };
     65 
     66 }  // namespace libtextclassifier2
     67 
     68 #endif  // LIBTEXTCLASSIFIER_UTIL_STRINGS_STRINGPIECE_H_
     69