ublk-cpp v0.0
Loading...
Searching...
No Matches
utils.hpp
Go to the documentation of this file.
1
5
6#pragma once
7
8#include <utility>
9#include <vector>
10
11namespace ublk {
12namespace detail {
13
14template <typename Func> auto defer(Func &&func) noexcept {
15 using F = std::decay_t<Func>;
16 class [[nodiscard]] Defer {
17 public:
18 Defer(F func) : func_(std::move(func)) {}
19 ~Defer() { func_(); }
20
21 Defer(const Defer &) = delete;
22 Defer &operator=(const Defer &) = delete;
23 Defer(Defer &&) = delete;
24 Defer &operator=(Defer &&) = delete;
25
26 private:
27 F func_;
28 };
29 return Defer(std::forward<Func>(func));
30}
31
32template <typename T, typename Alloc>
33using AllocVector = std::vector<
34 T, typename std::allocator_traits<Alloc>::template rebind_alloc<T>>;
35
36template <typename T> inline T align_up(T value, T alignment) noexcept {
37 // alignment must be a power of two
38 assert(alignment > 0 && (alignment & (alignment - 1)) == 0);
39 return (value + alignment - 1) & ~(alignment - 1);
40}
41
42template <typename T>
43concept is_pmr_allocator = requires(const T &a) {
44 { a.resource() } -> std::convertible_to<std::pmr::memory_resource *>;
45};
46
47template <typename Alloc>
48[[nodiscard]] inline void *alloc_aligned(const Alloc &alloc, size_t bytes,
49 size_t alignment) {
50 if constexpr (is_pmr_allocator<Alloc>) {
51 return alloc.resource()->allocate(bytes, alignment);
52 } else {
53 return ::operator new(bytes, std::align_val_t{alignment});
54 }
55}
56
57template <typename Alloc>
58inline void free_aligned(const Alloc &alloc, void *ptr, size_t bytes,
59 size_t alignment) noexcept {
60 if constexpr (is_pmr_allocator<Alloc>) {
61 alloc.resource()->deallocate(ptr, bytes, alignment);
62 } else {
63 ::operator delete(ptr, bytes, std::align_val_t{alignment});
64 }
65}
66
67} // namespace detail
68} // namespace ublk
The main namespace of the ublk-cpp library.
Definition ublk.hpp:21