Skip to main content

rl_lang/interpreter/stdlib/types/
char.rs

1use crate::interpreter::{
2    evaluator::Evaluator,
3    stdlib::common::{vc, verr, vok, vs},
4    values::Value,
5};
6
7pub fn std_is_char(_: &mut Evaluator, value: Value) -> bool {
8    matches!(value, Value::Char(_))
9}
10
11pub fn std_to_char(_: &mut Evaluator, value: Value) -> Value {
12    let result = match value {
13        Value::Char(c) => c,
14        Value::Integer(i) => match char::from_u32(i as u32) {
15            Some(c) => c,
16            None => return verr!(vs!(format!("{} is not a valid unicode codepoint", i))),
17        },
18        Value::Byte(i) => match char::from_u32(i as u32) {
19            Some(c) => c,
20            None => return verr!(vs!(format!("{} is not a valid unicode codepoint", i))),
21        },
22        Value::String(s) => {
23            let mut chars = s.chars();
24            match (chars.next(), chars.next()) {
25                (Some(c), None) => c,
26                _ => return verr!(vs!("string must be exactly one character".to_string())),
27            }
28        }
29
30        other => {
31            return verr!(vs!(format!(
32                "cannot parse \"{}\" as character",
33                other.type_name()
34            )));
35        }
36    };
37
38    vok!(vc!(result))
39}