risingwave_common_estimate_size/collections/
hashset.rs1use 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 self.heap_size.size()
31 }
32}
33
34impl<T: EstimateSize> EstimatedHashSet<T>
35where
36 T: Eq + Hash,
37{
38 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 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 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}