跳转到内容

String 和 Bytes 方法

String 是合法 UTF-8 文本值。Bytes 是原始字节序列。两者的索引规则不同: string 索引是字节 offset,并且必须落在 UTF-8 边界上;bytes 索引直接访问 u8

String helper 包括 lenis_emptycontainsfindstarts_withends_withstrip_prefixstrip_suffixto_upperto_lowertrimtrim_starttrim_endreplacerepeatslice

fn main() {
let label = " Quest.Gold ".trim().replace(".", "_").to_lower();
let kind = label.slice(0, 5);
let item = label.strip_prefix("quest_").unwrap_or("");
return kind + ":" + item;
}

findstrip_prefixstrip_suffix 返回 Option

splitsplit_linessplit_whitespace 产生数组。split_once 返回 Option<(String, String)>。Parse helper 返回 Option,所以无效输入可以由 脚本处理,不会直接变成 VM trap。

fn main() {
let parts = "count=3 enabled=true".split_whitespace();
let (_, count_text) = parts[0].split_once("=").unwrap_or(("count", "0"));
let (_, enabled_text) = parts[1].split_once("=").unwrap_or(("enabled", "false"));
let count = count_text
.parse_i64()
.unwrap_or(0);
let enabled = enabled_text
.parse_bool()
.unwrap_or(false);
return enabled && count == 3;
}

Unicode scalar value 使用 chars,UTF-8 字节使用 bytes

fn main() {
let first = "gold".chars().next().unwrap_or('\0');
return first.to_string().to_upper();
}

Bytes 支持 lenis_emptyslicegetread_u32_leread_u32_beto_hexitervaluesbytes::from_hex 返回 Result,因为格式错误的 hex 文本有可恢复错误信息。

fn main() {
let decoded = bytes::from_hex("01000000");
let bytes = result::unwrap_or(decoded, b"");
if bytes.len() >= 4 {
return bytes.read_u32_le(0);
}
return 0;
}

越界 byte 读取和非法 string slice 边界是 VM diagnostic,不是 Option