value: add TryFrom impl for borrowed Binary values

This commit is contained in:
Matt Bilker
2018-12-13 01:26:41 +00:00
parent b9d8ecbd44
commit cde3f8a90a

View File

@@ -599,6 +599,13 @@ impl Value {
}
}
pub fn as_binary(&self) -> Result<&[u8], KbinError> {
match self {
Value::Binary(ref data) => Ok(data),
value => Err(KbinErrorKind::ValueTypeMismatch(StandardType::Binary, value.clone()).into()),
}
}
pub fn as_array(&self) -> Result<&[Value], KbinError> {
match self {
Value::Array(_, ref values) => Ok(values),
@@ -623,6 +630,15 @@ impl TryFrom<Value> for Vec<u8> {
}
}
#[cfg(feature = "try_from")]
impl TryFrom<&Value> for Vec<u8> {
type Error = KbinError;
fn try_from(value: &Value) -> Result<Self, Self::Error> {
value.as_binary().map(Vec::from)
}
}
impl From<Vec<u8>> for Value {
fn from(value: Vec<u8>) -> Value {
Value::Binary(value)