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

#include <concepts>
#include <memory>

namespace NYT {

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

constexpr size_t ErasedStorageMaxByteSize = 32;

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

class TErasedStorage;

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

template <class T>
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> &&
    !std::same_as<T, TErasedStorage>;

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

// This class does not call dtor of erased object
// thus we require trivial destructability.
class TErasedStorage
{
public:
    template <CTriviallyErasable TDecayedConcrete>
    explicit TErasedStorage(TDecayedConcrete concrete) noexcept;

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

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

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

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

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

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

} // namespace NYT

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