entropy_map/set.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
//! A module providing `Set`, an immutable set implementation backed by a MPHF.
//!
//! This implementation is optimized for efficient membership checks by using a MPHF to evaluate
//! whether an item is in the set. Keys are stored in the map to ensure that queries for an item
//! not in the set always fail.
//!
//! # When to use?
//! Use this set implementation when you have a pre-defined set of keys and you want to check for
//! efficient membership in that set. Because this set is immutable, it is not possible to
//! dynamically update membership. However, when the `rkyv_derive` feature is enabled, you can use
//! [`rkyv`](https://rkyv.org/) to perform zero-copy deserialization of a new set.
use std::borrow::Borrow;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::mem::size_of_val;
use num::{PrimInt, Unsigned};
use wyhash::WyHash;
use crate::mphf::{Mphf, MphfError, DEFAULT_GAMMA};
/// An efficient, immutable set.
#[cfg_attr(feature = "rkyv_derive", derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize))]
#[cfg_attr(feature = "rkyv_derive", archive_attr(derive(rkyv::CheckBytes)))]
pub struct Set<K, const B: usize = 32, const S: usize = 8, ST = u8, H = WyHash>
where
ST: PrimInt + Unsigned,
H: Hasher + Default,
{
/// Minimally Perfect Hash Function for keys indices retrieval
mphf: Mphf<B, S, ST, H>,
/// Set keys
keys: Box<[K]>,
}
impl<K, const B: usize, const S: usize, ST, H> Set<K, B, S, ST, H>
where
K: Eq + Hash,
ST: PrimInt + Unsigned,
H: Hasher + Default,
{
/// Constructs a `Set` from an iterator of keys and MPHF function parameters.
///
/// # Examples
/// ```
/// use entropy_map::{Set, DEFAULT_GAMMA};
///
/// let set: Set<u32> = Set::from_iter_with_params([1, 2, 3], DEFAULT_GAMMA).unwrap();
/// assert!(set.contains(&1));
/// ```
pub fn from_iter_with_params<I>(iter: I, gamma: f32) -> Result<Self, MphfError>
where
I: IntoIterator<Item = K>,
{
let mut keys: Vec<K> = iter.into_iter().collect();
let mphf = Mphf::from_slice(&keys, gamma)?;
// Re-order `keys` and according to `mphf`
for i in 0..keys.len() {
loop {
let idx: usize = mphf.get(&keys[i]).unwrap();
if idx == i {
break;
}
keys.swap(i, idx);
}
}
Ok(Set { mphf, keys: keys.into_boxed_slice() })
}
/// Returns `true` if the set contains the value.
///
/// # Examples
/// ```
/// # use std::collections::HashSet;
/// # use entropy_map::Set;
/// let set = Set::try_from(HashSet::from([1, 2, 3])).unwrap();
/// assert_eq!(set.contains(&1), true);
/// assert_eq!(set.contains(&4), false);
/// ```
#[inline]
pub fn contains<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q> + PartialEq<Q>,
Q: Hash + Eq + ?Sized,
{
// SAFETY: `idx` is always within array bounds (ensured during construction)
self.mphf
.get(key)
.map(|idx| unsafe { self.keys.get_unchecked(idx) == key })
.unwrap_or_default()
}
/// Returns the number of elements in the set.
///
/// # Examples
/// ```
/// # use std::collections::HashSet;
/// # use entropy_map::Set;
/// let set = Set::try_from(HashSet::from([1, 2, 3])).unwrap();
/// assert_eq!(set.len(), 3);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.keys.len()
}
/// Returns `true` if the set contains no elements.
///
/// # Examples
/// ```
/// # use std::collections::HashSet;
/// # use entropy_map::Set;
/// let set = Set::try_from(HashSet::from([0u32; 0])).unwrap();
/// assert_eq!(set.is_empty(), true);
/// let set = Set::try_from(HashSet::from([1, 2, 3])).unwrap();
/// assert_eq!(set.is_empty(), false);
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
/// Returns an iterator visiting set elements in arbitrary order.
///
/// # Examples
/// ```
/// # use std::collections::HashSet;
/// # use entropy_map::Set;
/// let set = Set::try_from(HashSet::from([1, 2, 3])).unwrap();
/// for x in set.iter() {
/// println!("{x}");
/// }
/// ```
#[inline]
pub fn iter(&self) -> impl Iterator<Item = &K> {
self.keys.iter()
}
/// Returns the total number of bytes occupied by `Set`.
///
/// # Examples
/// ```
/// # use std::collections::HashSet;
/// # use entropy_map::Set;
/// let set = Set::try_from(HashSet::from([1, 2, 3])).unwrap();
/// assert_eq!(set.size(), 218);
/// ```
#[inline]
pub fn size(&self) -> usize {
size_of_val(self) + self.mphf.size() + size_of_val(self.keys.as_ref())
}
}
/// Creates a `Set` from a `HashSet`.
impl<K> TryFrom<HashSet<K>> for Set<K>
where
K: Eq + Hash,
{
type Error = MphfError;
#[inline]
fn try_from(value: HashSet<K>) -> Result<Self, Self::Error> {
Set::from_iter_with_params(value, DEFAULT_GAMMA)
}
}
/// Implement `contains` for `Archived` version of `Set` if feature is enabled
#[cfg(feature = "rkyv_derive")]
impl<K, const B: usize, const S: usize, ST, H> ArchivedSet<K, B, S, ST, H>
where
K: Eq + Hash + rkyv::Archive,
K::Archived: PartialEq<K>,
ST: PrimInt + Unsigned + rkyv::Archive<Archived = ST>,
H: Hasher + Default,
{
/// Returns `true` if the set contains the value.
///
/// # Examples
/// ```
/// # use std::collections::HashSet;
/// # use entropy_map::{ArchivedSet, Set};
/// let set: Set<u32> = Set::try_from(HashSet::from([1, 2, 3])).unwrap();
/// let archived_set = rkyv::from_bytes::<Set<u32>>(
/// &rkyv::to_bytes::<_, 1024>(&set).unwrap()
/// ).unwrap();
/// assert_eq!(archived_set.contains(&1), true);
/// assert_eq!(archived_set.contains(&4), false);
/// ```
#[inline]
pub fn contains<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
<K as rkyv::Archive>::Archived: PartialEq<Q>,
Q: Hash + Eq,
{
// SAFETY: `idx` is always within bounds (ensured during construction)
self.mphf
.get(key)
.map(|idx| unsafe { self.keys.get_unchecked(idx) == key })
.unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use paste::paste;
use proptest::prelude::*;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
fn gen_set(items_num: usize) -> HashSet<u64> {
let mut rng = ChaCha8Rng::seed_from_u64(123);
(0..items_num).map(|_| rng.gen::<u64>()).collect()
}
#[test]
fn test_set_with_hashset() {
// Collect original key-value pairs directly into a HashSet
let original_set = gen_set(1000);
// Create the set from the iterator
let set = Set::try_from(original_set.clone()).unwrap();
// Test len
assert_eq!(set.len(), original_set.len());
// Test is_empty
assert_eq!(set.is_empty(), original_set.is_empty());
// Test get, contains_key
for key in &original_set {
assert!(set.contains(key));
}
// Test iter
for &k in set.iter() {
assert!(original_set.contains(&k));
}
// Test size
assert_eq!(set.size(), 8540);
}
/// Assert that we can call `.contains()` with `K::borrow()`.
#[test]
fn test_contains_borrow() {
let set = Set::try_from(HashSet::from(["a".to_string(), "b".to_string()])).unwrap();
assert!(set.contains("a"));
assert!(set.contains("b"));
assert!(!set.contains("c"));
}
#[cfg(feature = "rkyv_derive")]
#[test]
fn test_rkyv() {
// create regular `HashSet`, then `Set`, then serialize to `rkyv` bytes.
let original_set = gen_set(1000);
let set = Set::try_from(original_set.clone()).unwrap();
let rkyv_bytes = rkyv::to_bytes::<_, 1024>(&set).unwrap();
assert_eq!(rkyv_bytes.len(), 8408);
let rkyv_set = rkyv::check_archived_root::<Set<u64>>(&rkyv_bytes).unwrap();
// Test get on `Archived` version
for k in original_set.iter() {
assert!(rkyv_set.contains(k));
}
}
#[cfg(feature = "rkyv_derive")]
#[test]
fn test_rkyv_contains_borrow() {
let set = Set::try_from(HashSet::from(["a".to_string(), "b".to_string()])).unwrap();
let rkyv_bytes = rkyv::to_bytes::<_, 1024>(&set).unwrap();
let rkyv_set = rkyv::check_archived_root::<Set<String>>(&rkyv_bytes).unwrap();
assert!(rkyv_set.contains("a"));
assert!(rkyv_set.contains("b"));
assert!(!rkyv_set.contains("c"));
}
macro_rules! proptest_set_model {
($(($b:expr, $s:expr, $gamma:expr)),* $(,)?) => {
$(
paste! {
proptest! {
#[test]
fn [<proptest_set_model_ $b _ $s _ $gamma>](model: HashSet<u64>, arbitrary: HashSet<u64>) {
let entropy_set: Set<u64, $b, $s> = Set::from_iter_with_params(
model.clone(),
$gamma as f32 / 100.0
).unwrap();
// Assert that length matches model.
assert_eq!(entropy_set.len(), model.len());
assert_eq!(entropy_set.is_empty(), model.is_empty());
// Assert that contains operations match model for contained elements.
for elm in &model {
assert!(entropy_set.contains(&elm));
}
// Assert that contains operations match model for random elements.
for elm in arbitrary {
assert_eq!(
model.contains(&elm),
entropy_set.contains(&elm),
);
}
}
}
}
)*
};
}
proptest_set_model!(
// (1, 8, 100),
(2, 8, 100),
(4, 8, 100),
(7, 8, 100),
(8, 8, 100),
(15, 8, 100),
(16, 8, 100),
(23, 8, 100),
(24, 8, 100),
(31, 8, 100),
(32, 8, 100),
(33, 8, 100),
(48, 8, 100),
(53, 8, 100),
(61, 8, 100),
(63, 8, 100),
(64, 8, 100),
(32, 7, 100),
(32, 5, 100),
(32, 4, 100),
(32, 3, 100),
(32, 1, 100),
(32, 0, 100),
(32, 8, 200),
(32, 6, 200),
);
proptest! {
#[test]
fn test_set_contains(model: HashSet<u64>, arbitrary: HashSet<u64>) {
let entropy_set = Set::try_from(model.clone()).unwrap();
for elm in &model {
assert!(entropy_set.contains(&elm));
}
for elm in arbitrary {
assert_eq!(
model.contains(&elm),
entropy_set.contains(&elm),
);
}
}
}
}