map.h 17.8 KB
Newer Older
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
// Copyright (c) 2018 Kenton Varda and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#pragma once

#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
#pragma GCC system_header
#endif

#include "table.h"
#include "hash.h"

namespace kj {

template <typename Key, typename Value>
class HashMap {
  // A key/value mapping backed by hashing.
  //
  // `Key` must be hashable (via a `.hashCode()` method or `KJ_HASHCODE()`; see `hash.h`) and must
  // implement `operator==()`. Additionally, when performing lookups, you can use key types other
39
  // than `Key` as long as the other type is also hashable (producing the same hash codes) and
40 41 42 43 44 45 46
  // there is an `operator==` implementation with `Key` on the left and that other type on the
  // right. For example, if the key type is `String`, you can pass `StringPtr` to `find()`.

public:
  void reserve(size_t size);
  // Pre-allocates space for a map of the given size.

47 48
  size_t size() const;
  size_t capacity() const;
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
  void clear();

  struct Entry {
    Key key;
    Value value;
  };

  Entry* begin();
  Entry* end();
  const Entry* begin() const;
  const Entry* end() const;
  // Deterministic iteration. If you only ever insert(), iteration order will be insertion order.
  // If you erase(), the erased element is swapped with the last element in the ordering.

  Entry& insert(Key key, Value value);
  // Inserts a new entry. Throws if the key already exists.

  template <typename Collection>
  void insertAll(Collection&& collection);
  // Given an iterable collection of `Entry`s, inserts all of them into this map. If the
  // input is an rvalue, the entries will be moved rather than copied.

  template <typename UpdateFunc>
  Entry& upsert(Key key, Value value, UpdateFunc&& update);
  // Tries to insert a new entry. However, if a duplicate already exists (according to some index),
  // then update(Value& existingValue, Value&& newValue) is called to modify the existing value.

  template <typename KeyLike>
  kj::Maybe<Value&> find(KeyLike&& key);
  template <typename KeyLike>
  kj::Maybe<const Value&> find(KeyLike&& key) const;
  // Search for a matching key. The input does not have to be of type `Key`; it merely has to
  // be something that the Hasher accepts.
  //
  // Note that the default hasher for String accepts StringPtr.

85 86 87 88 89
  template <typename KeyLike, typename Func>
  Value& findOrCreate(KeyLike&& key, Func&& createEntry);
  // Like find() but if the key isn't present then call createEntry() to create the corresponding
  // entry and insert it. createEntry() must return type `Entry`.

90 91 92 93 94 95 96 97
  template <typename KeyLike>
  kj::Maybe<Entry&> findEntry(KeyLike&& key);
  template <typename KeyLike>
  kj::Maybe<const Entry&> findEntry(KeyLike&& key) const;
  template <typename KeyLike, typename Func>
  Entry& findOrCreateEntry(KeyLike&& key, Func&& createEntry);
  // Sometimes you need to see the whole matching Entry, not just the Value.

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  template <typename KeyLike>
  bool erase(KeyLike&& key);
  // Erase the entry with the matching key.
  //
  // WARNING: This invalidates all pointers and interators into the map. Use eraseAll() if you need
  //   to iterate and erase multiple entries.

  void erase(Entry& entry);
  // Erase an entry by reference.

  template <typename Predicate,
      typename = decltype(instance<Predicate>()(instance<Key&>(), instance<Value&>()))>
  size_t eraseAll(Predicate&& predicate);
  // Erase all values for which predicate(key, value) returns true. This scans over the entire map.

private:
  class Callbacks {
  public:
116 117 118
    inline const Key& keyForRow(const Entry& entry) const { return entry.key; }
    inline Key& keyForRow(Entry& entry) const { return entry.key; }

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
    template <typename KeyLike>
    inline bool matches(Entry& e, KeyLike&& key) const {
      return e.key == key;
    }
    template <typename KeyLike>
    inline bool matches(const Entry& e, KeyLike&& key) const {
      return e.key == key;
    }
    template <typename KeyLike>
    inline bool hashCode(KeyLike&& key) const {
      return kj::hashCode(key);
    }
  };

  kj::Table<Entry, HashIndex<Callbacks>> table;
};

template <typename Key, typename Value>
class TreeMap {
  // A key/value mapping backed by a B-tree.
  //
  // `Key` must support `operator<` and `operator==` against other Keys, and against any type
  // which you might want to pass to find() (with `Key` always on the left of the comparison).

public:
  void reserve(size_t size);
  // Pre-allocates space for a map of the given size.

147 148
  size_t size() const;
  size_t capacity() const;
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
  void clear();

