aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/protobuf/util/walk.cpp
blob: b65ec03e047600923116d5240f0d96c12b196737 (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
#include "walk.h"

#include <util/generic/hash_set.h>

namespace {
    using namespace NProtoBuf;

    template <typename TMessage, typename TOnField>
    void DoWalkReflection(TMessage& msg, TOnField& onField) {
        const Descriptor* descr = msg.GetDescriptor();
        for (int i1 = 0; i1 < descr->field_count(); ++i1) {
            const FieldDescriptor* fd = descr->field(i1);
            if (!onField(msg, fd)) {
                continue;
            }

            std::conditional_t<std::is_const_v<TMessage>, TConstField, TMutableField> ff(msg, fd);
            if (ff.IsMessage()) {
                for (size_t i2 = 0; i2 < ff.Size(); ++i2) {
                    if constexpr (std::is_const_v<TMessage>) {
                        WalkReflection(*ff.template Get<Message>(i2), onField);
                    } else {
                        WalkReflection(*ff.MutableMessage(i2), onField);
                    }
                }
            }
        }
    }

    void DoWalkSchema(const Descriptor* descriptor,
                      std::function<bool(const FieldDescriptor*)>& onField,
                      THashSet<const Descriptor*>& visited)
    {
        if (!visited.emplace(descriptor).second) {
            return;
        }
        for (int i1 = 0; i1 < descriptor->field_count(); ++i1) {
            const FieldDescriptor* fd = descriptor->field(i1);
            if (!onField(fd)) {
                continue;
            }

            if (fd->type() == FieldDescriptor::Type::TYPE_MESSAGE) {
                DoWalkSchema(fd->message_type(), onField, visited);
            }
        }
        visited.erase(descriptor);
    }

}

namespace NProtoBuf {
    void WalkReflection(Message& msg,
                        std::function<bool(Message&, const FieldDescriptor*)> onField) 
    {
        DoWalkReflection(msg, onField);
    }

    void WalkReflection(const Message& msg,
                        std::function<bool(const Message&, const FieldDescriptor*)> onField)
    {
        DoWalkReflection(msg, onField);
    }

    void WalkSchema(const Descriptor* descriptor,
                    std::function<bool(const FieldDescriptor*)> onField) 
    {
        THashSet<const Descriptor*> visited;
        DoWalkSchema(descriptor, onField, visited);
    }

} // namespace NProtoBuf