From f6fbf001f5e27f3bff1eacc68ca9c6cac9ee7853 Mon Sep 17 00:00:00 2001 From: Matt Bilker Date: Wed, 12 Dec 2018 07:57:17 +0000 Subject: [PATCH] value: add TryFrom implementations to get inner type from value --- Cargo.toml | 1 + src/lib.rs | 1 + src/value/mod.rs | 14 ++++++++++++++ 3 files changed, 16 insertions(+) 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 {