From c85f497d8e13534b654b92a64f55c187e16e7874 Mon Sep 17 00:00:00 2001 From: Tim Fennis Date: Tue, 15 Oct 2024 13:11:45 +0200 Subject: [PATCH] Add chr function --- src/stdlib/string.rs | 9 ++++++++- tests/programs/602_stdlib_string/004_chr.ndct | 4 ++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 tests/programs/602_stdlib_string/004_chr.ndct diff --git a/src/stdlib/string.rs b/src/stdlib/string.rs index c834d8d..9179c38 100644 --- a/src/stdlib/string.rs +++ b/src/stdlib/string.rs @@ -4,7 +4,8 @@ use andy_cpp_macros::export_module; mod inner { use crate::interpreter::sequence::Sequence; use crate::interpreter::value::Value; - use anyhow::anyhow; + + use anyhow::{anyhow, Context}; use itertools::Itertools; use std::rc::Rc; @@ -21,6 +22,12 @@ mod inner { Ok(res) } + pub fn chr(num: i64) -> anyhow::Result { + let num = u32::try_from(num).context("this number is not a valid character")?; + let char = char::from_u32(num).context("this number is not a valid character")?; + Ok(String::from(char)) + } + // TODO: remove this function once actual slicing is supported pub fn slice(string: &str, i: usize, j: usize) -> anyhow::Result { let len = string.chars().count(); diff --git a/tests/programs/602_stdlib_string/004_chr.ndct b/tests/programs/602_stdlib_string/004_chr.ndct new file mode 100644 index 0000000..94c262b --- /dev/null +++ b/tests/programs/602_stdlib_string/004_chr.ndct @@ -0,0 +1,4 @@ +--PROGRAM-- +print(chr(3486)); +--EXPECT-- +ඞ