A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Implement serialization and deserialization for our OOM-handling `String` (#12552)
Nick Fitzgerald33a3a2dd6237
diff --git a/Cargo.lock b/Cargo.lockindex e03c860f30..689dc7e107 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4879,6 +4879,7 @@ dependencies = ["anyhow","hashbrown 0.16.1","libm",+ "serde",][[package]]diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.tomlindex 2213c940a3..a8c0defef6 100644--- a/crates/core/Cargo.toml+++ b/crates/core/Cargo.toml@@ -11,8 +11,9 @@ version.workspace = true# This crate should have *very* minimal dependencies! Don't add new ones# lightly.anyhow = { workspace = true, optional = true }-libm = { workspace = true }hashbrown = { workspace = true, features = ["default-hasher"] }+libm = { workspace = true }+serde = { workspace = true }[lints]workspace = truediff --git a/crates/core/src/alloc/string.rs b/crates/core/src/alloc/string.rsindex 4212ce0feb..e25e6307de 100644--- a/crates/core/src/alloc/string.rs+++ b/crates/core/src/alloc/string.rs@@ -55,6 +55,48 @@ impl From<inner::String> for String {}}+impl serde::ser::Serialize for String {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ serializer.serialize_str(self)+ }+}++impl<'de> serde::de::Deserialize<'de> for String {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ struct Visitor;++ impl<'de> serde::de::Visitor<'de> for Visitor {+ type Value = String;++ fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {+ f.write_str("a `wasmtime_core::alloc::String` str")+ }++ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>+ where+ E: serde::de::Error,+ {+ let mut s = String::new();+ s.reserve_exact(v.len()).map_err(|oom| E::custom(oom))?;+ s.push_str(v).expect("reserved capacity");+ Ok(s)+ }+ }++ // NB: do not use `deserialize_string` as that eagerly allocates the+ // `String` and does not give us a chance to handle OOM. Instead, use+ // `deserialize_str` which passes the visitor the borrowed `str`, giving+ // us a chance to fallibly allocate space.+ deserializer.deserialize_str(Visitor)+ }+}+impl String {/// Same as [`std::string::String::new`].#[inline]