use cid::Cid;
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_hamt::Error;
use fvm_shared3::HAMT_BIT_WIDTH;
use crate::v11::{make_empty_map, make_map_with_root, BytesKey, Map};
#[derive(Debug)]
pub struct Set<'a, BS>(Map<'a, BS, ()>);
impl<'a, BS: Blockstore> PartialEq for Set<'a, BS> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<'a, BS> Set<'a, BS>
where
BS: Blockstore,
{
pub fn new(bs: &'a BS) -> Self {
Self(make_empty_map(bs, HAMT_BIT_WIDTH))
}
pub fn new_set_with_bitwidth(bs: &'a BS, bitwidth: u32) -> Self {
Self(make_empty_map(bs, bitwidth))
}
pub fn from_root(bs: &'a BS, cid: &Cid) -> Result<Self, Error> {
Ok(Self(make_map_with_root(cid, bs)?))
}
#[inline]
pub fn root(&mut self) -> Result<Cid, Error> {
self.0.flush()
}
#[inline]
pub fn put(&mut self, key: BytesKey) -> Result<(), Error> {
self.0.set(key, ())?;
Ok(())
}
#[inline]
pub fn has(&self, key: &[u8]) -> Result<bool, Error> {
self.0.contains_key(key)
}
#[inline]
pub fn delete(&mut self, key: &[u8]) -> Result<Option<()>, Error> {
match self.0.delete(key)? {
Some(_) => Ok(Some(())),
None => Ok(None),
}
}
pub fn for_each<F>(&self, mut f: F) -> Result<(), Error>
where
F: FnMut(&BytesKey) -> anyhow::Result<()>,
{
self.0.for_each(|s, _: &()| f(s))
}
pub fn collect_keys(&self) -> Result<Vec<BytesKey>, Error> {
let mut ret_keys = Vec::new();
self.for_each(|k| {
ret_keys.push(k.clone());
Ok(())
})?;
Ok(ret_keys)
}
}