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