aboutsummaryrefslogtreecommitdiff
path: root/src/core/lib/gprpp/map.h
blob: 566691df5809c3253cc0e53788e319f9f6d1b131 (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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/*
 *
 * Copyright 2017 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#ifndef GRPC_CORE_LIB_GPRPP_MAP_H
#define GRPC_CORE_LIB_GPRPP_MAP_H

#include <grpc/support/port_platform.h>

#include <string.h>

#include <algorithm>
#include <functional>
#include <iterator>

#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/pair.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"

namespace grpc_core {
struct StringLess {
  bool operator()(const char* a, const char* b) const {
    return strcmp(a, b) < 0;
  }
  bool operator()(const UniquePtr<char>& k1, const UniquePtr<char>& k2) {
    return strcmp(k1.get(), k2.get()) < 0;
  }
};

template <typename T>
struct RefCountedPtrLess {
  bool operator()(const RefCountedPtr<T>& p1, const RefCountedPtr<T>& p2) {
    return p1.get() < p2.get();
  }
};

namespace testing {
class MapTest;
}

// Alternative map implementation for grpc_core
template <class Key, class T, class Compare = std::less<Key>>
class Map {
 public:
  typedef Key key_type;
  typedef T mapped_type;
  typedef Pair<key_type, mapped_type> value_type;
  typedef Compare key_compare;
  class iterator;

  Map() {}
  ~Map() { clear(); }

  // Copying not currently supported.
  Map(const Map& other) = delete;

  // Move support.
  Map(Map&& other) : root_(other.root_), size_(other.size_) {
    other.root_ = nullptr;
    other.size_ = 0;
  }
  Map& operator=(Map&& other) {
    if (this != &other) {
      clear();
      root_ = other.root_;
      size_ = other.size_;
      other.root_ = nullptr;
      other.size_ = 0;
    }
    return *this;
  }

  T& operator[](key_type&& key);
  T& operator[](const key_type& key);
  iterator find(const key_type& k);
  size_t erase(const key_type& key);
  // Removes the current entry and points to the next one
  iterator erase(iterator iter);

  size_t size() { return size_; }

  template <class... Args>
  Pair<iterator, bool> emplace(Args&&... args);

  Pair<iterator, bool> insert(value_type&& pair) {
    return emplace(std::move(pair));
  }

  Pair<iterator, bool> insert(const value_type& pair) { return emplace(pair); }

  bool empty() const { return root_ == nullptr; }

  void clear() {
    auto iter = begin();
    while (!empty()) {
      iter = erase(iter);
    }
  }

  iterator begin() {
    Entry* curr = GetMinEntry(root_);
    return iterator(this, curr);
  }

  iterator end() { return iterator(this, nullptr); }

  iterator lower_bound(const Key& k) {
    key_compare compare;
    return std::find_if(begin(), end(), [&k, &compare](const value_type& v) {
      return !compare(v.first, k);
    });
  }

 private:
  friend class testing::MapTest;
  struct Entry {
    explicit Entry(value_type&& pair) : pair(std::move(pair)) {}
    value_type pair;
    Entry* left = nullptr;
    Entry* right = nullptr;
    int32_t height = 1;
  };

  static int32_t EntryHeight(const Entry* e) {
    return e == nullptr ? 0 : e->height;
  }

  static Entry* GetMinEntry(Entry* e);
  Entry* InOrderSuccessor(const Entry* e) const;
  static Entry* RotateLeft(Entry* e);
  static Entry* RotateRight(Entry* e);
  static Entry* RebalanceTreeAfterInsertion(Entry* root, const key_type& k);
  static Entry* RebalanceTreeAfterDeletion(Entry* root);
  // Returns a pair with the first value being an iterator pointing to the
  // inserted entry and the second value being the new root of the subtree
  // after a rebalance
  Pair<iterator, Entry*> InsertRecursive(Entry* root, value_type&& p);
  // Returns a pair with the first value being an iterator pointing to the
  // successor of the deleted entry and the second value being the new root of
  // the subtree after a rebalance
  Pair<iterator, Entry*> RemoveRecursive(Entry* root, const key_type& k);
  // Return 0 if lhs = rhs
  //        1 if lhs > rhs
  //       -1 if lhs < rhs
  static int CompareKeys(const Key& lhs, const Key& rhs);

  Entry* root_ = nullptr;
  size_t size_ = 0;
};

template <class Key, class T, class Compare>
class Map<Key, T, Compare>::iterator
    : public std::iterator<std::input_iterator_tag, Pair<Key, T>, int32_t,
                           Pair<Key, T>*, Pair<Key, T>&> {
 public:
  iterator(const iterator& iter) : curr_(iter.curr_), map_(iter.map_) {}
  bool operator==(const iterator& rhs) const { return (curr_ == rhs.curr_); }
  bool operator!=(const iterator& rhs) const { return (curr_ != rhs.curr_); }

  iterator& operator++() {
    curr_ = map_->InOrderSuccessor(curr_);
    return *this;
  }

  iterator operator++(int) {
    Entry* prev = curr_;
    curr_ = map_->InOrderSuccessor(curr_);
    return iterator(map_, prev);
  }

  iterator& operator=(const iterator& other) {
    if (this != &other) {
      this->curr_ = other.curr_;
      this->map_ = other.map_;
    }
    return *this;
  }

  // operator*()
  value_type& operator*() { return curr_->pair; }
  const value_type& operator*() const { return curr_->pair; }

  // operator->()
  value_type* operator->() { return &curr_->pair; }
  value_type const* operator->() const { return &curr_->pair; }

 private:
  friend class Map<key_type, mapped_type, key_compare>;
  using GrpcMap = typename ::grpc_core::Map<Key, T, Compare>;
  iterator(GrpcMap* map, Entry* curr) : curr_(curr), map_(map) {}
  Entry* curr_;
  GrpcMap* map_;
};

template <class Key, class T, class Compare>
T& Map<Key, T, Compare>::operator[](key_type&& key) {
  auto iter = find(key);
  if (iter == end()) {
    return emplace(std::move(key), T()).first->second;
  }
  return iter->second;
}

template <class Key, class T, class Compare>
T& Map<Key, T, Compare>::operator[](const key_type& key) {
  auto iter = find(key);
  if (iter == end()) {
    return emplace(key, T()).first->second;
  }
  return iter->second;
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::iterator Map<Key, T, Compare>::find(
    const key_type& k) {
  Entry* iter = root_;
  while (iter != nullptr) {
    int comp = CompareKeys(iter->pair.first, k);
    if (comp == 0) {
      return iterator(this, iter);
    } else if (comp < 0) {
      iter = iter->right;
    } else {
      iter = iter->left;
    }
  }
  return end();
}

template <class Key, class T, class Compare>
template <class... Args>
typename ::grpc_core::Pair<typename Map<Key, T, Compare>::iterator, bool>
Map<Key, T, Compare>::emplace(Args&&... args) {
  Pair<key_type, mapped_type> pair(std::forward<Args>(args)...);
  iterator ret = find(pair.first);
  bool insertion = false;
  if (ret == end()) {
    Pair<iterator, Entry*> p = InsertRecursive(root_, std::move(pair));
    root_ = p.second;
    ret = p.first;
    insertion = true;
    size_++;
  }
  return MakePair(ret, insertion);
}

template <class Key, class T, class Compare>
size_t Map<Key, T, Compare>::erase(const key_type& key) {
  iterator it = find(key);
  if (it == end()) return 0;
  erase(it);
  return 1;
}

// TODO(mhaidry): Modify erase to use the iterator location
// to create an efficient erase method
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::iterator Map<Key, T, Compare>::erase(
    iterator iter) {
  if (iter == end()) return iter;
  key_type& del_key = iter->first;
  Pair<iterator, Entry*> ret = RemoveRecursive(root_, del_key);
  root_ = ret.second;
  size_--;
  return ret.first;
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::InOrderSuccessor(
    const Entry* e) const {
  if (e->right != nullptr) {
    return GetMinEntry(e->right);
  }
  Entry* successor = nullptr;
  Entry* iter = root_;
  while (iter != nullptr) {
    int comp = CompareKeys(iter->pair.first, e->pair.first);
    if (comp > 0) {
      successor = iter;
      iter = iter->left;
    } else if (comp < 0) {
      iter = iter->right;
    } else
      break;
  }
  return successor;
}

// Returns a pair with the first value being an iterator pointing to the
// inserted entry and the second value being the new root of the subtree
// after a rebalance
template <class Key, class T, class Compare>
typename ::grpc_core::Pair<typename Map<Key, T, Compare>::iterator,
                           typename Map<Key, T, Compare>::Entry*>
Map<Key, T, Compare>::InsertRecursive(Entry* root, value_type&& p) {
  if (root == nullptr) {
    Entry* e = New<Entry>(std::move(p));
    return MakePair(iterator(this, e), e);
  }
  int comp = CompareKeys(root->pair.first, p.first);
  if (comp > 0) {
    Pair<iterator, Entry*> ret = InsertRecursive(root->left, std::move(p));
    root->left = ret.second;
    ret.second = RebalanceTreeAfterInsertion(root, ret.first->first);
    return ret;
  } else if (comp < 0) {
    Pair<iterator, Entry*> ret = InsertRecursive(root->right, std::move(p));
    root->right = ret.second;
    ret.second = RebalanceTreeAfterInsertion(root, ret.first->first);
    return ret;
  } else {
    root->pair = std::move(p);
    return MakePair(iterator(this, root), root);
  }
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::GetMinEntry(
    Entry* e) {
  if (e != nullptr) {
    while (e->left != nullptr) {
      e = e->left;
    }
  }
  return e;
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::RotateLeft(
    Entry* e) {
  Entry* rightChild = e->right;
  Entry* rightLeftChild = rightChild->left;
  rightChild->left = e;
  e->right = rightLeftChild;
  e->height = 1 + GPR_MAX(EntryHeight(e->left), EntryHeight(e->right));
  rightChild->height = 1 + GPR_MAX(EntryHeight(rightChild->left),
                                   EntryHeight(rightChild->right));
  return rightChild;
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::RotateRight(
    Entry* e) {
  Entry* leftChild = e->left;
  Entry* leftRightChild = leftChild->right;
  leftChild->right = e;
  e->left = leftRightChild;
  e->height = 1 + GPR_MAX(EntryHeight(e->left), EntryHeight(e->right));
  leftChild->height =
      1 + GPR_MAX(EntryHeight(leftChild->left), EntryHeight(leftChild->right));
  return leftChild;
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry*
Map<Key, T, Compare>::RebalanceTreeAfterInsertion(Entry* root,
                                                  const key_type& k) {
  root->height = 1 + GPR_MAX(EntryHeight(root->left), EntryHeight(root->right));
  int32_t heightDifference = EntryHeight(root->left) - EntryHeight(root->right);
  if (heightDifference > 1 && CompareKeys(root->left->pair.first, k) > 0) {
    return RotateRight(root);
  }
  if (heightDifference < -1 && CompareKeys(root->right->pair.first, k) < 0) {
    return RotateLeft(root);
  }
  if (heightDifference > 1 && CompareKeys(root->left->pair.first, k) < 0) {
    root->left = RotateLeft(root->left);
    return RotateRight(root);
  }
  if (heightDifference < -1 && CompareKeys(root->right->pair.first, k) > 0) {
    root->right = RotateRight(root->right);
    return RotateLeft(root);
  }
  return root;
}

template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry*
Map<Key, T, Compare>::RebalanceTreeAfterDeletion(Entry* root) {
  root->height = 1 + GPR_MAX(EntryHeight(root->left), EntryHeight(root->right));
  int32_t heightDifference = EntryHeight(root->left) - EntryHeight(root->right);
  if (heightDifference > 1) {
    int leftHeightDifference =
        EntryHeight(root->left->left) - EntryHeight(root->left->right);
    if (leftHeightDifference < 0) {
      root->left = RotateLeft(root->left);
    }
    return RotateRight(root);
  }
  if (heightDifference < -1) {
    int rightHeightDifference =
        EntryHeight(root->right->left) - EntryHeight(root->right->right);
    if (rightHeightDifference > 0) {
      root->right = RotateRight(root->right);
    }
    return RotateLeft(root);
  }
  return root;
}

template <class Key, class T, class Compare>
typename ::grpc_core::Pair<typename Map<Key, T, Compare>::iterator,
                           typename Map<Key, T, Compare>::Entry*>
Map<Key, T, Compare>::RemoveRecursive(Entry* root, const key_type& k) {
  Pair<iterator, Entry*> ret = MakePair(end(), root);
  if (root == nullptr) return ret;
  int comp = CompareKeys(root->pair.first, k);
  if (comp > 0) {
    ret = RemoveRecursive(root->left, k);
    root->left = ret.second;
  } else if (comp < 0) {
    ret = RemoveRecursive(root->right, k);
    root->right = ret.second;
  } else {
    Entry* entry;
    Entry* successor = InOrderSuccessor(root);
    if (root->left == nullptr) {
      entry = root->right;
      Delete(root);
      return MakePair(iterator(this, successor), entry);
    } else if (root->right == nullptr) {
      entry = root->left;
      Delete(root);
      return MakePair(iterator(this, successor), entry);
    } else {
      entry = successor;
      root->pair.swap(entry->pair);
      ret = RemoveRecursive(root->right, entry->pair.first);
      root->right = ret.second;
      ret.first = iterator(this, root);
    }
  }
  return MakePair(ret.first, RebalanceTreeAfterDeletion(root));
}

template <class Key, class T, class Compare>
int Map<Key, T, Compare>::CompareKeys(const key_type& lhs,
                                      const key_type& rhs) {
  key_compare compare;
  bool left_comparison = compare(lhs, rhs);
  bool right_comparison = compare(rhs, lhs);
  // Both values are equal
  if (!left_comparison && !right_comparison) {
    return 0;
  }
  return left_comparison ? -1 : 1;
}
}  // namespace grpc_core
#endif /* GRPC_CORE_LIB_GPRPP_MAP_H */