// 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"))),
        }
    }

}
