6#ifndef NURI_CORE_CONTAINER_DUMB_BUFFER_H_
7#define NURI_CORE_CONTAINER_DUMB_BUFFER_H_
15#include <absl/log/absl_check.h>
25 constexpr static size_t bytes(
size_t len)
noexcept {
26 return len *
sizeof(T);
29 static T *alloc(
size_t len)
noexcept {
30 void *buf = std::malloc(bytes(len));
31 ABSL_QCHECK(buf !=
nullptr);
32 return static_cast<T *
>(buf);
35 static T *realloc(T *orig,
size_t len)
noexcept {
36 void *buf = std::realloc(
static_cast<void *
>(orig), bytes(len));
37 ABSL_QCHECK(buf !=
nullptr);
38 return static_cast<T *
>(buf);
41 static void copy(T *dst,
const T *src,
size_t len)
noexcept {
42 std::memcpy(
static_cast<void *
>(dst),
static_cast<const void *
>(src),
47 static_assert(std::is_same_v<T, remove_cvref_t<T>>,
48 "T must not have cv-qualifiers or reference");
49 static_assert(std::is_trivially_copyable_v<T>,
50 "T must be trivially copyable");
51 static_assert(
alignof(T) <=
alignof(std::max_align_t),
52 "T must have less than or equal alignment to all scalar "
55 DumbBuffer(
size_t len)
noexcept: data_(alloc(len)), len_(len) { }
57 DumbBuffer(
const DumbBuffer &other) noexcept
58 : data_(alloc(other.len_)), len_(other.len_) {
59 copy(data_, other.data_, len_);
62 DumbBuffer(DumbBuffer &&other) noexcept
63 : data_(other.data_), len_(other.len_) {
64 other.data_ =
nullptr;
68 ~DumbBuffer() noexcept { std::free(
static_cast<void *
>(data_)); }
70 DumbBuffer &operator=(
const DumbBuffer &other)
noexcept {
76 copy(data_, other.data_, len_);
80 DumbBuffer &operator=(DumbBuffer &&other)
noexcept {
81 std::swap(data_, other.data_);
82 std::swap(len_, other.len_);
86 T &operator[](
size_t idx)
noexcept {
return data_[idx]; }
88 const T &operator[](
size_t idx)
const noexcept {
return data_[idx]; }
90 T *data() noexcept {
return data_; }
92 const T *data() const noexcept {
return data_; }
94 size_t size() const noexcept {
return len_; }
96 void resize(
size_t len)
noexcept {
97 data_ = realloc(data_, len_);
101 T *begin() noexcept {
return data_; }
102 T *end() noexcept {
return data_ + len_; }
104 const T *cbegin() const noexcept {
return data_; }
105 const T *cend() const noexcept {
return data_ + len_; }
106 const T *begin() const noexcept {
return cbegin(); }
107 const T *end() const noexcept {
return cend(); }