Struct Value

Source
pub struct Value { /* private fields */ }
Expand description

The Value type. See the module level documentation for more.

Implementations§

Source§

impl Value

Source

pub fn empty() -> Value

Returns the empty Value, a value whose string representation is the empty string.

TODO: This should really be a constant, but there’s way to build it as one unless I use lazy_static.

Source

pub fn as_str(&self) -> &str

Returns the value’s string representation as a reference-counted string.

Note: This is the standard way of retrieving a Value’s string rep, as unlike to_string it doesn’t create a new String.

§Example
use molt::types::Value;
let value = Value::from(123);
assert_eq!(value.as_str(), "123");
Source

pub fn try_as_str(&self) -> Option<&str>

Returns the value’s string representation if it is already ready. This is useful for implementing command line switches.

§Example
use molt::types::Value;
let value = Value::from(123);
assert_eq!(value.try_as_str(), None);
assert_eq!(value.as_str(), "123");
assert_eq!(value.try_as_str(), Some("123"));
let value_str = Value::from("123");
assert_eq!(value_str.try_as_str(), Some("123"));
Source

pub fn as_bool(&self) -> Result<bool, Exception>

Tries to return the Value as a bool, parsing the value’s string representation if necessary.

§Boolean Strings

The following are valid boolean strings, regardless of case: true, false, on, off, yes, no, 1, 0. Note that other numeric strings are not valid boolean strings.

§Numeric Values

Non-negative numbers are interpreted as true; zero is interpreted as false.

§Example
use molt::types::Value;
use molt::types::Exception;
// All of the following can be interpreted as booleans.
let value = Value::from(true);
let flag = value.as_bool()?;
assert_eq!(flag, true);

let value = Value::from("no");
let flag = value.as_bool()?;
assert_eq!(flag, false);

let value = Value::from(5);
let flag = value.as_bool()?;
assert_eq!(flag, true);

let value = Value::from(0);
let flag = value.as_bool()?;
assert_eq!(flag, false);

let value = Value::from(1.1);
let flag = value.as_bool()?;
assert_eq!(flag, true);

let value = Value::from(0.0);
let flag = value.as_bool()?;
assert_eq!(flag, false);

// Numeric strings can not, unless evaluated as expressions.
let value = Value::from("123");
assert!(value.as_bool().is_err());
Source

pub fn get_bool(arg: &str) -> Result<bool, Exception>

Converts a string argument into a boolean, returning an error on failure.

Molt accepts the following strings as Boolean values:

  • true: true, yes, on, 1
  • false: false, no, off, 0

Parsing is case-insensitive, and leading and trailing whitespace are ignored.

This method does not evaluate expressions; use molt::expr to evaluate boolean expressions.

§Example
let arg = "yes";
let flag = Value::get_bool(arg)?;
assert!(flag);
Source

pub fn as_dict(&self) -> Result<Rc<MoltDict>, Exception>

Tries to return the Value as an Rc<MoltDict>, parsing the value’s string representation if necessary.

§Example
use std::rc::Rc;
use molt::types::Value;
use molt::types::MoltDict;
use molt::types::Exception;

let value = Value::from("abc 1234");
let dict: Rc<MoltDict> = value.as_dict()?;

assert_eq!(dict.len(), 1);
assert_eq!(dict.get(&Value::from("abc")), Some(&Value::from("1234")));
Source

pub fn to_dict(&self) -> Result<MoltDict, Exception>

Tries to return the Value as a MoltDict, parsing the value’s string representation if necessary.

Use as_dict when simply referring to the dict’s content; use this method when constructing a new dict from the old one.

§Example
use molt::types::Value;
use molt::types::MoltDict;
use molt::types::Exception;

let value = Value::from("abc 1234");
let dict: MoltDict = value.to_dict()?;
assert_eq!(dict.len(), 2);
assert_eq!(dict.get(&Value::from("abc")), Some(&Value::from("1234")));
Source

pub fn as_int(&self) -> Result<MoltInt, Exception>

Tries to return the Value as a MoltInt, parsing the value’s string representation if necessary.

§Integer Syntax

Molt accepts decimal integer strings, and hexadecimal integer strings with a 0x prefix. Strings may begin with a unary “+” or “-”. Hex digits may be in upper or lower case.

§Example
use molt::types::Value;
use molt::types::MoltInt;
use molt::types::Exception;

let value = Value::from(123);
let int = value.as_int()?;
assert_eq!(int, 123);

let value = Value::from("OxFF");
let int = value.as_int()?;
assert_eq!(int, 255);
Source

pub fn get_int(arg: &str) -> Result<MoltInt, Exception>

Converts a string argument into a MoltInt, returning an error on failure.

