Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Add a fallible-allocation-only `HashSet` to `wasmtime_environ::collections` (#12507)

Nick Fitzgerald6c76af85f35d
diff --git a/Cargo.lock b/Cargo.lock
index 59369c9a8e..a27e9dd5e0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4708,6 +4708,7 @@ dependencies = [
"cranelift-entity",
"env_logger 0.11.5",
"gimli 0.33.0",
+ "hashbrown 0.15.2",
"indexmap 2.11.4",
"log",
"object 0.37.3",
diff --git a/crates/environ/Cargo.toml b/crates/environ/Cargo.toml
index daffb47cd5..07d8ef5709 100644
--- a/crates/environ/Cargo.toml
+++ b/crates/environ/Cargo.toml
@@ -23,6 +23,7 @@ postcard = { workspace = true }
cpp_demangle = { version = "0.4.3", optional = true }
cranelift-entity = { workspace = true, features = ['enable-serde'] }
cranelift-bitset = { workspace = true, features = ['enable-serde'] }
+hashbrown = { workspace = true, features = ["default-hasher"] }
wasmparser = { workspace = true, features = ['validate', 'serde', 'features'] }
indexmap = { workspace = true, features = ["serde"] }
serde = { workspace = true }
diff --git a/crates/environ/src/collections.rs b/crates/environ/src/collections.rs
index 577abc9fc4..9041071f49 100644
--- a/crates/environ/src/collections.rs
+++ b/crates/environ/src/collections.rs
@@ -1,10 +1,12 @@
//! Fallible, OOM-handling collections.
mod entity_set;
+mod hash_set;
mod primary_map;
mod secondary_map;
pub use entity_set::EntitySet;
+pub use hash_set::HashSet;
pub use primary_map::PrimaryMap;
pub use secondary_map::SecondaryMap;
pub use wasmtime_core::alloc::{TryNew, Vec, try_new};
diff --git a/crates/environ/src/collections/hash_set.rs b/crates/environ/src/collections/hash_set.rs
new file mode 100644
index 0000000000..5032d06d9c
--- /dev/null
+++ b/crates/environ/src/collections/hash_set.rs
@@ -0,0 +1,190 @@
+use crate::error::OutOfMemory;
+use core::{
+ borrow::Borrow,
+ fmt,
+ hash::{BuildHasher, Hash},
+};
+
+#[cfg(feature = "std")]
+use std::{collections::hash_set as inner, hash::RandomState as DefaultHashBuilder};
+
+#[cfg(not(feature = "std"))]
+use hashbrown::{DefaultHashBuilder, hash_set as inner};
+
+/// A wrapper type around [`hashbrown::hash_set::HashSet`] that only exposes
+/// fallible allocation.
+pub struct HashSet<T, S = DefaultHashBuilder> {
+ inner: inner::HashSet<T, S>,
+}
+
+impl<T, S> PartialEq for HashSet<T, S>
+where
+ T: Eq + Hash,
+ S: BuildHasher,
+{
+ fn eq(&self, other: &Self) -> bool {
+ self.inner.eq(&other.inner)
+ }
+}
+
+impl<T, S> Eq for HashSet<T, S>
+where
+ T: Eq + Hash,
+ S: BuildHasher,
+{
+}
+
+impl<T, S> fmt::Debug for HashSet<T, S>
+where
+ T: fmt::Debug,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(&self.inner, f)
+ }
+}
+
+impl<T> HashSet<T, DefaultHashBuilder> {
+ /// Same as [`hashbrown::hash_set::HashSet::new`].
+ pub fn new() -> Self {
+ Self {
+ inner: inner::HashSet::new(),
+ }
+ }
+}
+
+impl<T> HashSet<T, DefaultHashBuilder>
+where
+ T: Eq + Hash,
+{
+ /// Same as [`hashbrown::hash_set::HashSet::with_capacity`] but returns an
+ /// error on allocation failure.
+ pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
+ let mut set = Self::new();
+ set.reserve(capacity)?;
+ Ok(set)
+ }
+}
+
+impl<T, S> HashSet<T, S> {
+ /// Same as [`hashbrown::hash_set::HashSet::with_hasher`].
+ pub const fn with_hasher(hasher: S) -> Self {
+ Self {
+ inner: inner::HashSet::with_hasher(hasher),
+ }
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::capacity`].
+ pub fn capacity(&self) -> usize {
+ self.inner.capacity()
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::iter`].
+ pub fn iter(&self) -> inner::Iter<'_, T> {
+ self.inner.iter()
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::len`].
+ pub fn len(&self) -> usize {
+ self.inner.len()
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::is_empty`].
+ pub fn is_empty(&self) -> bool {
+ self.inner.is_empty()
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::drain`].
+ pub fn drain(&mut self) -> inner::Drain<'_, T> {
+ self.inner.drain()
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::retain`].
+ pub fn retain<F>(&mut self, f: F)
+ where
+ F: FnMut(&T) -> bool,
+ {
+ self.inner.retain(f);
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::extract_if`].
+ pub fn extract_if<F>(&mut self, f: F) -> inner::ExtractIf<'_, T, F>
+ where
+ F: FnMut(&T) -> bool,
+ {
+ self.inner.extract_if(f)
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::clear`].
+ pub fn clear(&mut self) {
+ self.inner.clear();
+ }
+}
+
+impl<T, S> HashSet<T, S>
+where
+ T: Eq + Hash,
+ S: BuildHasher,
+{
+ /// Same as [`hashbrown::hash_set::HashSet::with_capacity_and_hasher`] but
+ /// returns an error on allocation failure.
+ pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Result<Self, OutOfMemory> {
+ let mut map = Self::with_hasher(hasher);
+ map.reserve(capacity)?;
+ Ok(map)
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::reserve`] but returns an error
+ /// on allocation failure.
+ pub fn reserve(&mut self, additional: usize) -> Result<(), OutOfMemory> {
+ self.inner.try_reserve(additional).map_err(|_| {
+ OutOfMemory::new(
+ self.len()
+ .saturating_add(additional)
+ .saturating_mul(core::mem::size_of::<T>()),
+ )
+ })
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::contains`].
+ pub fn contains<Q>(&self, value: &Q) -> bool
+ where
+ Q: Hash + Eq + ?Sized,
+ T: Borrow<Q>,
+ {
+ self.inner.contains(value)
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::get`].
+ pub fn get<Q>(&self, value: &Q) -> Option<&T>
+ where
+ Q: Hash + Eq + ?Sized,
+ T: Borrow<Q>,
+ {
+ self.inner.get(value)
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::insert`] but returns an error on
+ /// allocation failure.
+ pub fn insert(&mut self, value: T) -> Result<bool, OutOfMemory> {
+ self.reserve(1)?;
+ Ok(self.inner.insert(value))
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::remove`].
+ pub fn remove<Q>(&mut self, value: &Q) -> bool
+ where
+ Q: Hash + Eq + ?Sized,
+ T: Borrow<Q>,
+ {
+ self.inner.remove(value)
+ }
+
+ /// Same as [`hashbrown::hash_set::HashSet::take`].
+ pub fn take<Q>(&mut self, value: &Q) -> Option<T>
+ where
+ Q: Hash + Eq + ?Sized,
+ T: Borrow<Q>,
+ {
+ self.inner.take(value)
+ }
+}
diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rs
index c1084a3b5a..efc4d95e2a 100644
--- a/crates/fuzzing/tests/oom.rs
+++ b/crates/fuzzing/tests/oom.rs
@@ -144,6 +144,37 @@ fn entity_set_insert() -> Result<()> {
})
}
+#[test]
+fn hash_set_with_capacity() -> Result<()> {
+ OomTest::new().test(|| {
+ let _s = HashSet::<usize>::with_capacity(100)?;
+ Ok(())
+ })
+}
+
+#[test]
+fn hash_set_reserve() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut set = HashSet::<usize>::new();
+ set.reserve(100)?;
+ Ok(())
+ })
+}
+
+#[test]
+fn hash_set_insert() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut set = HashSet::<usize>::new();
+ for i in 0..1024 {
+ set.insert(i)?;
+ }
+ for i in 0..1024 {
+ set.insert(i)?;
+ }
+ Ok(())
+ })
+}
+
#[test]
fn vec_with_capacity() -> Result<()> {
OomTest::new().test(|| {