Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-subscriber/src/bounded_set.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use std::{
5 collections::HashSet,
6 sync::{
7 RwLock,
8 atomic::{AtomicBool, Ordering},
9 },
10 };
11
12 use s2n_tls_metrics_schema::bounded_set::FrozenBoundedStringSet;
13
14 #[derive(Debug)]
15 pub(crate) struct BoundedStringSet {
16 storage: RwLock<HashSet<String>>,
17 overflow: AtomicBool,
18 }
19
20 impl Default for BoundedStringSet {
21 fn default() -> Self {
22 Self {
23 // set capacity to 10 to minimize allocations
24 storage: RwLock::new(HashSet::with_capacity(Self::MAX_STORAGE)),
25 overflow: AtomicBool::new(false),
26 }
27 }
28 }
29
30 impl BoundedStringSet {
31 pub(crate) const MAX_STORAGE: usize = 10;
32 /// record the existence of a value.
33 ///
34 /// This will be a no-op if the item is already in the set
35 pub fn record(&self, item: &str) {
36 let storage = self.storage.read().unwrap();
37 if storage.contains(item) {
38 return;
39 }
40 if storage.len() >= Self::MAX_STORAGE {
41 self.overflow.store(true, Ordering::Relaxed);
42 return;
43 }
44 drop(storage);
45
46 // acquire write lock
47 let mut write_set = self.storage.write().unwrap();
48 if write_set.contains(item) {
49 return;
50 }
51 if write_set.len() >= Self::MAX_STORAGE {
52 self.overflow.store(true, Ordering::Relaxed);
53 return;
54 }
55 write_set.insert(item.to_owned());
56 }
57
58 pub fn freeze(&self) -> FrozenBoundedStringSet {
59 if self.overflow.load(Ordering::Relaxed) {
60 FrozenBoundedStringSet::TooMany
61 } else {
62 let storage = self.storage.read().unwrap();
63 FrozenBoundedStringSet::Entries(storage.iter().cloned().collect())
64 }
65 }
66 }