1 // Scintilla source code edit control 2 /** @file UniqueString.cxx 3 ** Define an allocator for UniqueString. 4 **/ 5 // Copyright 2017 by Neil Hodgson <[email protected]> 6 // The License.txt file describes the conditions under which this software may be distributed. 7 8 #include <string_view> 9 #include <vector> 10 #include <algorithm> 11 #include <memory> 12 13 #include "UniqueString.h" 14 15 namespace Scintilla { 16 17 /// Equivalent to strdup but produces a std::unique_ptr<const char[]> allocation to go 18 /// into collections. UniqueStringCopy(const char * text)19UniqueString UniqueStringCopy(const char *text) { 20 if (!text) { 21 return UniqueString(); 22 } 23 const std::string_view sv(text); 24 std::unique_ptr<char[]> upcNew = std::make_unique<char[]>(sv.length() + 1); 25 sv.copy(upcNew.get(), sv.length()); 26 return UniqueString(upcNew.release()); 27 } 28 29 // A set of strings that always returns the same pointer for each string. 30 31 UniqueStringSet::UniqueStringSet() noexcept = default; 32 ~UniqueStringSet()33UniqueStringSet::~UniqueStringSet() { 34 strings.clear(); 35 } 36 Clear()37void UniqueStringSet::Clear() noexcept { 38 strings.clear(); 39 } 40 Save(const char * text)41const char *UniqueStringSet::Save(const char *text) { 42 if (!text) 43 return nullptr; 44 45 const std::string_view sv(text); 46 for (const UniqueString &us : strings) { 47 if (sv == us.get()) { 48 return us.get(); 49 } 50 } 51 52 strings.push_back(UniqueStringCopy(text)); 53 return strings.back().get(); 54 } 55 56 } 57