refactor: unify string helpers and pattern2 derived slot

This commit is contained in:
2025-12-28 13:22:02 +09:00
parent 84e1cd7c7b
commit 10e6a15552
41 changed files with 2044 additions and 585 deletions

View File

@ -13,6 +13,7 @@
* - `toLowerCase()` - 小文字変換
* - `trim()` - 前後の空白除去
* - `indexOf(search)` - 文字列検索
* - `indexOf(search, fromIndex)` - 指定位置から検索
* - `replace(from, to)` - 文字列置換
* - `charAt(index)` - 指定位置の文字取得
*
@ -71,18 +72,18 @@ impl StringBox {
/// Env gate: NYASH_STR_CP=1 → return codepoint index; default is byte index
pub fn find(&self, search: &str) -> Box<dyn NyashBox> {
use crate::boxes::integer_box::IntegerBox;
match self.value.find(search) {
Some(byte_pos) => {
let use_cp = std::env::var("NYASH_STR_CP").ok().as_deref() == Some("1");
let idx = if use_cp {
self.value[..byte_pos].chars().count() as i64
} else {
byte_pos as i64
};
Box::new(IntegerBox::new(idx))
}
None => Box::new(IntegerBox::new(-1)),
}
let mode = crate::boxes::string_ops::index_mode_from_env();
let idx = crate::boxes::string_ops::index_of(&self.value, search, None, mode);
Box::new(IntegerBox::new(idx))
}
/// Find substring starting from a given index (or -1 if not found)
/// Env gate: NYASH_STR_CP=1 → indices are codepoint-based; default is byte index
pub fn find_from(&self, search: &str, start: i64) -> Box<dyn NyashBox> {
use crate::boxes::integer_box::IntegerBox;
let mode = crate::boxes::string_ops::index_mode_from_env();
let idx = crate::boxes::string_ops::index_of(&self.value, search, Some(start), mode);
Box::new(IntegerBox::new(idx))
}
/// Replace all occurrences of old with new
@ -94,18 +95,9 @@ impl StringBox {
/// Env gate: NYASH_STR_CP=1 → return codepoint index; default is byte index.
pub fn lastIndexOf(&self, search: &str) -> Box<dyn NyashBox> {
use crate::boxes::integer_box::IntegerBox;
match self.value.rfind(search) {
Some(byte_pos) => {
let use_cp = std::env::var("NYASH_STR_CP").ok().as_deref() == Some("1");
let idx = if use_cp {
self.value[..byte_pos].chars().count() as i64
} else {
byte_pos as i64
};
Box::new(IntegerBox::new(idx))
}
None => Box::new(IntegerBox::new(-1)),
}
let mode = crate::boxes::string_ops::index_mode_from_env();
let idx = crate::boxes::string_ops::last_index_of(&self.value, search, mode);
Box::new(IntegerBox::new(idx))
}
/// Trim whitespace from both ends