actors_runtime/util/
set.rs

1// Copyright 2019-2022 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use cid::Cid;
5use fvm_ipld_hamt::Error;
6use fvm_shared::blockstore::Blockstore;
7use fvm_shared::HAMT_BIT_WIDTH;
8
9use crate::{make_empty_map, make_map_with_root, BytesKey, Map};
10
11/// Set is a Hamt with empty values for the purpose of acting as a hash set.
12#[derive(Debug)]
13pub struct Set<'a, BS>(Map<'a, BS, ()>);
14
15impl<'a, BS: Blockstore> PartialEq for Set<'a, BS> {
16    fn eq(&self, other: &Self) -> bool {
17        self.0 == other.0
18    }
19}
20
21impl<'a, BS> Set<'a, BS>
22where
23    BS: Blockstore,
24{
25    /// Initializes a new empty Set with the default bitwidth.
26    pub fn new(bs: &'a BS) -> Self {
27        Self(make_empty_map(bs, HAMT_BIT_WIDTH))
28    }
29
30    /// Initializes a new empty Set given a bitwidth.
31    pub fn new_set_with_bitwidth(bs: &'a BS, bitwidth: u32) -> Self {
32        Self(make_empty_map(bs, bitwidth))
33    }
34
35    /// Initializes a Set from a root Cid.
36    pub fn from_root(bs: &'a BS, cid: &Cid) -> Result<Self, Error> {
37        Ok(Self(make_map_with_root(cid, bs)?))
38    }
39
40    /// Retrieve root from the Set.
41    #[inline]
42    pub fn root(&mut self) -> Result<Cid, Error> {
43        self.0.flush()
44    }
45
46    /// Adds key to the set.
47    #[inline]
48    pub fn put(&mut self, key: BytesKey) -> Result<(), Error> {
49        // Set hamt node to array root
50        self.0.set(key, ())?;
51        Ok(())
52    }
53
54    /// Checks if key exists in the set.
55    #[inline]
56    pub fn has(&self, key: &[u8]) -> Result<bool, Error> {
57        self.0.contains_key(key)
58    }
59
60    /// Deletes key from set.
61    #[inline]
62    pub fn delete(&mut self, key: &[u8]) -> Result<Option<()>, Error> {
63        match self.0.delete(key)? {
64            Some(_) => Ok(Some(())),
65            None => Ok(None),
66        }
67    }
68
69    /// Iterates through all keys in the set.
70    pub fn for_each<F>(&self, mut f: F) -> Result<(), Error>
71    where
72        F: FnMut(&BytesKey) -> anyhow::Result<()>,
73    {
74        // Calls the for each function on the hamt with ignoring the value
75        self.0.for_each(|s, _: &()| f(s))
76    }
77
78    /// Collects all keys from the set into a vector.
79    pub fn collect_keys(&self) -> Result<Vec<BytesKey>, Error> {
80        let mut ret_keys = Vec::new();
81
82        self.for_each(|k| {
83            ret_keys.push(k.clone());
84            Ok(())
85        })?;
86
87        Ok(ret_keys)
88    }
89}