liblcf
Loading...
Searching...
No Matches
dbarray.cpp
Go to the documentation of this file.
1#include "lcf/dbarrayalloc.h"
2#include "lcf/dbarray.h"
3#include "lcf/dbstring.h"
4#include <cassert>
5#include <cstddef>
6
7//#define LCF_DEBUG_DBARRAY
8
9#ifdef LCF_DEBUG_DBARRAY
10#include <iostream>
11#endif
12
13namespace lcf {
14
15const DBArrayAlloc::size_type DBArrayAlloc::_empty_buf[2] = { 0, 0 };
16constexpr DBString::size_type DBString::npos;
17
18static ptrdiff_t HeaderSize(size_t align) {
19 return std::max(sizeof(DBArrayAlloc::size_type), align);
20}
21
22static size_t AllocSize(size_t size, size_t align) {
23 return HeaderSize(align) + size;
24}
25
26static void* Adjust(void* p, ptrdiff_t off) {
27 return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(p) + off);
28}
29
30void* DBArrayAlloc::alloc(size_type size, size_type field_size, size_type align) {
31 if (field_size == 0) {
32 return empty_buf();
33 }
34 assert(align <= alignof(std::max_align_t));
35 auto* raw = ::operator new(AllocSize(size, align));
36 auto* p = Adjust(raw, HeaderSize(align));
37 *get_size_ptr(p) = field_size;
38#ifdef LCF_DEBUG_DBARRAY
39 std::cout << "DBArray: Allocated"
40 << " size=" << size
41 << " field_size=" << *get_size_ptr(p)
42 << " align=" << align
43 << " ptr=" << raw
44 << " adjusted=" << p
45 << std::endl;
46#endif
47 return p;
48}
49
50void DBArrayAlloc::free(void* p, size_type align) noexcept {
51 assert(p != nullptr);
52 if (p != empty_buf()) {
53 auto* raw = Adjust(p, -HeaderSize(align));
54#ifdef LCF_DEBUG_DBARRAY
55 std::cout << "DBArray: Free"
56 << " align=" << align
57 << " ptr=" << raw
58 << " adjusted=" << p
59 << " field_size=" << *get_size_ptr(p)
60 << std::endl;
61#endif
62 ::operator delete(raw);
63 }
64}
65
66char* DBString::construct_z(const char* s, size_t len) {
67 auto* p = alloc(len);
68 if (len) {
69 std::memcpy(p, s, len + 1);
70 }
71 return p;
72}
73
74char* DBString::construct_sv(const char* s, size_t len) {
75 auto* p = alloc(len);
76 if (len) {
77 std::memcpy(p, s, len);
78 p[len] = '\0';
79 }
80 return p;
81}
82
83DBString& DBString::operator=(const DBString& o) {
84 if (this != &o) {
85 destroy();
86 _storage = construct_z(o.data(), o.size());
87 }
88 return *this;
89}
90
91} // namespace lcf
static void * Adjust(void *p, ptrdiff_t off)
Definition dbarray.cpp:26
static ptrdiff_t HeaderSize(size_t align)
Definition dbarray.cpp:18
static size_t AllocSize(size_t size, size_t align)
Definition dbarray.cpp:22