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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// License: see LICENSE file at root directory of `master` branch

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

use {
    alloc::{
        borrow::Cow,
        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(err!("Value is not a String")),
        }
    }

    /// # If the value is a string, returns a mutable reference of it
    ///
    /// Returns an error if the value is not a string.
    pub fn as_mut_str(&mut self) -> Result<&mut String> {
        match self {
            Value::String(s) => Ok(s),
            _ => Err(err!("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 From<Cow<'_, str>> for Value {

    fn from(s: Cow<str>) -> Self {
        Self::from(s.into_owned())
    }

}

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(err!("Value is not a String")),
        }
    }

}