diff --git a/Cargo.toml b/Cargo.toml index ff72249f5..299937c3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ exclude = ["rfcs/**/*", "/.travis.yml", "/appveyor.yml"] build = "build.rs" [package.metadata.docs.rs] -features = ["std", "serde", "kv_unstable_std", "kv_unstable_sval"] +features = ["std", "serde", "kv_unstable_std", "kv_unstable_sval", "kv_unstable_serde"] [[test]] name = "filters" @@ -48,6 +48,7 @@ std = [] kv_unstable = ["value-bag"] kv_unstable_sval = ["kv_unstable", "value-bag/sval", "sval"] kv_unstable_std = ["std", "kv_unstable", "value-bag/error"] +kv_unstable_serde = ["kv_unstable_std", "value-bag/serde", "serde"] [dependencies] cfg-if = "1.0" diff --git a/src/kv/value.rs b/src/kv/value.rs index 60f25c4d1..561ea8641 100644 --- a/src/kv/value.rs +++ b/src/kv/value.rs @@ -7,6 +7,9 @@ extern crate value_bag; #[cfg(feature = "kv_unstable_sval")] extern crate sval; +#[cfg(feature = "kv_unstable_serde")] +extern crate serde; + use self::value_bag::ValueBag; pub use kv::Error; @@ -147,6 +150,17 @@ impl<'v> Value<'v> { } } + #[cfg(feature = "kv_unstable_serde")] + /// Get a value from a type implementing `serde::Serialize`. + pub fn capture_serde(value: &'v T) -> Self + where + T: self::serde::Serialize + 'static, + { + Value { + inner: ValueBag::capture_serde1(value), + } + } + /// Get a value from a type implementing `sval::value::Value`. #[cfg(feature = "kv_unstable_sval")] pub fn capture_sval(value: &'v T) -> Self @@ -178,6 +192,17 @@ impl<'v> Value<'v> { } } + /// Get a value from a type implementing `serde::Serialize`. + #[cfg(feature = "kv_unstable_serde")] + pub fn from_serde(value: &'v T) -> Self + where + T: self::serde::Serialize, + { + Value { + inner: ValueBag::from_serde1(value), + } + } + /// Get a value from a type implementing `sval::value::Value`. #[cfg(feature = "kv_unstable_sval")] pub fn from_sval(value: &'v T) -> Self @@ -261,6 +286,16 @@ impl ToValue for dyn std::error::Error + 'static { } } +#[cfg(feature = "kv_unstable_serde")] +impl<'v> self::serde::Serialize for Value<'v> { + fn serialize(&self, s: S) -> Result + where + S: self::serde::Serializer, + { + self.inner.serialize(s) + } +} + #[cfg(feature = "kv_unstable_sval")] impl<'v> self::sval::value::Value for Value<'v> { fn stream(&self, stream: &mut self::sval::value::Stream) -> self::sval::value::Result { @@ -485,6 +520,14 @@ pub(crate) mod tests { assert!(Value::from_dyn_error(&err).to_error().is_some()); } + #[cfg(feature = "kv_unstable_serde")] + #[test] + fn test_capture_serde() { + assert_eq!(Some(42u64), Value::capture_serde(&42).to_u64()); + + assert_eq!(Some(42u64), Value::from_serde(&42).to_u64()); + } + #[cfg(feature = "kv_unstable_sval")] #[test] fn test_capture_sval() {