|
| 1 | +/** |
| 2 | + * \file libipc/aligned.h |
| 3 | + * \author mutouyun (orz@orzz.org) |
| 4 | + * \brief Defines the type suitable for use as uninitialized storage for types of given type. |
| 5 | + */ |
| 6 | +#pragma once |
| 7 | + |
| 8 | +#include <array> |
| 9 | +#include <cstddef> |
| 10 | + |
| 11 | +#include "libipc/imp/byte.h" |
| 12 | + |
| 13 | +namespace ipc { |
| 14 | + |
| 15 | +/** |
| 16 | + * \brief The type suitable for use as uninitialized storage for types of given type. |
| 17 | + * std::aligned_storage is deprecated in C++23, so we define our own. |
| 18 | + * \tparam T The type to be aligned. |
| 19 | + * \tparam AlignT The alignment of the type. |
| 20 | + * \see https://en.cppreference.com/w/cpp/types/aligned_storage |
| 21 | + * https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p1413r3.pdf |
| 22 | + */ |
| 23 | +template <typename T, std::size_t AlignT = alignof(T)> |
| 24 | +class aligned { |
| 25 | + alignas(AlignT) std::array<ipc::byte, sizeof(T)> storage_; |
| 26 | + |
| 27 | +public: |
| 28 | + /** |
| 29 | + * \brief Returns a pointer to the aligned storage. |
| 30 | + * \return A pointer to the aligned storage. |
| 31 | + */ |
| 32 | + T *ptr() noexcept { |
| 33 | + return reinterpret_cast<T *>(storage_.data()); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * \brief Returns a pointer to the aligned storage. |
| 38 | + * \return A pointer to the aligned storage. |
| 39 | + */ |
| 40 | + T const *ptr() const noexcept { |
| 41 | + return reinterpret_cast<const T *>(storage_.data()); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * \brief Returns a reference to the aligned storage. |
| 46 | + * \return A reference to the aligned storage. |
| 47 | + */ |
| 48 | + T &ref() noexcept { |
| 49 | + return *ptr(); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * \brief Returns a reference to the aligned storage. |
| 54 | + * \return A reference to the aligned storage. |
| 55 | + */ |
| 56 | + T const &ref() const noexcept { |
| 57 | + return *ptr(); |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +/** |
| 62 | + * \brief Rounds up the given value to the given alignment. |
| 63 | + * \tparam T The type of the value. |
| 64 | + * \param value The value to be rounded up. |
| 65 | + * \param alignment The alignment to be rounded up to. |
| 66 | + * \return The rounded up value. |
| 67 | + * \see https://stackoverflow.com/questions/3407012/c-rounding-up-to-the-nearest-multiple-of-a-number |
| 68 | +*/ |
| 69 | +template <typename T> |
| 70 | +constexpr T round_up(T value, T alignment) noexcept { |
| 71 | + return (value + alignment - 1) & ~(alignment - 1); |
| 72 | +} |
| 73 | + |
| 74 | +} // namespace ipc |
0 commit comments