diff options
author | Yuri Gorshenin <y@maps.me> | 2017-02-08 16:50:50 +0300 |
---|---|---|
committer | Yuri Gorshenin <y@maps.me> | 2017-02-08 16:50:50 +0300 |
commit | 41c18b845c5379a3c8f5ecdfeea7dc05fde7dcf4 (patch) | |
tree | ecc4908507bb7b2eba8eab3dc2a3b32cba30fa33 /base | |
parent | acb0e55ebb6a21ad8a570f27d407a05a949fe6d9 (diff) |
[base] Implemented SafeSmallSet.
Diffstat (limited to 'base')
-rw-r--r-- | base/small_set.hpp | 53 |
1 files changed, 52 insertions, 1 deletions
diff --git a/base/small_set.hpp b/base/small_set.hpp index 35c7afe7a1..1e1995d38a 100644 --- a/base/small_set.hpp +++ b/base/small_set.hpp @@ -154,7 +154,7 @@ uint64_t constexpr SmallSet<UpperBound>::kNumBlocks; template <uint64_t UpperBound> uint64_t constexpr SmallSet<UpperBound>::kOne; -template<uint64_t UpperBound> +template <uint64_t UpperBound> std::string DebugPrint(SmallSet<UpperBound> const & set) { std::ostringstream os; @@ -164,4 +164,55 @@ std::string DebugPrint(SmallSet<UpperBound> const & set) os << "]"; return os.str(); } + +// This is a delegate for SmallSet<>, that checks the validity of +// argument in Insert(), Remove() and Contains() methods and does +// nothing when the argument is not valid. +template <uint64_t UpperBound> +class SafeSmallSet +{ +public: + using Set = SmallSet<UpperBound>; + using Iterator = typename Set::Iterator; + + void Insert(uint64_t value) + { + if (IsValid(value)) + m_set.Insert(value); + } + + void Remove(uint64_t value) + { + if (IsValid(value)) + m_set.Remove(value); + } + + bool Contains(uint64_t value) const { return IsValid(value) && m_set.Contains(value); } + + uint64_t Size() const { return m_set.Size(); } + + void Clear() { m_set.Clear(); } + + Iterator begin() const { return m_set.begin(); } + Iterator cbegin() const { return m_set.cbegin(); } + + Iterator end() const { return m_set.end(); } + Iterator cend() const { return m_set.cend(); } + +private: + bool IsValid(uint64_t value) const { return value < UpperBound; } + + Set m_set; +}; + +template <uint64_t UpperBound> +std::string DebugPrint(SafeSmallSet<UpperBound> const & set) +{ + std::ostringstream os; + os << "SafeSmallSet<" << UpperBound << "> [" << set.Size() << ": "; + for (auto const & v : set) + os << v << " "; + os << "]"; + return os.str(); +} } // namespace base |