Molt accepts decimal integer strings, and hexadecimal integer strings with a 0x prefix. Strings may begin with a unary “+” or “-”. Leading and trailing whitespace is ignored.

§Example
let arg = "1";
let int = Value::get_int(arg)?;
Source

pub fn as_float(&self) -> Result<MoltFloat, Exception>

Tries to return the Value as a MoltFloat, parsing the value’s string representation if necessary.

§Floating-Point Syntax

Molt accepts the same floating-point strings as Rust’s standard numeric parser.

§Example
use molt::types::Value;
use molt::types::MoltFloat;
use molt::types::Exception;

let value = Value::from(12.34);
let flt = value.as_float()?;
assert_eq!(flt, 12.34);

let value = Value::from("23.45");
let flt = value.as_float()?;
assert_eq!(flt, 23.45);
Source

pub fn get_float(arg: &str) -> Result<MoltFloat, Exception>

Converts an string argument into a MoltFloat, returning an error on failure.

Molt accepts any string acceptable to str::parse<f64> as a valid floating point string. Leading and trailing whitespace is ignored, and parsing is case-insensitive.

§Example
let arg = "1e2";
let val = Value::get_float(arg)?;
Source

pub fn as_list(&self) -> Result<Rc<MoltList>, Exception>

Tries to return the Value as an Rc<MoltList>, parsing the value’s string representation if necessary.

§Example
use std::rc::Rc;
use molt::types::Value;
use molt::types::MoltList;
use molt::types::Exception;

let value = Value::from("1234 abc");
let list: Rc<MoltList> = value.as_list()?;
assert_eq!(list.len(), 2);

assert_eq!(list[0], Value::from("1234"));
assert_eq!(list[1], Value::from("abc"));
Source

pub fn to_list(&self) -> Result<MoltList, Exception>

Tries to return the Value as a MoltList, parsing the value’s string representation if necessary.

Use as_list when simply referring to the list’s content; use this method when constructing a new list from the old one.

§Example
use molt::types::Value;
use molt::types::MoltList;
use molt::types::Exception;

let value = Value::from("1234 abc");
let list: MoltList = value.to_list()?;
assert_eq!(list.len(), 2);

assert_eq!(list[0], Value::from("1234"));
assert_eq!(list[1], Value::from("abc"));
Source

pub fn as_var_name(&self) -> Rc<VarName>

Returns the Value as an Rc<VarName>, parsing the value’s string representation if necessary. This type is usually hidden by the Interp’s var and set_var methods, which use it implicitly; however it is available to extension authors if need be.

§Example
use molt::types::{Value, VarName};

let value = Value::from("my_var");
let var_name = value.as_var_name();
assert_eq!(var_name.name(), "my_var");
assert_eq!(var_name.index(), None);

let value = Value::from("my_array(1)");
let var_name = value.as_var_name();
assert_eq!(var_name.name(), "my_array");
assert_eq!(var_name.index(), Some("1"));
Source

pub fn from_other<T>(value: T) -> Value
where T: Display + Debug + 'static,

Creates a new Value containing the given value of some user type.

The user type must meet certain constraints; see the module level documentation for details on how to define an external type for use with Molt.

§Example

Suppose we have a type HexColor that meets the constraints; we can create a Value containing one as follows. Notice that the Value ownership of its input:

let color: HexColor::new(0x11u8, 0x22u8, 0x33u8);
let value = Value::from_other(color);

// Retrieve the value's string rep.
assert_eq!(value.as_str(), "#112233");

See Value::as_other and Value::as_copy for examples of how to retrieve a MyType value from a Value.

Source

pub fn as_other<T>(&self) -> Option<Rc<T>>
where T: Display + Debug + FromStr + 'static,

Tries to interpret the Value as a value of external type T, parsing the string representation if necessary.

The user type must meet certain constraints; see the module level documentation for details on how to define an external type for use with Molt.

§Return Value

The value is returned as an Rc<T>, as this allows the client to use the value freely and clone it efficiently if needed.

This method returns Option<Rc<T>> rather than Result<Rc<T>,Exception> because it is up to the caller to provide a meaningful error message. It is normal for externally defined types to wrap this function in a function that does so; see the module level documentation for an example.

§Example

Suppose we have a type HexColor that meets the constraints; we can create a Value containing one and retrieve it as follows.

// Just a normal Molt string
let value = Value::from("#112233");

// Retrieve it as an Option<Rc<HexColor>>:
let color = value.as_other::<HexColor>()

if color.is_some() {
    let color = color.unwrap();
    let r = *color.red();
    let g = *color.green();
    let b = *color.blue();
}
Source

