From 3d5a0c672e6f3cf87944b33712e17531aa42c607 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Wed, 28 Feb 2024 19:00:51 +1100 Subject: Templatize StringData::create This improves performance by letting the compiler optimize most use cases where string count and length are known are compile time. --- src/shared_string.hh | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'src/shared_string.hh') diff --git a/src/shared_string.hh b/src/shared_string.hh index 17bb72d8..bb06c7fc 100644 --- a/src/shared_string.hh +++ b/src/shared_string.hh @@ -7,6 +7,7 @@ #include "hash_map.hh" #include +#include namespace Kakoune { @@ -32,12 +33,11 @@ private: static void inc_ref(StringData* r, void*) noexcept { ++r->refcount; } static void dec_ref(StringData* r, void*) noexcept { - if ((--r->refcount & refcount_mask) == 0) - { - if (r->refcount & interned_flag) - Registry::instance().remove(r->strview()); - StringData::operator delete(r, sizeof(StringData) + r->length + 1); - } + if ((--r->refcount & refcount_mask) > 0) + return; + if (r->refcount & interned_flag) + Registry::instance().remove(r->strview()); + StringData::operator delete(r, sizeof(StringData) + r->length + 1); } static void ptr_moved(StringData*, void*, void*) noexcept {} }; @@ -57,7 +57,23 @@ public: HashMap m_strings; }; - static Ptr create(ArrayView strs); + static Ptr create(ConvertibleTo auto&&... strs) + { + const int len = ((int)StringView{strs}.length() + ...); + void* ptr = StringData::operator new(sizeof(StringData) + len + 1); + auto* res = new (ptr) StringData(len); + auto* data = reinterpret_cast(res + 1); + auto append = [&](StringView str) { + if (str.empty()) // memccpy(..., nullptr, 0) is UB + return; + memcpy(data, str.begin(), (size_t)str.length()); + data += (int)str.length(); + }; + (append(strs), ...); + *data = 0; + return RefPtr{res}; + } + }; using StringDataPtr = StringData::Ptr; -- cgit v1.2.3