Skip to content

Commit 287bff3

Browse files
committed
Add builtin str_find
1 parent 0a2879f commit 287bff3

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/_builtins.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use crate::builtin::Builtin;
77

88
/*GENERATE cargo run -- _builtins.tok -- `find . -name "*.rs"` */
9-
pub static BUILTINS: [Builtin; 64] = [
9+
pub static BUILTINS: [Builtin; 65] = [
1010
Builtin {
1111
name: "Float",
1212
func: crate::value::token::tokay_token_float,
@@ -219,6 +219,10 @@ pub static BUILTINS: [Builtin; 64] = [
219219
name: "str_endswith",
220220
func: crate::value::str::Str::tokay_method_str_endswith,
221221
},
222+
Builtin {
223+
name: "str_find",
224+
func: crate::value::str::Str::tokay_method_str_find,
225+
},
222226
Builtin {
223227
name: "str_get_item",
224228
func: crate::value::str::Str::tokay_method_str_get_item,

src/value/str.rs

+28
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,34 @@ impl Str {
135135
Ok(RefValue::from(string))
136136
});
137137

138+
tokay_method!("str_find : @s, pat, start=0, end=void", {
139+
if !s.is("str") {
140+
s = RefValue::from(s.to_string());
141+
}
142+
143+
let string = s.borrow();
144+
145+
let string = string.object::<Str>().unwrap().as_str();
146+
let pat = pat.borrow().to_string();
147+
let start = start.to_usize().unwrap_or(0);
148+
149+
let end = if end.is_void() {
150+
string.len()
151+
} else {
152+
end.to_usize().unwrap_or(string.len())
153+
};
154+
155+
if start > end {
156+
return Ok(value!(-1));
157+
}
158+
159+
Ok(if let Some(index) = string[start..end].find(&pat) {
160+
value!(start + index)
161+
} else {
162+
value!(-1)
163+
})
164+
});
165+
138166
tokay_method!("str_endswith : @s, postfix", {
139167
if !s.is("str") {
140168
s = RefValue::from(s.to_string());

0 commit comments

Comments
 (0)