mirror of
https://github.com/voltrevo/ValueScript.git
synced 2026-01-14 16:08:02 -05:00
includes
This commit is contained in:
@@ -47,6 +47,7 @@ pub fn get_string_method(method: &str) -> Val {
|
||||
"codePointAt" => Val::Static(&CODE_POINT_AT),
|
||||
"concat" => Val::Static(&CONCAT),
|
||||
"endsWith" => Val::Static(&ENDS_WITH),
|
||||
"includes" => Val::Static(&INCLUDES),
|
||||
_ => Val::Undefined,
|
||||
}
|
||||
}
|
||||
@@ -156,6 +157,61 @@ static ENDS_WITH: NativeFunction = NativeFunction {
|
||||
},
|
||||
};
|
||||
|
||||
static INCLUDES: NativeFunction = NativeFunction {
|
||||
fn_: |this: &mut Val, params: Vec<Val>| -> Val {
|
||||
match this {
|
||||
Val::String(string_data) => {
|
||||
let string_bytes = string_data.as_bytes();
|
||||
|
||||
let search_string = match params.get(0) {
|
||||
Some(s) => s.val_to_string(),
|
||||
_ => return Val::Bool(false),
|
||||
};
|
||||
|
||||
let start_pos = match params.get(1) {
|
||||
Some(p) => match p.to_index() {
|
||||
// FIXME: to_index isn't quite right here
|
||||
None => return Val::Bool(false),
|
||||
Some(i) => i,
|
||||
},
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
let search_bytes = search_string.as_bytes();
|
||||
|
||||
let search_length = search_bytes.len();
|
||||
|
||||
if search_length == 0 {
|
||||
// TODO: Even if start_pos is out of bounds?
|
||||
return Val::Bool(true);
|
||||
}
|
||||
|
||||
if start_pos + search_length > string_bytes.len() {
|
||||
return Val::Bool(false);
|
||||
}
|
||||
|
||||
for i in start_pos..(string_bytes.len() - search_length + 1) {
|
||||
let mut found = true;
|
||||
|
||||
for j in 0..search_length {
|
||||
if string_bytes[i + j] != search_bytes[j] {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
return Val::Bool(true);
|
||||
}
|
||||
}
|
||||
|
||||
Val::Bool(false)
|
||||
}
|
||||
_ => std::panic!("Not implemented: exceptions/string indirection"),
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
fn unicode_at(bytes: &[u8], index: usize) -> Option<String> {
|
||||
match code_point_at(bytes, index) {
|
||||
Some(code_point) => Some(
|
||||
|
||||
Reference in New Issue
Block a user