aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/memory/erased_storage.h
blob: 46ea5cc854d0e34d53e4e62f5d9f2905de8b03b4 (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
#pragma once

#include <concepts>
#include <memory>

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

template <size_t MaxByteSize>
class TErasedStorage;

////////////////////////////////////////////////////////////////////////////////

namespace NDetail {

template <class T>
struct TIsErasedStorage
    : public std::false_type
{ };

template <size_t N>
struct TIsErasedStorage<TErasedStorage<N>>
    : public std::true_type
{ };

} // namespace NDetail

////////////////////////////////////////////////////////////////////////////////

template <class T, size_t ErasedStorageMaxByteSize>
concept CTriviallyErasable =
    std::default_initializable<T> &&
    std::is_trivially_destructible_v<T> &&
    std::is_trivially_copyable_v<T> &&
    (sizeof(T) <= ErasedStorageMaxByteSize) &&
    (alignof(T) <= ErasedStorageMaxByteSize) &&
    !std::is_reference_v<T> &&
    !NDetail::TIsErasedStorage<T>::value;

////////////////////////////////////////////////////////////////////////////////

// This class does not call dtor of erased object
// thus we require trivial destructability.
template <size_t MaxByteSize>
class TErasedStorage
{
public:
    static constexpr size_t ByteSize = MaxByteSize;

    template <CTriviallyErasable<MaxByteSize> TDecayedConcrete>
    explicit TErasedStorage(TDecayedConcrete concrete) noexcept;

    TErasedStorage(const TErasedStorage& other) = default;
    TErasedStorage& operator=(const TErasedStorage& other) = default;

    template <CTriviallyErasable<MaxByteSize> TDecayedConcrete>
    TDecayedConcrete& AsConcrete() & noexcept;

    template <CTriviallyErasable<MaxByteSize> TDecayedConcrete>
    const TDecayedConcrete& AsConcrete() const & noexcept;

    template <CTriviallyErasable<MaxByteSize> TDecayedConcrete>
    TDecayedConcrete&& AsConcrete() && noexcept;

    bool operator==(const TErasedStorage& other) const = default;

private:
    // NB(arkady-e1ppa): aligned_storage is deprecated.
    alignas(MaxByteSize) std::byte Bytes_[MaxByteSize];
};

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT

#define ERASED_STORAGE_INL_H_
#include "erased_storage-inl.h"
#undef ERASED_STORAGE_INL_H_