pub fn as_copy<T>(&self) -> Option<T>
where T: Display + Debug + FromStr + Copy + 'static,

Tries to interpret the Value as a value of type T, parsing the string representation if necessary, and returning a copy.

The user type must meet certain constraints; and in particular it must implement Copy. See the module level documentation for details on how to define an external type for use with Molt.

This method returns Option rather than Result because it is up to the caller to provide a meaningful error message. It is normal for externally defined types to wrap this function in a function that does so.

§Example

Suppose we have a type HexColor that meets the normal external type constraints and also supports copy; we can create a Value containing one and retrieve it as follows.

// Just a normal Molt string
let value = Value::from("#112233");

// Retrieve it as an Option<HexColor>:
let color = value.as_copy::<HexColor>()

if color.is_some() {
    let color = color.unwrap();
    let r = color.red();
    let g = color.green();
    let b = color.blue();
}

Trait Implementations§

Source§

impl Clone for Value

Source§

fn clone(&self) -> Value

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

The Debug formatter for values.

TODO: This should indicate something about the data rep as well, especially for values in which the string rep isn’t yet set.

Source§

impl Display for Value

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

The Display formatter for Value. Outputs the value’s string rep.

Source§

impl From<&[Value]> for Value

Source§

fn from(list: &[Value]) -> Self

Creates a new Value whose data representation is a MoltList.

§Example
use molt::types::Value;

let values = [Value::from(1234), Value::from("abc")];
let value = Value::from(&values[..]);
assert_eq!(value.as_str(), "1234 abc");
Source§

impl From<&String> for Value

Source§

fn from(str: &String) -> Self

Creates a new Value from the given string reference.

§Example
use molt::types::Value;
let value = Value::from("My String Slice");
assert_eq!(value.as_str(), "My String Slice");
Source§

impl From<&str> for Value

Source§

fn from(str: &str) -> Self

Creates a new Value from the given string slice.

§Example
use molt::types::Value;
let value = Value::from("My String Slice");
assert_eq!(value.as_str(), "My String Slice");
Source§

impl From<IndexMap<Value, Value>> for Value

Source§

fn from(dict: MoltDict) -> Self

Creates a new Value whose data representation is a MoltDict.

§Example
use molt::types::Value;
use molt::types::MoltDict;
use molt::dict::dict_new;

let mut dict: MoltDict = dict_new();
dict.insert(Value::from("abc"), Value::from("123"));
let value = Value::from(dict);
assert_eq!(value.as_str(), "abc 123");
Source§

impl From<String> for Value

Source§

fn from(str: String) -> Self

Creates a new Value from the given String.

§Example
use molt::types::Value;
let string = String::from("My New String");
let value = Value::from(string);
assert_eq!(value.as_str(), "My New String");
Source§

impl From<Vec<Value>> for Value

Source§

fn from(list: MoltList) -> Self

Creates a new Value whose data representation is a MoltList.

§Example
use molt::types::Value;

let list = vec![Value::from(1234), Value::from("abc")];
let value = Value::from(list);
assert_eq!(value.as_str(), "1234 abc");
Source§

impl From<bool> for Value

Source§

fn from(flag: bool) -> Self

Creates a new Value whose data representation is a bool. The value’s string representation will be “1” or “0”.

§Example
use molt::types::Value;
let value = Value::from(true);
assert_eq!(value.as_str(), "1");

let value = Value::from(false);
assert_eq!(value.as_str(), "0");
Source§

impl From<f64> for Value

Source§

fn from(flt: MoltFloat) -> Self

Creates a new Value whose data representation is a MoltFloat.

§String Representation

The string representation of the value will be however Rust’s format! macro formats floating point numbers by default. Note: this isn’t quite what we want; Standard TCL goes to great lengths to ensure that the formatted string will yield exactly the same floating point number when it is parsed. Rust will format the number 5.0 as 5, turning it into a integer if parsed naively. So there is more work to be done here.

§Example
use molt::types::Value;

let value = Value::from(12.34);
assert_eq!(value.as_str(), "12.34");
Source§

impl From<i64> for Value

Source§

fn from(int: MoltInt) -> Self

Creates a new Value whose data representation is a MoltInt.

§Example
use molt::types::Value;

let value = Value::from(123);
assert_eq!(value.as_str(), "123");
Source§

impl Hash for Value

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Value

Source§

fn eq(&self, other: &Self) -> bool

Two Values are equal if their string representations are equal. Application code will often want to compare values numerically.

1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Value

Auto Trait Implementations§

§

impl Freeze for Value

§

impl !RefUnwindSafe for Value

§

impl !Send for Value

§

impl !Sync for Value

§

impl Unpin for Value

§

impl !UnwindSafe for Value

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.