use crate::{make_map, make_map_with_root, BytesKey, Map};
use cid::Cid;
use ipld_blockstore::BlockStore;
use ipld_hamt::Error;
use std::error::Error as StdError;
#[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_map(bs))
}
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, ())
}
#[inline]
pub fn has(&self, key: &[u8]) -> Result<bool, Error> {
Ok(self.0.get(key)?.is_some())
}
#[inline]
pub fn delete(&mut self, key: &[u8]) -> Result<(), Error> {
self.0.delete(key)?;
Ok(())
}
pub fn for_each<F>(&self, mut f: F) -> Result<(), Box<dyn StdError>>
where
F: FnMut(&BytesKey) -> Result<(), Box<dyn StdError>>,
{
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)
}
}