blob: 7835cc6523d828494315524d6216b796372e9485 [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Fallible `#![no_std]` hash set [`HashSet<T>`] implemented as a thin
//! `#[inline(always)]` wrapper over [`HashMap<T, ()>`].
#![forbid(unsafe_code)]
use core::mem::{align_of, size_of};
use vx_alloc::alloc::AllocError;
use crate::collections::hash_map::HashMap;
use crate::collections::key::{Key, KeyQuery};
/// Fallible, `#![no_std]` hash set (`std::collections::HashSet<T>` analog).
#[repr(transparent)]
pub struct HashSet<T: Key> {
map: HashMap<T, ()>,
}
const _: () = assert!(size_of::<HashSet<u64>>() == 64);
const _: () = assert!(align_of::<HashSet<u64>>() == 8);
impl<T: Key> HashSet<T> {
/// Construct an empty [`HashSet<T>`] without allocating.
#[inline(always)]
pub const fn new() -> Self {
Self { map: HashMap::new() }
}
/// Construct an empty [`HashSet<T>`] with space reserved for at least
/// `capacity` elements without rehashing.
#[inline(always)]
pub fn try_with_capacity(capacity: usize) -> Result<Self, AllocError> {
Ok(Self { map: HashMap::try_with_capacity(capacity)? })
}
/// Reserve capacity for at least `additional` more elements.
#[inline(always)]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> {
self.map.try_reserve(additional)
}
/// Insert `value` into the set.
///
/// Returns `Ok(true)` if `value` was newly inserted, or `Ok(false)` if an
/// equal element was already present.
#[inline(always)]
pub fn try_insert(&mut self, value: T) -> Result<bool, AllocError> {
Ok(self.map.try_insert(value, ())?.is_none())
}
/// Insert a borrowed element into the set without allocating an
/// intermediate owned key (e.g. `&str` into `HashSet<String>`).
#[inline(always)]
pub fn try_insert_ref<Q: ?Sized + KeyQuery<T>>(
&mut self,
value: &Q,
) -> Result<bool, AllocError> {
Ok(self.map.try_insert_ref(value, ())?.is_none())
}
/// Return `true` if `value` is present in the set.
#[inline(always)]
pub fn contains<Q: ?Sized + KeyQuery<T>>(&self, value: &Q) -> bool {
self.map.contains_key(value)
}
/// Remove `value` from the set, returning `true` if it was present.
#[inline(always)]
pub fn remove<Q: ?Sized + KeyQuery<T>>(&mut self, value: &Q) -> bool {
self.map.remove(value).is_some()
}
/// Remove all elements while retaining the allocated bucket array.
#[inline(always)]
pub fn clear(&mut self) {
self.map.clear();
}
/// Return the number of elements in the set.
#[inline(always)]
pub const fn len(&self) -> usize {
self.map.len()
}
/// Return the current allocated bucket capacity.
#[inline(always)]
pub const fn capacity(&self) -> usize {
self.map.capacity()
}
/// Return `true` if the set contains no elements.
#[inline(always)]
pub const fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
impl<T: Key> Default for HashSet<T> {
#[inline(always)]
fn default() -> Self {
Self::new()
}
}