Implement string indexing for Kal

This commit is contained in:
Andrew Morris
2023-07-06 17:38:08 +10:00
parent 4e2fb4b0d4
commit 5a6d11c980
3 changed files with 21 additions and 2 deletions

View File

@@ -1,6 +1,6 @@
use num_bigint::BigInt;
use valuescript_vm::{
operations,
operations, unicode_at,
vs_object::VsObject,
vs_value::{number_to_index, ToVal, Val},
};
@@ -381,6 +381,24 @@ impl FnState {
let key = self.eval_arg(key);
let item = match obj {
Kal::String(string) => match key {
Kal::Number(Number(i)) => match number_to_index(i) {
Some(i) => 'b: {
let string_bytes = string.as_bytes();
if i >= string_bytes.len() {
break 'b Kal::Undefined;
}
match unicode_at(string_bytes, string_bytes.len(), i) {
Some(char) => Kal::String(char.to_string()),
None => Kal::String("".to_string()),
}
}
None => Kal::Undefined,
},
_ => Kal::Unknown,
},
Kal::Array(array) => match key {
Kal::Number(Number(i)) => match number_to_index(i) {
Some(i) => match array.values.get(i) {

View File

@@ -28,6 +28,7 @@ mod vs_symbol;
pub mod vs_value;
pub use bytecode::Bytecode;
pub use string_methods::unicode_at;
pub use virtual_machine::VirtualMachine;
pub use vs_symbol::VsSymbol;
pub use vs_value::{LoadFunctionResult, ValTrait};

View File

@@ -748,7 +748,7 @@ fn last_index_of(string_bytes: &[u8], search_bytes: &[u8], at_least_pos: usize)
None
}
fn unicode_at(bytes: &[u8], len: usize, index: usize) -> Option<char> {
pub fn unicode_at(bytes: &[u8], len: usize, index: usize) -> Option<char> {
match code_point_at(bytes, len, index) {
Some(code_point) => Some(
std::char::from_u32(code_point).expect("Invalid code point"), // TODO: Find out if this is reachable and what to do about it