1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use crate::type_name::SpannedTypeName;
use crate::value::dict::Dictionary;
use crate::value::primitive::Primitive;
use crate::value::{UntaggedValue, Value};
use nu_errors::{CoerceInto, ShellError};
use nu_source::TaggedItem;

impl std::convert::TryFrom<&Value> for i64 {
    type Error = ShellError;

    /// Convert to an i64 integer, if possible
    fn try_from(value: &Value) -> Result<i64, ShellError> {
        match &value.value {
            UntaggedValue::Primitive(Primitive::Int(int)) => Ok(*int),
            UntaggedValue::Primitive(Primitive::BigInt(int)) => {
                int.tagged(&value.tag).coerce_into("converting to i64")
            }
            _ => Err(ShellError::type_error("Integer", value.spanned_type_name())),
        }
    }
}

impl std::convert::TryFrom<&Value> for String {
    type Error = ShellError;

    /// Convert to a string, if possible
    fn try_from(value: &Value) -> Result<String, ShellError> {
        match &value.value {
            UntaggedValue::Primitive(Primitive::String(s)) => Ok(s.clone()),
            _ => Err(ShellError::type_error("String", value.spanned_type_name())),
        }
    }
}

impl std::convert::TryFrom<&Value> for Vec<u8> {
    type Error = ShellError;

    /// Convert to a u8 vec, if possible
    fn try_from(value: &Value) -> Result<Vec<u8>, ShellError> {
        match &value.value {
            UntaggedValue::Primitive(Primitive::Binary(b)) => Ok(b.clone()),
            _ => Err(ShellError::type_error("Binary", value.spanned_type_name())),
        }
    }
}

impl<'a> std::convert::TryFrom<&'a Value> for &'a Dictionary {
    type Error = ShellError;

    /// Convert to a dictionary, if possible
    fn try_from(value: &'a Value) -> Result<&'a Dictionary, ShellError> {
        match &value.value {
            UntaggedValue::Row(d) => Ok(d),
            _ => Err(ShellError::type_error(
                "Dictionary",
                value.spanned_type_name(),
            )),
        }
    }
}