1 // Copyright 2019 Google LLC. 2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. 3 #ifndef stringslice_DEFINED 4 #define stringslice_DEFINED 5 6 #include "modules/skplaintexteditor/include/stringview.h" 7 8 #include <memory> 9 #include <cstddef> 10 11 namespace SkPlainTextEditor { 12 // A lightweight modifiable string class. 13 class StringSlice { 14 public: 15 StringSlice() = default; StringSlice(const char * s,std::size_t l)16 StringSlice(const char* s, std::size_t l) { this->insert(0, s, l); } 17 StringSlice(StringSlice&&); StringSlice(const StringSlice & that)18 StringSlice(const StringSlice& that) : StringSlice(that.begin(), that.size()) {} 19 ~StringSlice() = default; 20 StringSlice& operator=(StringSlice&&); 21 StringSlice& operator=(const StringSlice&); 22 23 // access: 24 // Does not have a c_str method; is *not* NUL-terminated. begin()25 const char* begin() const { return fPtr.get(); } end()26 const char* end() const { return fPtr ? fPtr.get() + fLength : nullptr; } size()27 std::size_t size() const { return fLength; } view()28 SkPlainTextEditor::StringView view() const { return {fPtr.get(), fLength}; } 29 30 // mutation: 31 void insert(std::size_t offset, const char* text, std::size_t length); 32 void remove(std::size_t offset, std::size_t length); 33 34 // modify capacity only: reserve(std::size_t size)35 void reserve(std::size_t size) { if (size > fCapacity) { this->realloc(size); } } shrink()36 void shrink() { this->realloc(fLength); } 37 38 private: 39 struct FreeWrapper { void operator()(void*); }; 40 std::unique_ptr<char[], FreeWrapper> fPtr; 41 std::size_t fLength = 0; 42 std::size_t fCapacity = 0; 43 void realloc(std::size_t); 44 }; 45 } // namespace SkPlainTextEditor 46 #endif // stringslice_DEFINED 47