vyder_std 0.3.4

Standard library for vyder.
Documentation
//! Various functions to convert from one type to another.
//!
//! Available under the name `std-convert`.

use std::process::ExitCode;

use vyder::{values, Error, ExpectArity, Module, Span, Value, ValueResult};

/// Convert a value to a string.
///
/// Takes exactly one argument.
pub fn to_string(
    arguments: &[ValueResult],
    span: Span,
) -> Result<(ValueResult, Option<ExitCode>), Error> {
    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0]
        .clone()
        .expect_non_error()?;
    Ok((
        Value::new_ok_value(
            values::Str {
                value: argument.value.to_string(),
            }
            .into(),
            span,
        ),
        None,
    ))
}

/// Tries to convert a string to a number. May fail.
///
/// Takes exaclty one argument.
pub fn string_to_number(
    arguments: &[ValueResult],
    span: Span,
) -> Result<(ValueResult, Option<ExitCode>), Error> {
    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0]
        .clone()
        .expect_non_error()?
        .expect::<values::Str>()?
        .value;

    match argument.parse::<f64>() {
        Ok(number) => Ok((
            Value::new_ok_value(values::Number { value: number }.into(), span),
            None,
        )),
        Err(_) => Ok((
            Value::new_err_value(
                values::Str {
                    value: "failed to convert the input to a number".to_string(),
                }
                .into(),
                span,
            ),
            None,
        )),
    }
}

pub fn get_module() -> Module {
    Module::builder()
        .function("string_to_number", string_to_number, true)
        .function("to_string", to_string, false)
        .build()
}