compact_set.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // This is based on the following:
  2. //===- llvm/ADT/SmallSet.h - 'Normally small' sets --------------*- C++ -*-===//
  3. //
  4. // The LLVM Compiler Infrastructure
  5. //
  6. // This file is distributed under the University of Illinois Open Source
  7. // License. See LICENSE.TXT for details.
  8. //
  9. //===----------------------------------------------------------------------===//
  10. //
  11. // This file defines the CompactSet class.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #pragma once
  15. #include "compact_vector.h"
  16. #include <cstddef>
  17. #include <iterator>
  18. #include <set>
  19. #include <type_traits>
  20. namespace NYT {
  21. ///////////////////////////////////////////////////////////////////////////////
  22. //! Maintains a set of unique values, optimizing for the case
  23. //! when the set is small (less than N).
  24. /*!
  25. * In this case, the set can be maintained with no mallocs.
  26. * If the set gets large, we expand to using an
  27. * std::set to maintain reasonable lookup times.
  28. *
  29. * Note that any modification of the set may invalidate *all* iterators.
  30. */
  31. template <typename T, size_t N, typename C = std::less<T>, typename A = std::allocator<T>>
  32. class TCompactSet
  33. {
  34. public:
  35. class const_iterator;
  36. using size_type = std::size_t;
  37. using key_type = T;
  38. TCompactSet() = default;
  39. TCompactSet(const A& allocator);
  40. [[nodiscard]] bool empty() const;
  41. size_type size() const;
  42. const T& front() const;
  43. size_type count(const T& v) const;
  44. bool contains(const T& v) const;
  45. std::pair<const_iterator, bool> insert(const T& v);
  46. template <typename TIter>
  47. void insert(TIter i, TIter e);
  48. bool erase(const T& v);
  49. void clear();
  50. const_iterator begin() const;
  51. const_iterator cbegin() const;
  52. const_iterator end() const;
  53. const_iterator cend() const;
  54. private:
  55. // Use a TCompactVector to hold the elements here (even though it will never
  56. // reach its 'large' stage) to avoid calling the default ctors of elements
  57. // we will never use.
  58. TCompactVector<T, N> Vector_;
  59. std::set<T, C, A> Set_;
  60. using TSetConstIterator = typename std::set<T, C, A>::const_iterator;
  61. using TVectorConstIterator = typename TCompactVector<T, N>::const_iterator;
  62. bool is_small() const;
  63. };
  64. ///////////////////////////////////////////////////////////////////////////////
  65. } // namespace NYT
  66. #define COMPACT_SET_INL_H_
  67. #include "compact_set-inl.h"
  68. #undef COMPACT_SET_INL_H_