Skip to main content

rl_lang/interpreter/stdlib/string/
char_at.rs

1use crate::{
2    interpreter::evaluator::Evaluator,
3    utils::{errors::Error, span::Span},
4};
5
6pub fn std_char_at(
7    eval: &mut Evaluator,
8    string: String,
9    index: i64,
10    span: Span,
11) -> Result<char, Error> {
12    if index < 0 {
13        return Err(eval.err(format!("index cannot be negative: {}", index), span));
14    }
15    let mut chars = string.chars();
16    let chars_count = chars.clone().count();
17    if index as usize >= chars_count {
18        Err(eval.err(
19            format!(
20                "index out of bounds string length is {} , used {}",
21                chars_count, index
22            ),
23            span,
24        ))
25    } else {
26        Ok(chars.nth(index as usize).unwrap())
27    }
28}