tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
monotonic_allocator.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2024 Tobias Hienzsch
3
4#ifndef TETL_MEMORY_MONOTONIC_ALLOCATOR_HPP
5#define TETL_MEMORY_MONOTONIC_ALLOCATOR_HPP
6
7#include <etl/_cstddef/byte.hpp>
8#include <etl/_cstddef/ptrdiff_t.hpp>
9#include <etl/_cstddef/size_t.hpp>
10#include <etl/_memory/align.hpp>
11#include <etl/_span/span.hpp>
12
13namespace etl {
14template <typename T>
16 using value_type = T;
17 using size_type = etl::size_t;
18 using difference_type = etl::ptrdiff_t;
19
20 explicit monotonic_allocator(etl::span<etl::byte> memory)
21 : _memory{memory}
22 {
23 }
24
25 [[nodiscard]] auto allocate(etl::size_t n) -> T*
26 {
27 if (etl::align(alignof(T), sizeof(T) * n, _ptr, _sz) != nullptr) {
28 auto* result = reinterpret_cast<T*>(_ptr);
29 _ptr = reinterpret_cast<char*>(_ptr) + sizeof(T) * n;
30 _sz -= sizeof(T) * n;
31 return result;
32 }
33 return nullptr;
34 }
35
36 auto deallocate(T* p, etl::size_t n) -> void
37 {
38 etl::ignore_unused(p, n);
39 }
40
41private:
42 etl::span<etl::byte> _memory;
43 void* _ptr{_memory.data()};
44 etl::size_t _sz{_memory.size()};
45};
46
47} // namespace etl
48
49#endif // TETL_MEMORY_MONOTONIC_ALLOCATOR_HPP
Definition adjacent_find.hpp:9
auto align(etl::size_t alignment, etl::size_t size, void *&ptr, etl::size_t &space) noexcept -> void *
Given a pointer ptr to a buffer of size space, returns a pointer aligned by the specified alignment f...
Definition align.hpp:23
enum TETL_MAY_ALIAS byte
etl::byte is a distinct type that implements the concept of byte as specified in the C++ language def...
Definition byte.hpp:22
Definition monotonic_allocator.hpp:15
auto deallocate(T *p, etl::size_t n) -> void
Definition monotonic_allocator.hpp:36
monotonic_allocator(etl::span< etl::byte > memory)
Definition monotonic_allocator.hpp:20
auto allocate(etl::size_t n) -> T *
Definition monotonic_allocator.hpp:25
constexpr auto data() const noexcept -> pointer
Returns a pointer to the beginning of the sequence.
Definition span.hpp:225
constexpr auto size() const noexcept -> size_type
Returns the number of elements in the span.
Definition span.hpp:231