  struct Entry {
    Key key;
    Value value;
  };

  auto begin();
  auto end();
  auto begin() const;
  auto end() const;
  // Iteration is in sorted order by key.

  Entry& insert(Key key, Value value);
  // Inserts a new entry. Throws if the key already exists.

  template <typename Collection>
  void insertAll(Collection&& collection);
  // Given an iterable collection of `Entry`s, inserts all of them into this map. If the
  // input is an rvalue, the entries will be moved rather than copied.

  template <typename UpdateFunc>
  Entry& upsert(Key key, Value value, UpdateFunc&& update);
  // Tries to insert a new entry. However, if a duplicate already exists (according to some index),
  // then update(Value& existingValue, Value&& newValue) is called to modify the existing value.

  template <typename KeyLike>
  kj::Maybe<Value&> find(KeyLike&& key);
  template <typename KeyLike>
  kj::Maybe<const Value&> find(KeyLike&& key) const;
  // Search for a matching key. The input does not have to be of type `Key`; it merely has to
180 181 182 183 184 185
  // be something that can be compared against `Key`.

  template <typename KeyLike, typename Func>
  Value& findOrCreate(KeyLike&& key, Func&& createEntry);
  // Like find() but if the key isn't present then call createEntry() to create the corresponding
  // entry and insert it. createEntry() must return type `Entry`.
186

187 188 189 190 191 192 193 194
  template <typename KeyLike>
  kj::Maybe<Entry&> findEntry(KeyLike&& key);
  template <typename KeyLike>
  kj::Maybe<const Entry&> findEntry(KeyLike&& key) const;
  template <typename KeyLike, typename Func>
  Entry& findOrCreateEntry(KeyLike&& key, Func&& createEntry);
  // Sometimes you need to see the whole matching Entry, not just the Value.

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
  template <typename K1, typename K2>
  auto range(K1&& k1, K2&& k2);
  template <typename K1, typename K2>
  auto range(K1&& k1, K2&& k2) const;
  // Returns an iterable range of entries with keys between k1 (inclusive) and k2 (exclusive).

  template <typename KeyLike>
  bool erase(KeyLike&& key);
  // Erase the entry with the matching key.
  //
  // WARNING: This invalidates all pointers and interators into the map. Use eraseAll() if you need
  //   to iterate and erase multiple entries.

  void erase(Entry& entry);
  // Erase an entry by reference.

  template <typename Predicate,
      typename = decltype(instance<Predicate>()(instance<Key&>(), instance<Value&>()))>
  size_t eraseAll(Predicate&& predicate);
  // Erase all values for which predicate(key, value) returns true. This scans over the entire map.

  template <typename K1, typename K2>
  size_t eraseRange(K1&& k1, K2&& k2);
  // Erases all entries with keys between k1 (inclusive) and k2 (exclusive).

private:
  class Callbacks {
  public:
223 224 225
    inline const Key& keyForRow(const Entry& entry) const { return entry.key; }
    inline Key& keyForRow(Entry& entry) const { return entry.key; }

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
    template <typename KeyLike>
    inline bool matches(Entry& e, KeyLike&& key) const {
      return e.key == key;
    }
    template <typename KeyLike>
    inline bool matches(const Entry& e, KeyLike&& key) const {
      return e.key == key;
    }
    template <typename KeyLike>
    inline bool isBefore(Entry& e, KeyLike&& key) const {
      return e.key < key;
    }
    template <typename KeyLike>
    inline bool isBefore(const Entry& e, KeyLike&& key) const {
      return e.key < key;
    }
  };

  kj::Table<Entry, TreeIndex<Callbacks>> table;
};

namespace _ {  // private

class HashSetCallbacks {
public:
251 252 253
  template <typename Row>
  inline Row& keyForRow(Row& row) const { return row; }

254 255 256 257 258 259 260 261 262 263
  template <typename T, typename U>
  inline bool matches(T& a, U& b) const { return a == b; }
  template <typename KeyLike>
  inline bool hashCode(KeyLike&& key) const {
    return kj::hashCode(key);
  }
};

class TreeSetCallbacks {
public:
264 265 266
  template <typename Row>
  inline Row& keyForRow(Row& row) const { return row; }

267 268 269 270 271 272 273 274 275 276 277 278 279 280
  template <typename T, typename U>
  inline bool matches(T& a, U& b) const { return a == b; }
  template <typename T, typename U>
  inline bool isBefore(T& a, U& b) const { return a < b; }
};

}  // namespace _ (private)

template <typename Element>
class HashSet: public Table<Element, HashIndex<_::HashSetCallbacks>> {
  // A simple hashtable-based set, using kj::hashCode() and operator==().

public:
  // Everything is inherited.
281 282 283 284 285

