From 99a4f5aa3791b3c65e26802861e1e786b84da276 Mon Sep 17 00:00:00 2001 From: Dmitry Ilvokhin Date: Mon, 29 Jul 2024 07:01:31 -0700 Subject: [PATCH] Add `SparseByteSet::size()` method Summary: Useful, when `SparseByteSet` used as fast pre check for heavyweight operation. Reviewed By: marksantaniello Differential Revision: D60285173 fbshipit-source-id: 8deac984b0f00096448af51fdfee283d0bb13ca2 --- folly/container/SparseByteSet.h | 7 +++++++ folly/container/test/SparseByteSetTest.cpp | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/folly/container/SparseByteSet.h b/folly/container/SparseByteSet.h index 6836110901f..7c5c3e7b0ec 100644 --- a/folly/container/SparseByteSet.h +++ b/folly/container/SparseByteSet.h @@ -106,6 +106,13 @@ class SparseByteSet { */ inline void clear() { size_ = 0; } + /*** + * size() + * + * O(1), non-amortized. + */ + inline uint16_t size() { return size_; } + private: uint16_t size_; // can't use uint8_t because it would overflow if all // possible values were inserted. diff --git a/folly/container/test/SparseByteSetTest.cpp b/folly/container/test/SparseByteSetTest.cpp index 6ec5d23dcbc..e2aa34f16ab 100644 --- a/folly/container/test/SparseByteSetTest.cpp +++ b/folly/container/test/SparseByteSetTest.cpp @@ -103,3 +103,15 @@ TEST_F(SparseByteSetTest, remove_nop) { bool r = s.remove(12); EXPECT_FALSE(r); } + +TEST_F(SparseByteSetTest, size) { + EXPECT_EQ(s.size(), 0); + + s.add(1); + s.add(2); + s.add(3); + EXPECT_EQ(s.size(), 3); + + s.remove(1); + EXPECT_EQ(s.size(), 2); +}