aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/memory/ref_tracked-inl.h
blob: 0c16c02ff88f7ab10ff0b466203e3324a53a133e (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
#ifndef REF_TRACKED_INL_H_
#error "Direct inclusion of this file is not allowed, include ref_tracked.h"
// For the sake of sane code completion.
#include "ref_tracked.h"
#endif

namespace NYT {

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

template <class T>
TRefCountedTypeKey GetRefCountedTypeKey()
{
    return TRefCountedTypeKey(&typeid(T));
}

template <class T>
Y_FORCE_INLINE TRefCountedTypeCookie GetRefCountedTypeCookie()
{
    static std::atomic<TRefCountedTypeCookie> cookie{NullRefCountedTypeCookie};
    auto cookieValue = cookie.load(std::memory_order::relaxed);
    if (Y_UNLIKELY(cookieValue == NullRefCountedTypeCookie)) {
        cookieValue = TRefCountedTrackerFacade::GetCookie(
            GetRefCountedTypeKey<T>(),
            sizeof(T),
            NYT::TSourceLocation());
        cookie.store(cookieValue, std::memory_order::relaxed);
    }
    return cookieValue;
}

template <class T, class TTag, int Counter>
Y_FORCE_INLINE TRefCountedTypeCookie GetRefCountedTypeCookieWithLocation(const TSourceLocation& location)
{
    static std::atomic<TRefCountedTypeCookie> cookie{NullRefCountedTypeCookie};
    auto cookieValue = cookie.load(std::memory_order::relaxed);
    if (Y_UNLIKELY(cookieValue == NullRefCountedTypeCookie)) {
        cookieValue = TRefCountedTrackerFacade::GetCookie(
            GetRefCountedTypeKey<T>(),
            sizeof(T),
            location);
        cookie.store(cookieValue, std::memory_order::relaxed);
    }
    return cookieValue;
}

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

#ifdef YT_ENABLE_REF_COUNTED_TRACKING

template <class T>
TRefTracked<T>::TRefTracked()
{
    auto cookie = GetRefCountedTypeCookie<T>();
    TRefCountedTrackerFacade::AllocateInstance(cookie);
}

template <class T>
TRefTracked<T>::TRefTracked(const TRefTracked&)
{
    auto cookie = GetRefCountedTypeCookie<T>();
    TRefCountedTrackerFacade::AllocateInstance(cookie);
}

template <class T>
TRefTracked<T>::TRefTracked(TRefTracked&&)
{
    auto cookie = GetRefCountedTypeCookie<T>();
    TRefCountedTrackerFacade::AllocateInstance(cookie);
}

template <class T>
TRefTracked<T>::~TRefTracked()
{
    auto cookie = GetRefCountedTypeCookie<T>();
    TRefCountedTrackerFacade::FreeInstance(cookie);
}

#endif

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

} // namespace NYT