  template <typename... Params>
  inline bool contains(Params&&... params) const {
    return this->find(kj::fwd<Params>(params)...) != nullptr;
  }
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
};

template <typename Element>
class TreeSet: public Table<Element, TreeIndex<_::TreeSetCallbacks>> {
  // A simple b-tree-based set, using operator<() and operator==().

public:
  // Everything is inherited.
};

// =======================================================================================
// inline implementation details

template <typename Key, typename Value>
void HashMap<Key, Value>::reserve(size_t size) {
  table.reserve(size);
}

template <typename Key, typename Value>
305
size_t HashMap<Key, Value>::size() const {
306 307 308
  return table.size();
}
template <typename Key, typename Value>
309
size_t HashMap<Key, Value>::capacity() const {
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
  return table.capacity();
}
template <typename Key, typename Value>
void HashMap<Key, Value>::clear() {
  return table.clear();
}

template <typename Key, typename Value>
typename HashMap<Key, Value>::Entry* HashMap<Key, Value>::begin() {
  return table.begin();
}
template <typename Key, typename Value>
typename HashMap<Key, Value>::Entry* HashMap<Key, Value>::end() {
  return table.end();
}
template <typename Key, typename Value>
const typename HashMap<Key, Value>::Entry* HashMap<Key, Value>::begin() const {
  return table.begin();
}
template <typename Key, typename Value>
const typename HashMap<Key, Value>::Entry* HashMap<Key, Value>::end() const {
  return table.end();
}

template <typename Key, typename Value>
typename HashMap<Key, Value>::Entry& HashMap<Key, Value>::insert(Key key, Value value) {
  return table.insert(Entry { kj::mv(key), kj::mv(value) });
}

template <typename Key, typename Value>
template <typename Collection>
void HashMap<Key, Value>::insertAll(Collection&& collection) {
  return table.insertAll(kj::fwd<Collection>(collection));
}

template <typename Key, typename Value>
template <typename UpdateFunc>
typename HashMap<Key, Value>::Entry& HashMap<Key, Value>::upsert(
    Key key, Value value, UpdateFunc&& update) {
  return table.upsert(Entry { kj::mv(key), kj::mv(value) },
      [&](Entry& existingEntry, Entry&& newEntry) {
    update(existingEntry.value, kj::mv(newEntry.value));
  });
}

template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<Value&> HashMap<Key, Value>::find(KeyLike&& key) {
  return table.find(key).map([](Entry& e) -> Value& { return e.value; });
}
template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<const Value&> HashMap<Key, Value>::find(KeyLike&& key) const {
  return table.find(key).map([](const Entry& e) -> const Value& { return e.value; });
}

366 367 368 369 370 371
template <typename Key, typename Value>
template <typename KeyLike, typename Func>
Value& HashMap<Key, Value>::findOrCreate(KeyLike&& key, Func&& createEntry) {
  return table.findOrCreate(key, kj::fwd<Func>(createEntry)).value;
}

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<typename HashMap<Key, Value>::Entry&>
HashMap<Key, Value>::findEntry(KeyLike&& key) {
  return table.find(kj::fwd<KeyLike>(key));
}
template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<const typename HashMap<Key, Value>::Entry&>
HashMap<Key, Value>::findEntry(KeyLike&& key) const {
  return table.find(kj::fwd<KeyLike>(key));
}
template <typename Key, typename Value>
template <typename KeyLike, typename Func>
typename HashMap<Key, Value>::Entry&
HashMap<Key, Value>::findOrCreateEntry(KeyLike&& key, Func&& createEntry) {
  return table.findOrCreate(kj::fwd<KeyLike>(key), kj::fwd<Func>(createEntry));
}

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
template <typename Key, typename Value>
template <typename KeyLike>
bool HashMap<Key, Value>::erase(KeyLike&& key) {
  return table.eraseMatch(key);
}

template <typename Key, typename Value>
void HashMap<Key, Value>::erase(Entry& entry) {
  table.erase(entry);
}

template <typename Key, typename Value>
template <typename Predicate, typename>
size_t HashMap<Key, Value>::eraseAll(Predicate&& predicate) {
  return table.eraseAll(kj::fwd<Predicate>(predicate));
}

// -----------------------------------------------------------------------------

template <typename Key, typename Value>
void TreeMap<Key, Value>::reserve(size_t size) {
  table.reserve(size);
}

template <typename Key, typename Value>
416
size_t TreeMap<Key, Value>::size() const {
417 418 419
  return table.size();
}
template <typename Key, typename Value>
420
size_t TreeMap<Key, Value>::capacity() const {
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 465 466 467 468 469 470 471 472 473 474 475 476 477
  return table.capacity();
}
template <typename Key, typename Value>
void TreeMap<Key, Value>::clear() {
  return table.clear();
}

template <typename Key, typename Value>
auto TreeMap<Key, Value>::begin() {
  return table.ordered().begin();
}
template <typename Key, typename Value>
auto TreeMap<Key, Value>::end() {
  return table.ordered().end();
}
template <typename Key, typename Value>
auto TreeMap<Key, Value>::begin() const {
  return table.ordered().begin();
}
template <typename Key, typename Value>
auto TreeMap<Key, Value>::end() const {
  return table.ordered().end();
}

template <typename Key, typename Value>
typename TreeMap<Key, Value>::Entry& TreeMap<Key, Value>::insert(Key key, Value value) {
  return table.insert(Entry { kj::mv(key), kj::mv(value) });
}

template <typename Key, typename Value>
template <typename Collection>
void TreeMap<Key, Value>::insertAll(Collection&& collection) {
  return table.insertAll(kj::fwd<Collection>(collection));
}

template <typename Key, typename Value>
template <typename UpdateFunc>
typename TreeMap<Key, Value>::Entry& TreeMap<Key, Value>::upsert(
    Key key, Value value, UpdateFunc&& update) {
  return table.upsert(Entry { kj::mv(key), kj::mv(value) },
      [&](Entry& existingEntry, Entry&& newEntry) {
    update(existingEntry.value, kj::mv(newEntry.value));
  });
}

template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<Value&> TreeMap<Key, Value>::find(KeyLike&& key) {
  return table.find(key).map([](Entry& e) -> Value& { return e.value; });
}
template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<const Value&> TreeMap<Key, Value>::find(KeyLike&& key) const {
  return table.find(key).map([](const Entry& e) -> const Value& { return e.value; });
}

template <typename Key, typename Value>
478 479 480 481 482 483
template <typename KeyLike, typename Func>
Value& TreeMap<Key, Value>::findOrCreate(KeyLike&& key, Func&& createEntry) {
  return table.findOrCreate(key, kj::fwd<Func>(createEntry)).value;
}

template <typename Key, typename Value>
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
template <typename KeyLike>
kj::Maybe<typename TreeMap<Key, Value>::Entry&>
TreeMap<Key, Value>::findEntry(KeyLike&& key) {
  return table.find(kj::fwd<KeyLike>(key));
}
template <typename Key, typename Value>
template <typename KeyLike>
kj::Maybe<const typename TreeMap<Key, Value>::Entry&>
TreeMap<Key, Value>::findEntry(KeyLike&& key) const {
  return table.find(kj::fwd<KeyLike>(key));
}
template <typename Key, typename Value>
template <typename KeyLike, typename Func>
typename TreeMap<Key, Value>::Entry&
TreeMap<Key, Value>::findOrCreateEntry(KeyLike&& key, Func&& createEntry) {
  return table.findOrCreate(kj::fwd<KeyLike>(key), kj::fwd<Func>(createEntry));
}

template <typename Key, typename Value>
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
template <typename K1, typename K2>
auto TreeMap<Key, Value>::range(K1&& k1, K2&& k2) {
  return table.range(kj::fwd<K1>(k1), kj::fwd<K2>(k2));
}
template <typename Key, typename Value>
template <typename K1, typename K2>
auto TreeMap<Key, Value>::range(K1&& k1, K2&& k2) const {
  return table.range(kj::fwd<K1>(k1), kj::fwd<K2>(k2));
}

template <typename Key, typename Value>
template <typename KeyLike>
bool TreeMap<Key, Value>::erase(KeyLike&& key) {
  return table.eraseMatch(key);
}

template <typename Key, typename Value>
void TreeMap<Key, Value>::erase(Entry& entry) {
  table.erase(entry);
}

template <typename Key, typename Value>
template <typename Predicate, typename>
size_t TreeMap<Key, Value>::eraseAll(Predicate&& predicate) {
  return table.eraseAll(kj::fwd<Predicate>(predicate));
}

template <typename Key, typename Value>
template <typename K1, typename K2>
size_t TreeMap<Key, Value>::eraseRange(K1&& k1, K2&& k2) {
  return table.eraseRange(kj::fwd<K1>(k1), kj::fwd<K2>(k2));
}

} // namespace kj