This repository was archived by the owner on Jun 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp_buffer.hpp
More file actions
126 lines (107 loc) · 2.69 KB
/
temp_buffer.hpp
File metadata and controls
126 lines (107 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//
// Fixed size stack allocated temporary buffer with dynamic allocation fall back
//
// Copyright(c) 2020 Chronimal. All rights reserved.
//
// Licensed under the MIT license; A copy of the license that can be
// found in the LICENSE file.
//
#ifndef TB_TEMP_BUFFER_HPP_INCLUDED
#define TB_TEMP_BUFFER_HPP_INCLUDED
// Configure namespace preference for TempBuffer.
// By default namespace utl is used.
#define TB_NAMESPACE_NAME utl
// clang-format off
#ifndef TB_BEGIN_NAMESPACE
#define TB_BEGIN_NAMESPACE namespace TB_NAMESPACE_NAME {
#endif // TB_BEGIN_NAMESPAC
#ifndef TB_END_NAMESPACE
#define TB_END_NAMESPACE }
#endif // TB_END_NAMESPACE
// clang-format on
#include <memory_resource>
#include <algorithm>
#include <bit>
TB_BEGIN_NAMESPACE
template<std::size_t L>
class TempBuffer
{
public:
TempBuffer() noexcept = default;
TempBuffer(TempBuffer&&) = delete;
TempBuffer(TempBuffer const&) = delete;
TempBuffer& operator=(TempBuffer&&) = delete;
TempBuffer& operator=(TempBuffer const&) = delete;
TempBuffer(std::size_t size) noexcept
: TempBuffer{}
{
resize(size);
}
TempBuffer(std::size_t size, int pattern) noexcept
: TempBuffer{size}
{
std::fill_n(p_, size, static_cast<std::byte>(pattern));
}
~TempBuffer()
{
reset();
}
void resize(size_t size)
{
if (size > sizeof(buffer_))
{
auto p = static_cast<decltype(p_)>(std::realloc(dynamic() ? p_ : nullptr, size));
if (p == nullptr)
{
throw std::bad_alloc();
}
p_ = p;
}
else
{
if (dynamic())
{
std::copy_n(p_, size, buffer_);
std::free(p_);
}
p_ = buffer_;
}
size_ = size;
}
void reset() noexcept
{
if (dynamic())
{
std::free(p_);
}
p_ = buffer_;
size_ = 0;
}
[[nodiscard]] void* get() const noexcept
{
return p_;
}
template<typename T, typename = std::enable_if_t<std::is_trivial_v<T> && std::is_standard_layout_v<T>>>
[[nodiscard]] T* as() const noexcept
{
return std::bit_cast<T*>(p_);
}
[[nodiscard]] std::size_t size() const noexcept
{
return size_;
}
[[nodiscard]] bool dynamic() const noexcept
{
return size_ > sizeof(buffer_);
}
[[nodiscard]] constexpr bool empty() const noexcept
{
return size_ == 0;
}
private:
std::size_t size_{};
std::byte* p_{buffer_};
alignas(std::max_align_t) std::byte buffer_[L];
};
TB_END_NAMESPACE
#endif // TB_TEMP_BUFFER_HPP_INCLUDED