tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
align.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2020 Tobias Hienzsch
3
4#ifndef TETL_MEMORY_ALIGN_HPP
5#define TETL_MEMORY_ALIGN_HPP
6
7#include <etl/_bit/bit_cast.hpp>
8#include <etl/_cstddef/size_t.hpp>
9#include <etl/_cstdint/uintptr_t.hpp>
10
11namespace etl {
12
13/// \brief Given a pointer ptr to a buffer of size space, returns a pointer
14/// aligned by the specified alignment for size number of bytes and decreases
15/// space argument by the number of bytes used for alignment. The first aligned
16/// address is returned.
17///
18/// The function modifies the pointer only if it would be possible to fit the
19/// wanted number of bytes aligned by the given alignment into the buffer. If
20/// the buffer is too small, the function does nothing and returns nullptr.
21///
22/// \warning The behavior is undefined if alignment is not a power of two.
23[[nodiscard]] inline auto align(etl::size_t alignment, etl::size_t size, void*& ptr, etl::size_t& space) noexcept
24 -> void*
25{
26 auto off = static_cast<etl::size_t>(bit_cast<etl::uintptr_t>(ptr) & (alignment - 1));
27 if (off != 0) {
28 off = alignment - off;
29 }
30 if (space < off || space - off < size) {
31 return nullptr;
32 }
33
34 ptr = static_cast<char*>(ptr) + off;
35 space -= off;
36 return ptr;
37}
38
39} // namespace etl
40
41#endif // TETL_MEMORY_ALIGN_HPP
constexpr auto bit_cast(From const &src) noexcept -> To
Obtain a value of type To by reinterpreting the object representation of from. Every bit in the value...
Definition bit_cast.hpp:39
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