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
// License: see LICENSE file at root directory of `master` branch

//! # Shortcuts for `Value::String`

use {
    alloc::string::{String, ToString},
    core::convert::TryFrom,

    crate::{Error, Result, Value},
};

/// # Shortcuts for [`String`](#variant.String)
impl Value {

    /// # If the value is a string, returns an immutable reference of it
    ///
    /// Returns an error if the value is not a string.
    pub fn as_str(&self) -> Result<&str> {
        match self {
            Value::String(s) => Ok(s),
            _ => Err(Error::from(__!("Value is not a String"))),
        }
    }

}

impl From<String> for Value {

    fn from(s: String) -> Self {
        Value::String(s)
    }

}

impl From<&str> for Value {

    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }

}

impl TryFrom<Value> for String {

    type Error = Error;

    fn try_from(value: Value) -> core::result::Result<Self, Self::Error> {
        match value {
            Value::String(s) => Ok(s),
            _ => Err(Error::from(__!("Value is not a String"))),
        }
    }

}