diff --git a/Cargo.toml b/Cargo.toml index 49c66e1..b73472f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,3 +23,4 @@ serde_derive = { version = "1.0.79", optional = true } [features] serde-1 = ["serde", "serde_bytes", "serde_derive", "indexmap/serde-1"] +try_from = [] diff --git a/src/lib.rs b/src/lib.rs index 7a2b5c1..e40d718 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ #![cfg_attr(test, feature(test))] +#![cfg_attr(feature = "try_from", feature(try_from))] extern crate byteorder; extern crate bytes; diff --git a/src/value/mod.rs b/src/value/mod.rs index d500fca..797b9d0 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "try_from")] +use std::convert::TryFrom; use std::fmt; use std::net::Ipv4Addr; use std::str::FromStr; @@ -412,6 +414,18 @@ macro_rules! construct_types { Value::$konst(value) } } + + #[cfg(feature = "try_from")] + impl TryFrom for $($value_type)* { + type Error = KbinError; + + fn try_from(value: Value) -> Result { + match value { + Value::$konst(v) => Ok(v), + value => Err(KbinErrorKind::ValueTypeMismatch(StandardType::$konst, value).into()), + } + } + } )+ impl Value {