Skip to main content

risingwave_common_estimate_size/collections/
hashset.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashSet;
16use std::hash::Hash;
17
18use super::EstimatedVec;
19use crate::{EstimateSize, KvSize};
20
21#[derive(Default)]
22pub struct EstimatedHashSet<T: EstimateSize> {
23    inner: HashSet<T>,
24    heap_size: KvSize,
25}
26
27impl<T: EstimateSize> EstimateSize for EstimatedHashSet<T> {
28    fn estimated_heap_size(&self) -> usize {
29        // Only counts the elements, not the overhead of the `HashSet` itself.
30        self.heap_size.size()
31    }
32}
33
34impl<T: EstimateSize> EstimatedHashSet<T>
35where
36    T: Eq + Hash,
37{
38    /// Insert into the cache.
39    pub fn insert(&mut self, value: T) -> bool {
40        let heap_size = self.heap_size.add_val(&value);
41        let inserted = self.inner.insert(value);
42        if inserted {
43            self.heap_size.set(heap_size);
44        }
45        inserted
46    }
47
48    /// Delete from the cache.
49    pub fn remove(&mut self, value: &T) -> bool {
50        let removed = self.inner.remove(value);
51        if removed {
52            self.heap_size.sub_val(value);
53        }
54        removed
55    }
56
57    /// Convert an [`EstimatedVec`] to a [`EstimatedHashSet`]. Do not need to recalculate the
58    /// heap size.
59    pub fn from_vec(v: EstimatedVec<T>) -> Self {
60        let heap_size = v.estimated_heap_size();
61        Self {
62            inner: HashSet::from_iter(v),
63            heap_size: KvSize::with_size(heap_size),
64        }
65    }
66}
67
68impl<T: EstimateSize> EstimatedHashSet<T> {
69    pub fn iter(&self) -> impl Iterator<Item = &T> {
70        self.inner.iter()
71    }
72}