Skip to content

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

Add a fallible-allocation-only version of `HashMap` (#12535)

Nick Fitzgeraldf0011184ee53
diff --git a/Cargo.lock b/Cargo.lock
index 363e6e2073..7b5a3da6db 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4868,6 +4868,7 @@ name = "wasmtime-internal-core"
version = "43.0.0"
dependencies = [
"anyhow",
+ "hashbrown 0.15.2",
"libm",
]
diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml
index 0658e7869f..2213c940a3 100644
--- a/crates/core/Cargo.toml
+++ b/crates/core/Cargo.toml
@@ -10,8 +10,9 @@ version.workspace = true
[dependencies]
# This crate should have *very* minimal dependencies! Don't add new ones
# lightly.
-libm = { workspace = true }
anyhow = { workspace = true, optional = true }
+libm = { workspace = true }
+hashbrown = { workspace = true, features = ["default-hasher"] }
[lints]
workspace = true
diff --git a/crates/core/src/alloc/try_clone.rs b/crates/core/src/alloc/try_clone.rs
index 73e7d0a3d6..98c4d61343 100644
--- a/crates/core/src/alloc/try_clone.rs
+++ b/crates/core/src/alloc/try_clone.rs
@@ -72,3 +72,13 @@ tuples! {
A, B, C, D, E, F, G, H, I;
A, B, C, D, E, F, G, H, I, J;
}
+
+#[cfg(feature = "std")]
+impl_try_clone_via_clone! {
+ std::hash::RandomState
+}
+
+#[cfg(not(feature = "std"))]
+impl_try_clone_via_clone! {
+ hashbrown::DefaultHashBuilder
+}
diff --git a/crates/environ/src/collections.rs b/crates/environ/src/collections.rs
index 5ddbaf8385..18d4193af6 100644
--- a/crates/environ/src/collections.rs
+++ b/crates/environ/src/collections.rs
@@ -1,11 +1,13 @@
//! Fallible, OOM-handling collections.
mod entity_set;
+mod hash_map;
mod hash_set;
mod primary_map;
mod secondary_map;
pub use entity_set::EntitySet;
+pub use hash_map::HashMap;
pub use hash_set::HashSet;
pub use primary_map::PrimaryMap;
pub use secondary_map::SecondaryMap;
diff --git a/crates/environ/src/collections/hash_map.rs b/crates/environ/src/collections/hash_map.rs
new file mode 100644
index 0000000000..53fe10efde
--- /dev/null
+++ b/crates/environ/src/collections/hash_map.rs
@@ -0,0 +1,254 @@
+use crate::error::OutOfMemory;
+use core::{
+ borrow::Borrow,
+ fmt,
+ hash::{BuildHasher, Hash},
+ mem,
+};
+
+#[cfg(feature = "std")]
+use std::{collections::hash_map as inner, hash::RandomState as DefaultHashBuilder};
+
+#[cfg(not(feature = "std"))]
+use hashbrown::{DefaultHashBuilder, hash_map as inner};
+use wasmtime_core::alloc::TryClone;
+
+/// A wrapper type around [`hashbrown::hash_map::HashMap`] that only exposes
+/// fallible allocation.
+pub struct HashMap<K, V, S = DefaultHashBuilder> {
+ inner: inner::HashMap<K, V, S>,
+}
+
+impl<K, V, S> TryClone for HashMap<K, V, S>
+where
+ K: Eq + Hash + TryClone,
+ V: TryClone,
+ S: BuildHasher + TryClone,
+{
+ fn try_clone(&self) -> Result<Self, OutOfMemory> {
+ let mut map = Self::with_capacity_and_hasher(self.len(), self.hasher().try_clone()?)?;
+ for (k, v) in self {
+ map.insert(k.try_clone()?, v.try_clone()?)
+ .expect("reserved capacity");
+ }
+ Ok(map)
+ }
+}
+
+impl<K, V, S> Default for HashMap<K, V, S>
+where
+ S: Default,
+{
+ fn default() -> Self {
+ Self {
+ inner: inner::HashMap::default(),
+ }
+ }
+}
+
+impl<K, V, S> PartialEq for HashMap<K, V, S>
+where
+ K: Eq + Hash,
+ V: PartialEq,
+ S: BuildHasher,
+{
+ fn eq(&self, other: &Self) -> bool {
+ self.inner.eq(&other.inner)
+ }
+}
+
+impl<K, V, S> Eq for HashMap<K, V, S>
+where
+ K: Eq + Hash,
+ V: Eq,
+ S: BuildHasher,
+{
+}
+
+impl<K, V, S> fmt::Debug for HashMap<K, V, S>
+where
+ K: fmt::Debug,
+ V: fmt::Debug,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(&self.inner, f)
+ }
+}
+
+impl<K, V> HashMap<K, V, DefaultHashBuilder> {
+ /// Same as [`hashbrown::hash_map::HashMap::new`].
+ pub fn new() -> Self {
+ Self {
+ inner: inner::HashMap::new(),
+ }
+ }
+}
+
+impl<K, V> HashMap<K, V, DefaultHashBuilder>
+where
+ K: Eq + Hash,
+{
+ /// Same as [`hashbrown::hash_map::HashMap::with_capacity`] but returns an
+ /// error on allocation failure.
+ pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
+ let mut map = Self::new();
+ map.reserve(capacity)?;
+ Ok(map)
+ }
+}
+
+impl<K, V, S> HashMap<K, V, S> {
+ /// Same as [`hashbrown::hash_map::HashMap::with_hasher`].
+ pub const fn with_hasher(hasher: S) -> Self {
+ Self {
+ inner: inner::HashMap::with_hasher(hasher),
+ }
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::hasher`].
+ pub fn hasher(&self) -> &S {
+ self.inner.hasher()
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::capacity`].
+ pub fn capacity(&self) -> usize {
+ self.inner.capacity()
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::len`].
+ pub fn len(&self) -> usize {
+ self.inner.len()
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::is_empty`].
+ pub fn is_empty(&self) -> bool {
+ self.inner.is_empty()
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::drain`].
+ pub fn drain(&mut self) -> inner::Drain<'_, K, V> {
+ self.inner.drain()
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::retain`].
+ pub fn retain<F>(&mut self, f: F)
+ where
+ F: FnMut(&K, &mut V) -> bool,
+ {
+ self.inner.retain(f);
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::extract_if`].
+ pub fn extract_if<F>(&mut self, f: F) -> inner::ExtractIf<'_, K, V, F>
+ where
+ F: FnMut(&K, &mut V) -> bool,
+ {
+ self.inner.extract_if(f)
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::clear`].
+ pub fn clear(&mut self) {
+ self.inner.clear();
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::iter`].
+ pub fn iter(&self) -> inner::Iter<'_, K, V> {
+ self.inner.iter()
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::iter_mut`].
+ pub fn iter_mut(&mut self) -> inner::IterMut<'_, K, V> {
+ self.inner.iter_mut()
+ }
+}
+
+impl<K, V, S> HashMap<K, V, S>
+where
+ K: Eq + Hash,
+ S: BuildHasher,
+{
+ /// Same as [`hashbrown::hash_map::HashMap::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_map::HashMap::reserve`] but returns an error
+ /// on allocation failure.
+ pub fn reserve(&mut self, additional: usize) -> Result<(), OutOfMemory> {
+ self.inner.try_reserve(additional).map_err(|_| {
+ let new_len = self.len().saturating_add(additional);
+ OutOfMemory::new(
+ new_len
+ .saturating_mul(mem::size_of::<K>())
+ .saturating_add(new_len.saturating_mul(mem::size_of::<V>())),
+ )
+ })
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::contains_key`].
+ pub fn contains_key<Q>(&self, key: &Q) -> bool
+ where
+ Q: Hash + Eq + ?Sized,
+ K: Borrow<Q>,
+ {
+ self.inner.contains_key(key)
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::get`].
+ pub fn get<Q>(&self, value: &Q) -> Option<&V>
+ where
+ Q: Hash + Eq + ?Sized,
+ K: Borrow<Q>,
+ {
+ self.inner.get(value)
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::insert`] but returns an error on
+ /// allocation failure.
+ pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, OutOfMemory> {
+ self.reserve(1)?;
+ Ok(self.inner.insert(key, value))
+ }
+
+ /// Same as [`hashbrown::hash_map::HashMap::remove`].
+ pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
+ where
+ Q: Hash + Eq + ?Sized,
+ K: Borrow<Q>,
+ {
+ self.inner.remove(key)
+ }
+}
+
+impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
+ type Item = (&'a K, &'a V);
+
+ type IntoIter = inner::Iter<'a, K, V>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
+ type Item = (&'a K, &'a mut V);
+
+ type IntoIter = inner::IterMut<'a, K, V>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter_mut()
+ }
+}
+
+impl<K, V, S> IntoIterator for HashMap<K, V, S> {
+ type Item = (K, V);
+
+ type IntoIter = inner::IntoIter<K, V>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.inner.into_iter()
+ }
+}
diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rs
index dec2295da1..8631965a41 100644
--- a/crates/fuzzing/tests/oom.rs
+++ b/crates/fuzzing/tests/oom.rs
@@ -175,6 +175,50 @@ fn hash_set_insert() -> Result<()> {
})
}
+#[test]
+fn hash_map_with_capacity() -> Result<()> {
+ OomTest::new().test(|| {
+ let _s = HashMap::<usize, usize>::with_capacity(100)?;
+ Ok(())
+ })
+}
+
+#[test]
+fn hash_map_reserve() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut map = HashMap::<usize, usize>::new();
+ map.reserve(100)?;
+ Ok(())
+ })
+}
+
+#[test]
+fn hash_map_insert() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut map = HashMap::<usize, usize>::new();
+ for i in 0..1024 {
+ map.insert(i, i * 2)?;
+ }
+ for i in 0..1024 {
+ map.insert(i, i * 2)?;
+ }
+ Ok(())
+ })
+}
+
+#[test]
+fn hash_map_try_clone() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut map = HashMap::new();
+ for i in 0..10 {
+ map.insert(i, i * 2)?;
+ }
+ let map2 = map.try_clone()?;
+ assert_eq!(map, map2);
+ Ok(())
+ })
+}
+
#[test]
fn vec_with_capacity() -> Result<()> {
OomTest::new().test(|| {