summaryrefslogtreecommitdiff
path: root/src/prefix_tree.cc
blob: 56466e816455fec59228050bfbe25ea7ceb5a3c1 (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#include "prefix_tree.hh"

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <string_view>

namespace prefix_tree {

namespace {

[[nodiscard]]
inline uint8_t get_u8(std::string_view str, size_t index) {
  return static_cast<uint8_t>(str[index] & 0xff);
}

[[nodiscard]]
inline uint16_t get_u16(std::string_view str, size_t index) {
  return (static_cast<uint16_t>(get_u8(str, index)) << 8) |
         get_u8(str, index + 1);
}

inline void write_u8(std::string& str, uint8_t value) {
  str.push_back(static_cast<char>(value));
}

inline void write_u16(std::string& str, uint16_t value) {
  write_u8(str, value >> 8);
  write_u8(str, value & 0xff);
}

class BuilderImpl : public Builder {
 public:
  BuilderImpl() = default;

  void add(std::string_view str) override { strings_.emplace(str); }

  [[nodiscard]]
  std::optional<std::string> build() const override {
    auto ret = build(1);
    if (!ret.has_value())
      ret = build(2);
    return ret;
  }

 private:
  [[nodiscard]]
  std::optional<std::string> build(uint8_t size) const {
    assert(size > 0);

    std::string tree;
    std::string strings;

    std::set<std::string_view> tmp;
    for (auto const& str : strings_)
      tmp.emplace(str);

    if (!write_tree(tmp, tree, strings, size))
      return std::nullopt;

    std::string header;
    write_u8(header, size);
    if (!write_size(header, size, tree.size()))
      return std::nullopt;

    return header + tree + strings;
  }

  bool write_tree(std::set<std::string_view> const& input, std::string& tree,
                  std::string& strings, uint8_t size) const {
    std::map<char, std::set<std::string_view>> buckets;
    bool match = false;
    for (auto& str : input) {
      if (str.empty()) {
        match = true;
        continue;
      }
      buckets[str.front()].emplace(str.substr(1));
    }

    write_u8(tree, buckets.size() + (match ? 1 : 0));
    if (match) {
      write_u8(tree, 0);
      write_size(tree, size, 0);
      write_size(tree, size, 0);
    }
    std::string extra;
    for (auto& pair : buckets) {
      auto it = pair.second.begin();
      auto str = *it;
      for (++it; it != pair.second.end(); ++it) {
        size_t i = 0;
        while (i < str.size() && i < it->size() && str[i] == it->at(i))
          ++i;
        if (i == 0) {
          str = "";
          break;
        }
        str = str.substr(0, i);
      }

      write_u8(tree, 1 + str.size());
      if (!write_size(tree, size, strings.size()))
        return false;
      strings.push_back(pair.first);
      strings.append(str);
      if (extra.size() > 0xffff)
        return false;
      if (!write_size(tree, size, extra.size()))
        return false;
      if (str.empty()) {
        if (!write_tree(pair.second, extra, strings, size))
          return false;
      } else {
        std::set<std::string_view> tmp;
        for (auto& str2 : pair.second) {
          tmp.emplace(str2.substr(str.size()));
        }
        if (!write_tree(tmp, extra, strings, size))
          return false;
      }
    }

    tree.append(extra);
    return true;
  }

  static bool write_size(std::string& str, uint8_t size, size_t value) {
    if (size == 1) {
      if (value > 0xff)
        return false;
      write_u8(str, value);
      return true;
    }
    if (size == 2) {
      if (value > 0xffff)
        return false;
      write_u16(str, value);
      return true;
    }
    assert(false);
    return false;
  }

  std::set<std::string> strings_;
};

std::optional<size_t> lookup16(std::string_view tree, std::string_view str) {
  size_t base_str = 2 + get_u16(tree, 0);
  size_t node = 2;
  std::optional<size_t> match;
  std::optional<size_t> earlier_match;

  while (node < base_str && !str.empty()) {
    auto children = get_u8(tree, node);

    if (children == 0) {
      // Leaf
      return match;
    }

    size_t child_node = node + 1;
    size_t child_end = child_node + (static_cast<size_t>(children) * 5);
    for (; child_node < child_end; child_node += 5) {
      uint8_t len = get_u8(tree, child_node);
      uint16_t offset = get_u16(tree, child_node + 1);

      if (str.starts_with(tree.substr(base_str + offset, len))) {
        // Match but not a leaf, always first in the list of children
        if (len == 0) {
          earlier_match = match;
          continue;
        }
        match = match.value_or(0) + len;
        str = str.substr(len);
        auto jump = get_u16(tree, child_node + 3);
        node = child_end + jump;
        break;
      }
    }

    if (child_node == child_end)
      return earlier_match;
  }

  if (node == base_str)
    return earlier_match;
  return match;
}

std::optional<size_t> lookup8(std::string_view tree, std::string_view str) {
  size_t base_str = 1 + get_u8(tree, 0);
  size_t node = 1;
  std::optional<size_t> match;
  std::optional<size_t> earlier_match;

  while (node < base_str && !str.empty()) {
    auto children = get_u8(tree, node);

    if (children == 0) {
      // Leaf
      return match;
    }

    size_t child_node = node + 1;
    size_t child_end = child_node + (static_cast<size_t>(children) * 3);
    for (; child_node < child_end; child_node += 3) {
      uint8_t len = get_u8(tree, child_node);
      uint8_t offset = get_u8(tree, child_node + 1);

      if (str.starts_with(tree.substr(base_str + offset, len))) {
        // Match but not a leaf, always first in the list of children
        if (len == 0) {
          earlier_match = match;
          continue;
        }
        match = match.value_or(0) + len;
        str = str.substr(len);
        auto jump = get_u8(tree, child_node + 2);
        node = child_end + jump;
        break;
      }
    }

    if (child_node == child_end)
      return earlier_match;
  }

  if (node == base_str)
    return earlier_match;
  return match;
}

}  // namespace

std::optional<size_t> lookup(std::string_view tree, std::string_view str) {
  auto size = get_u8(tree, 0);
  if (size == 1) {
    return lookup8(tree.substr(1), str);
  }
  if (size == 2) {
    return lookup16(tree.substr(1), str);
  }
  assert(false);
  return std::nullopt;
}

std::unique_ptr<Builder> builder() { return std::make_unique<BuilderImpl>(); }

}  // namespace prefix_tree