trie.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef THIRD_PARTY_LIBADDRESSINPUT_CHROMIUM_TRIE_H_
  5. #define THIRD_PARTY_LIBADDRESSINPUT_CHROMIUM_TRIE_H_
  6. #include <stdint.h>
  7. #include <map>
  8. #include <set>
  9. #include <vector>
  10. namespace autofill {
  11. // A prefix search tree. Can return all objects whose keys start with a prefix
  12. // byte sequence.
  13. //
  14. // Maps keys to multiple objects. This property is useful when mapping region
  15. // names to region objects. For example, there's a "St. Petersburg" in Florida,
  16. // and there's a "St. Petersburg" in Russia. A lookup for "St. Petersburg" key
  17. // should return two distinct objects.
  18. template <typename T>
  19. class Trie {
  20. public:
  21. Trie();
  22. ~Trie();
  23. // Returns true if no data was added in AddDataForKey().
  24. bool empty() const { return data_list_.empty() && sub_nodes_.empty(); }
  25. // Adds a mapping from the 0 terminated |key| to |data_item|. Can be called
  26. // with the same |key| multiple times.
  27. void AddDataForKey(const std::vector<uint8_t>& key, const T& data_item);
  28. // Adds all objects whose keys start with the 0 terminated |key_prefix| to the
  29. // |results| parameter. The |results| parameter should not be NULL.
  30. void FindDataForKeyPrefix(const std::vector<uint8_t>& key_prefix,
  31. std::set<T>* results) const;
  32. private:
  33. // All objects for this node in the Trie. This field is a collection to enable
  34. // mapping the same key to multiple objects.
  35. std::set<T> data_list_;
  36. // Trie sub nodes. The root Trie stores the objects for the empty key. The
  37. // children of the root Trie store the objects for the one-byte keys. The
  38. // grand-children of the root Trie store the objects for the two-byte keys,
  39. // and so on.
  40. std::map<uint8_t, Trie<T> > sub_nodes_;
  41. };
  42. } // namespace autofill
  43. #endif // THIRD_PARTY_LIBADDRESSINPUT_CHROMIUM_TRIE_H_