vyder_std 0.3.4

Standard library for vyder.
Documentation
//! Various functions to handle strings.
//!
//! Available under the name `std-strings`.

use std::process::ExitCode;

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

/// Trim the whitespace at the start and the end of the input.
///
/// Expects exactly one argument.
pub fn trim_whitespace(
    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;

    Ok((
        Value::new_ok_value(
            values::Str {
                value: argument.trim().to_string(),
            }
            .into(),
            span,
        ),
        None,
    ))
}

/// Replace a pattern in the given string with something new.
///
/// Expectes the input, a pattern and the new string to replace each occurence of the pattern with.
pub fn replace(
    arguments: &[ValueResult],
    span: Span,
) -> Result<(ValueResult, Option<ExitCode>), Error> {
    let arguments = arguments.to_vec().expect_exact::<3>(&span)?.clone();

    let input = arguments[0]
        .clone()
        .expect_non_error()?
        .expect::<values::Str>()?;
    let pattern = arguments[1]
        .clone()
        .expect_non_error()?
        .expect::<values::Str>()?;
    let new = arguments[2]
        .clone()
        .expect_non_error()?
        .expect::<values::Str>()?;

    Ok((
        Value::new_ok_value(
            values::Str {
                value: input.value.replace(&pattern.value, &new.value),
            }
            .into(),
            span,
        ),
        None,
    ))
}

pub fn get_module() -> Module {
    Module::builder()
        .function("trim_whitespace", trim_whitespace, false)
        .function("replace", replace, false)
        .build()
}