1
1
mirror of https://github.com/mawww/kakoune.git synced 2024-12-22 19:11:40 +03:00
kakoune/src/shared_string.hh

85 lines
2.2 KiB
C++
Raw Normal View History

#ifndef shared_string_hh_INCLUDED
#define shared_string_hh_INCLUDED
#include "string.hh"
#include "ref_ptr.hh"
#include "utils.hh"
#include "unordered_map.hh"
namespace Kakoune
{
2015-03-01 15:03:08 +03:00
struct StringData : UseMemoryDomain<MemoryDomain::SharedString>
{
int refcount;
int length;
2015-05-14 21:13:52 +03:00
uint32_t hash;
2015-05-14 21:13:52 +03:00
StringData(int ref, int len) : refcount(ref), length(len) {}
2015-01-26 22:41:26 +03:00
[[gnu::always_inline]]
2015-01-26 01:36:05 +03:00
char* data() { return reinterpret_cast<char*>(this + 1); }
2015-01-26 22:41:26 +03:00
[[gnu::always_inline]]
2015-01-26 01:36:05 +03:00
const char* data() const { return reinterpret_cast<const char*>(this + 1); }
2015-01-26 22:41:26 +03:00
[[gnu::always_inline]]
2015-01-26 01:36:05 +03:00
StringView strview() const { return {data(), length}; }
struct PtrPolicy
{
static void inc_ref(StringData* r, void*) { ++r->refcount; }
static void dec_ref(StringData* r, void*) { if (--r->refcount == 0) delete r; }
static void ptr_moved(StringData*, void*, void*) noexcept {}
};
static RefPtr<StringData, PtrPolicy> create(StringView str, char back = 0)
{
const int len = (int)str.length() + (back != 0 ? 1 : 0);
2015-03-01 15:03:08 +03:00
void* ptr = StringData::operator new(sizeof(StringData) + len + 1);
auto* res = new (ptr) StringData(0, len);
std::copy(str.begin(), str.end(), res->data());
if (back != 0)
2015-01-26 01:36:05 +03:00
res->data()[len-1] = back;
res->data()[len] = 0;
2015-05-14 21:13:52 +03:00
res->hash = hash_data(res->data(), res->length);
return RefPtr<StringData, PtrPolicy>{res};
}
2015-03-01 15:03:08 +03:00
static void destroy(StringData* s)
{
2015-03-01 15:03:08 +03:00
StringData::operator delete(s, sizeof(StringData) + s->length + 1);
}
2015-03-01 15:03:08 +03:00
friend void inc_ref_count(StringData* s, void*)
{
2015-03-12 12:52:33 +03:00
++s->refcount;
}
2015-03-01 15:03:08 +03:00
friend void dec_ref_count(StringData* s, void*)
{
2015-03-12 12:52:33 +03:00
if (--s->refcount == 0)
2015-03-01 15:03:08 +03:00
StringData::destroy(s);
}
};
using StringDataPtr = RefPtr<StringData, StringData::PtrPolicy>;
class StringRegistry : public Singleton<StringRegistry>
{
public:
void debug_stats() const;
StringDataPtr intern(StringView str);
void purge_unused();
private:
UnorderedMap<StringView, StringDataPtr, MemoryDomain::SharedString> m_strings;
};
inline StringDataPtr intern(StringView str)
{
return StringRegistry::instance().intern(str);
}
}
#endif // shared_string_hh_INCLUDED