aboutsummaryrefslogtreecommitdiffstats
path: root/yt/yt/core/ytree/interned_attributes.cpp
blob: 1b3f39c5b214d70b481a9d4a947930723def266a (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
#include "interned_attributes.h"

#include <yt/yt/core/misc/collection_helpers.h>
#include <yt/yt/core/misc/serialize.h>

namespace NYT::NYTree {

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

namespace {

class TInternedAttributeRegistry
{
public:
    void Intern(const TString& uninternedKey, TInternedAttributeKey internedKey)
    {
        YT_VERIFY(AttributeNameToIndex_.emplace(uninternedKey, internedKey).second);
        YT_VERIFY(AttributeIndexToName_.emplace(internedKey, uninternedKey).second);
    }

    TInternedAttributeKey GetInterned(TStringBuf uninternedKey)
    {
        auto it = AttributeNameToIndex_.find(uninternedKey);
        return it == AttributeNameToIndex_.end() ? InvalidInternedAttribute : it->second;
    }

    const TString& GetUninterned(TInternedAttributeKey internedKey)
    {
        return GetOrCrash(AttributeIndexToName_, internedKey);
    }

private:
    THashMap<TString, TInternedAttributeKey> AttributeNameToIndex_;
    THashMap<TInternedAttributeKey, TString> AttributeIndexToName_;
};

} // namespace

void InternAttribute(const TString& uninternedKey, TInternedAttributeKey internedKey)
{
    Singleton<TInternedAttributeRegistry>()->Intern(uninternedKey, internedKey);
}

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

TInternedAttributeKey::TInternedAttributeKey()
    : Code_(InvalidInternedAttribute.Code_)
{ }

void TInternedAttributeKey::Save(TStreamSaveContext& context) const
{
    using NYT::Save;

    Save(context, Unintern());
}

void TInternedAttributeKey::Load(TStreamLoadContext& context)
{
    using NYT::Load;

    auto uninternedKey = Load<TString>(context);
    Code_ = Lookup(uninternedKey).Code_;
}

/*static*/ TInternedAttributeKey TInternedAttributeKey::Lookup(TStringBuf uninternedKey)
{
    return Singleton<TInternedAttributeRegistry>()->GetInterned(uninternedKey);
}

const TString& TInternedAttributeKey::Unintern() const
{
    return Singleton<TInternedAttributeRegistry>()->GetUninterned(*this);
}

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

REGISTER_INTERNED_ATTRIBUTE(count, CountInternedAttribute)

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

} // namespace NYT::NYTree