shared_string.hh (2606B)
1 #ifndef shared_string_hh_INCLUDED 2 #define shared_string_hh_INCLUDED 3 4 #include "string.hh" 5 #include "ref_ptr.hh" 6 #include "utils.hh" 7 #include "hash_map.hh" 8 9 #include <cstring> 10 11 namespace Kakoune 12 { 13 14 struct StringData : UseMemoryDomain<MemoryDomain::SharedString> 15 { 16 uint32_t refcount; 17 const int length; 18 19 [[gnu::always_inline]] 20 const char* data() const { return reinterpret_cast<const char*>(this + 1); } 21 [[gnu::always_inline]] 22 StringView strview() const { return {data(), length}; } 23 24 private: 25 StringData(int len) : refcount(0), length(len) {} 26 27 static constexpr uint32_t interned_flag = 1u << 31; 28 static constexpr uint32_t refcount_mask = ~interned_flag; 29 30 struct PtrPolicy 31 { 32 static void inc_ref(StringData* r, void*) noexcept { ++r->refcount; } 33 static void dec_ref(StringData* r, void*) noexcept 34 { 35 if ((--r->refcount & refcount_mask) > 0) 36 return; 37 if (r->refcount & interned_flag) 38 Registry::instance().remove(r->strview()); 39 auto alloc_len = sizeof(StringData) + r->length + 1; 40 r->~StringData(); 41 operator delete(r, alloc_len); 42 } 43 static void ptr_moved(StringData*, void*, void*) noexcept {} 44 }; 45 46 public: 47 using Ptr = RefPtr<StringData, PtrPolicy>; 48 49 class Registry : public Singleton<Registry> 50 { 51 public: 52 void debug_stats() const; 53 Ptr intern(StringView str); 54 Ptr intern(StringView str, size_t hash); 55 void remove(StringView str); 56 57 private: 58 HashMap<StringView, StringData*, MemoryDomain::SharedString> m_strings; 59 }; 60 61 static Ptr create(ConvertibleTo<StringView> auto&&... strs) 62 { 63 const int len = ((int)StringView{strs}.length() + ...); 64 void* ptr = operator new(sizeof(StringData) + len + 1); 65 auto* res = new (ptr) StringData(len); 66 auto* data = reinterpret_cast<char*>(res + 1); 67 auto append = [&](StringView str) { 68 if (str.empty()) // memcpy(..., nullptr, 0) is UB 69 return; 70 memcpy(data, str.begin(), (size_t)str.length()); 71 data += (int)str.length(); 72 }; 73 (append(strs), ...); 74 *data = 0; 75 return Ptr{res}; 76 } 77 }; 78 79 using StringDataPtr = StringData::Ptr; 80 using StringRegistry = StringData::Registry; 81 82 inline StringDataPtr intern(StringView str) { return StringRegistry::instance().intern(str); } 83 inline StringDataPtr intern(StringView str, size_t hash) { return StringRegistry::instance().intern(str, hash); } 84 85 } 86 87 #endif // shared_string_hh_INCLUDED