Skip to content

Commit 6b160e9

Browse files
committed
core: Introduce stateless allocator for JSON
A stateless allocator is added for JSON parsing. This allocator forwards all requests to a thread local pointer to a memory resource, and assumes that the resource has been initialized when the allocator is constructed. Signed-off-by: Abhijat Malviya <[email protected]>
1 parent 978961f commit 6b160e9

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/core/json/json_object.cc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ std::optional<T> ParseWithDecoder(std::string_view input, json_decoder<T>&& deco
4646

4747
namespace dfly {
4848

49+
void InitTLJsonHeap(PMR_NS::memory_resource* mr) {
50+
detail::tl_mr = mr;
51+
}
52+
4953
std::optional<ShortLivedJSON> JsonFromString(std::string_view input) {
5054
return ParseWithDecoder(input, json_decoder<ShortLivedJSON>{});
5155
}

src/core/json/json_object.h

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,52 @@
2121

2222
namespace dfly {
2323

24+
namespace detail {
25+
26+
inline thread_local PMR_NS::memory_resource* tl_mr = nullptr;
27+
28+
template <typename T> class StatelessJsonAllocator {
29+
public:
30+
using value_type = T;
31+
using size_type = std::size_t;
32+
using difference_type = std::ptrdiff_t;
33+
using is_always_equal = std::true_type;
34+
35+
template <typename U> StatelessJsonAllocator(const StatelessJsonAllocator<U>&) noexcept {
36+
}
37+
38+
StatelessJsonAllocator() noexcept {
39+
DCHECK_NE(tl_mr, nullptr) << "json allocator created without backing memory resource";
40+
};
41+
42+
static value_type* allocate(size_type n) {
43+
void* ptr = tl_mr->allocate(n * sizeof(value_type), alignof(value_type));
44+
return static_cast<value_type*>(ptr);
45+
}
46+
47+
static void deallocate(value_type* ptr, size_type n) noexcept {
48+
tl_mr->deallocate(ptr, n * sizeof(value_type), alignof(value_type));
49+
}
50+
51+
static PMR_NS::memory_resource* resource() {
52+
return tl_mr;
53+
}
54+
};
55+
56+
template <typename T, typename U>
57+
bool operator==(const StatelessJsonAllocator<T>&, const StatelessJsonAllocator<U>&) noexcept {
58+
return true;
59+
}
60+
61+
template <typename T, typename U>
62+
bool operator!=(const StatelessJsonAllocator<T>&, const StatelessJsonAllocator<U>&) noexcept {
63+
return false;
64+
}
65+
66+
} // namespace detail
67+
68+
void InitTLJsonHeap(PMR_NS::memory_resource* mr);
69+
2470
using ShortLivedJSON = jsoncons::json;
2571
using JsonType = jsoncons::pmr::json;
2672

0 commit comments

Comments
 (0)