summaryrefslogtreecommitdiffstats
path: root/src/common/alignment.h
blob: e4653bf35788f33fb449f25faec1187e34b2b016 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// This file is under the public domain.

#pragma once

#include <cstddef>
#include <type_traits>

namespace Common {

template <typename T>
requires std::is_unsigned_v<T>
[[nodiscard]] constexpr T AlignUp(T value, size_t size) {
    auto mod{static_cast<T>(value % size)};
    value -= mod;
    return static_cast<T>(mod == T{0} ? value : value + size);
}

template <typename T>
requires std::is_unsigned_v<T>
[[nodiscard]] constexpr T AlignUpLog2(T value, size_t align_log2) {
    return static_cast<T>((value + ((1ULL << align_log2) - 1)) >> align_log2 << align_log2);
}

template <typename T>
requires std::is_unsigned_v<T>
[[nodiscard]] constexpr T AlignDown(T value, size_t size) {
    return static_cast<T>(value - value % size);
}

template <typename T>
requires std::is_unsigned_v<T>
[[nodiscard]] constexpr bool Is4KBAligned(T value) {
    return (value & 0xFFF) == 0;
}

template <typename T>
requires std::is_unsigned_v<T>
[[nodiscard]] constexpr bool IsWordAligned(T value) {
    return (value & 0b11) == 0;
}

template <typename T>
requires std::is_integral_v<T>
[[nodiscard]] constexpr bool IsAligned(T value, size_t alignment) {
    using U = typename std::make_unsigned_t<T>;
    const U mask = static_cast<U>(alignment - 1);
    return (value & mask) == 0;
}

template <typename T, typename U>
requires std::is_integral_v<T>
[[nodiscard]] constexpr T DivideUp(T x, U y) {
    return (x + (y - 1)) / y;
}

template <typename T, size_t Align = 16>
class AlignmentAllocator {
public:
    using value_type = T;
    using size_type = size_t;
    using difference_type = ptrdiff_t;

    using propagate_on_container_copy_assignment = std::true_type;
    using propagate_on_container_move_assignment = std::true_type;
    using propagate_on_container_swap = std::true_type;
    using is_always_equal = std::false_type;

    constexpr AlignmentAllocator() noexcept = default;

    template <typename T2>
    constexpr AlignmentAllocator(const AlignmentAllocator<T2, Align>&) noexcept {}

    [[nodiscard]] T* allocate(size_type n) {
        return static_cast<T*>(::operator new (n * sizeof(T), std::align_val_t{Align}));
    }

    void deallocate(T* p, size_type n) {
        ::operator delete (p, n * sizeof(T), std::align_val_t{Align});
    }

    template <typename T2>
    struct rebind {
        using other = AlignmentAllocator<T2, Align>;
    };

    template <typename T2, size_t Align2>
    constexpr bool operator==(const AlignmentAllocator<T2, Align2>&) const noexcept {
        return std::is_same_v<T, T2> && Align == Align2;
    }
};

} // namespace Common