Skip to main content

vyder_std/
convert.rs

1//! Various functions to convert from one type to another.
2//!
3//! Available under the name `std-convert`.
4
5use std::process::ExitCode;
6
7use vyder::{values, Error, ExpectArity, Module, Span, Value, ValueResult};
8
9/// Convert a value to a string.
10///
11/// Takes exactly one argument.
12pub fn to_string(
13    arguments: &[ValueResult],
14    span: Span,
15) -> Result<(ValueResult, Option<ExitCode>), Error> {
16    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0]
17        .clone()
18        .expect_non_error()?;
19    Ok((
20        Value::new_ok_value(
21            values::Str {
22                value: argument.value.to_string(),
23            }
24            .into(),
25            span,
26        ),
27        None,
28    ))
29}
30
31/// Tries to convert a string to a number. May fail.
32///
33/// Takes exaclty one argument.
34pub fn string_to_number(
35    arguments: &[ValueResult],
36    span: Span,
37) -> Result<(ValueResult, Option<ExitCode>), Error> {
38    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0]
39        .clone()
40        .expect_non_error()?
41        .expect::<values::Str>()?
42        .value;
43
44    match argument.parse::<f64>() {
45        Ok(number) => Ok((
46            Value::new_ok_value(values::Number { value: number }.into(), span),
47            None,
48        )),
49        Err(_) => Ok((
50            Value::new_err_value(
51                values::Str {
52                    value: "failed to convert the input to a number".to_string(),
53                }
54                .into(),
55                span,
56            ),
57            None,
58        )),
59    }
60}
61
62pub fn get_module() -> Module {
63    Module::builder()
64        .function("string_to_number", string_to_number, true)
65        .function("to_string", to_string, false)
66        .build()
67}