Cogs.Core
ImmutableString.cpp
1#include <mutex>
2#include <OsoMemoryProfiler/OsoMemoryProfiler.h>
3#include "ImmutableString.h"
4#include "Collections/PoolBase.h"
5
6namespace {
7 using namespace Cogs;
8 using namespace Cogs::Collections;
9
10 constexpr size_t S = sizeof(size_t);
11 constexpr size_t shortStringSize = 32;
12
13 constexpr size_t getByteSize(size_t N)
14 {
15 return S + N + 1;
16 }
17
18 constexpr bool isShortString(size_t byteSize)
19 {
20 return byteSize < shortStringSize;
21 }
22
23 struct StaticStore {
24 PoolBase shortStringPool = PoolBase(shortStringSize, 128, 128, Memory::Allocator::defaultAllocator(), MemBlockType::Strings);
25 std::mutex lock;
26 };
27
28 StaticStore& getStore()
29 {
30 static StaticStore store;
31 return store;
32 }
33
34}
35
36
38{
39 release();
40 if (!view.empty()) {
41 const size_t N = view.size();
42 assert(N != 0);
43 assert(ptr == nullptr);
44
45 const size_t byteSize = getByteSize(N);
46 if (isShortString(byteSize)) {
47 StaticStore& store = getStore();
48 std::lock_guard guard(store.lock);
49 ptr = static_cast<char*>(store.shortStringPool.allocate());
50 }
51 else {
52 ptr = new char[byteSize];
53 OsoMP_Allocate(uint8_t(MemBlockType::Strings), ptr, byteSize, nullptr, 0);
54 }
55 assert(ptr);
56 std::memcpy(ptr, &N, S);
57 std::memcpy(ptr + S, view.data(), N);
58 ptr[S + N] = '\0';
59 }
60}
61
62void Cogs::ImmutableString::release()
63{
64 if (ptr) {
65 size_t N = 0;
66 std::memcpy(&N, ptr, sizeof(N));
67
68 const size_t byteSize = getByteSize(N);
69 if (isShortString(byteSize)) {
70 StaticStore& store = getStore();
71 std::lock_guard guard(store.lock);
72 store.shortStringPool.deallocate(ptr);
73 }
74 else {
75 OsoMP_Free(uint8_t(MemBlockType::Strings), ptr, nullptr, 0);
76 delete[] ptr;
77 }
78 ptr = nullptr;
79 }
80}
constexpr ImmutableString() noexcept=default
Create an empty string.
static Allocator * defaultAllocator()
Gets the system default allocator.
Definition: Allocator.cpp:17
Provides a weakly referenced view over the contents of a string.
Definition: StringView.h:24
constexpr const char * data() const noexcept
Get the sequence of characters referenced by the string view.
Definition: StringView.h:171
constexpr size_t size() const noexcept
Get the size of the string.
Definition: StringView.h:178
constexpr bool empty() const noexcept
Check if the string is empty.
Definition: StringView.h:122
Contains collection classes used to manage object storage.
Contains all Cogs related functionality.
Definition: FieldSetter.h:23
Base untyped pool.
Definition: PoolBase.h:22