Rust字符串处理库hipstr的使用,高性能字符串操作与格式化工具
Rust字符串处理库hipstr的使用,高性能字符串操作与格式化工具
hipstr
是Rust的另一种字符串类型,具有以下特点:
- 通过
borrowed
(一个const
构造函数)或from_static
实现无拷贝的借用 - 无分配小字符串(在64位平台上为23字节)
- 无拷贝的拥有切片
- 一个niche:
Option<HipStr>
和HipStr
大小相同 - 零依赖并且兼容
no_std
(带有alloc
)
还支持字节字符串、OS字符串和路径!
⚡ 示例
use hipstr::HipStr;
let simple_greetings = HipStr::from_static("Hello world");
let _clone = simple_greetings.clone(); // 无拷贝
let user = "John";
let greetings = HipStr::from(format!("Hello {}", user));
let user = greetings.slice(6..); // 无拷贝
drop(greetings); // 切片是拥有的,即使greetings消失它仍然存在
let chars = user.chars().count(); // "继承" `&str`方法
✏️ 特性
std
(默认):提供HipOsStr
和HipPath
类型,以及更多trait实现(用于比较和转换)serde
:提供与serde的序列化/反序列化支持borsh
:提供与borsh的序列化/反序列化支持bstr
:提供与BurntSushi的bstr crate的兼容性unstable
:什么都不做,用于展示不稳定的实现细节
☣️ hipstr的安全性
这个crate广泛使用了unsafe
代码块。它利用了大多数平台(目前Rust编译器支持的所有平台?)中指针存在的2位对齐niche来区分三种可能的表示。
为了使事情更安全,Rust在多平台上进行了彻底测试,正常测试和使用Miri(MIR解释器)。
🧪 测试和验证策略
为了确保安全性和可靠性,这个crate经过了彻底的测试:
- 接近100%的测试覆盖率
- 跨平台验证:
- 32位和64位架构
- 小端和大端
此外,这个crate使用高级动态验证方法进行检查:
- 使用Tokio的
loom
crate进行并发测试 - 使用Miri(MIR解释器)检测未定义行为
☔ 覆盖率
这个crate有接近完整的行覆盖率:
cargo llvm-cov --all-features --html
# 或
cargo tarpaulin --all-features --out html --engine llvm
🖥️ 跨平台测试
在Github提供的CI中,hipstr
在以下环境下测试:
- Linux
- Windows
- MacOS(ARM 64位 LE)
你可以使用cross轻松地在各种平台上运行测试:
cross test --target s390x-unknown-linux-gnu # 32位 BE
cross test --target powerpc64-unknown-linux-gnu # 64位 BE
cross test --target i686-unknown-linux-gnu # 32位 LE
cross test --target x86_64-unknown-linux-gnu # 64位 LE
🧵 Loom
这个crate使用loom
crate来检查自定义的"Arc"实现。运行测试:
RUSTFLAGS='--cfg loom' cargo test --release loom
🔍 Miri
这个crate成功运行Miri:
MIRIFLAGS='-Zmiri-symbolic-alignment-check -Zmiri-permissive-provenance' cargo +nightly miri test
for SEED in $(seq 0 10); do
echo "Trying seed: $SEED"
MIRIFLAGS="-Zmiri-seed=$SEED -Zmiri-permissive-provenance" cargo +nightly miri test || { echo "Failing seed: $SEED"; break; };
done
📦 类似crates
#[non_exhaustive]
名称 | TS cheap-clone | Local cheap-clone | Inline | Cheap slice | Bytes | Borrow 'static |
Borrow any 'a |
注释 |
---|---|---|---|---|---|---|---|---|
hipstr |
✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | 显然! |
arcstr |
✓* | - | - | -** | - | ✓ | - | *使用自定义thin Arc ,**重切片(带有专用的子字符串类型) |
flexstr |
✓* | ✓ | ✓ | - | - | ✓ | - | *使用(A)rc<str> 而不是(A)rc<String> (移除一级间接但使用胖指针) |
imstr |
✓ | ✓ | - | ✓ | - | - | - | |
faststr |
✓ | - | ✓ | ✓ | - | ✓ | - | 零文档,复杂API |
fast-str |
✓ | - | ✓ | ✓ | - | ✓ | - | 内联表示是可选的 |
ecow |
✓* | - | ✓ | - | ✓** | ✓ | - | *仅在两个词上🤤,**甚至任何T |
cowstr |
✓ | - | - | -* | - | ✓ | -** | *重切片,**与其名称相反 |
compact_str |
- | - | ✓ | - | ✓* | - | - | *通过smallvec 可选 |
inline_string |
- | - | ✓ | - | - | - | - | |
kstring |
✓ | ✓ | ✓ | - | - | ✓ | ✓* | 安全模式,使用装箱字符串;*带有第二种类型 |
smartstring |
- | - | ✓ | - | - | - | - | |
smallstr |
- | - | ✓ | - | - | - | - | |
smol_str |
- | - | ✓* | - | - | ✓ | - | *但仅内联字符串,作为参考 |
简而言之,HipStr
,一种字符串类型统治它们😉
🏎️ 性能
虽然速度不是hipstr
的主要动机,但它在这方面似乎表现不错。
📖 作者和许可证
目前只有我PoLazarus 👻
欢迎帮助!🚨
MIT + Apache
完整示例代码
use hipstr::HipStr;
fn main() {
// 创建静态字符串(无拷贝)
let static_str = HipStr::from_static("Hello, world!");
println!("Static string: {}", static_str);
// 克隆字符串(无拷贝)
let cloned_str = static_str.clone();
println!("Cloned string: {}", cloned_str);
// 从动态字符串创建
let name = "Alice";
let dynamic_str = HipStr::from(format!("Hello, {}!", name));
println!("Dynamic string: {}", dynamic_str);
// 切片操作(无拷贝)
let slice = dynamic_str.slice(7..12);
println!("Slice: {}", slice); // 输出 "Alice"
// 即使原字符串被丢弃,切片仍然有效
drop(dynamic_str);
println!("Slice after drop: {}", slice);
// 继承&str的所有方法
println!("Character count: {}", slice.chars().count());
println!("Contains 'lic'? {}", slice.contains("lic"));
// 小字符串优化
let small_str = HipStr::from("short");
println!("Is small string: {}", small_str.len() <= 23);
}
这个示例展示了hipstr
的主要功能:
- 从静态字符串创建
- 零成本克隆
- 从动态字符串创建
- 零成本切片操作
- 继承所有
&str
方法 - 小字符串优化
要使用这个库,请在Cargo.toml中添加依赖:
hipstr = "0.8.0"
Rust字符串处理库hipstr的使用指南
hipstr是一个高性能的Rust字符串处理库,专注于提供快速、灵活的字符串操作和格式化功能。它特别适合需要大量字符串处理的场景,如文本解析、数据转换和格式化输出等。
主要特性
- 高性能字符串操作
- 灵活的格式化功能
- 低内存开销
- 与标准库无缝集成
- 支持Unicode
安装
在Cargo.toml中添加依赖:
[dependencies]
hipstr = "0.3"
基本使用方法
创建HipStr
use hipstr::HipStr;
// 从字符串字面量创建
let s1 = HipStr::from("Hello");
// 从String创建
let s2 = HipStr::from(String::from("World"));
// 从&str创建
let s3 = HipStr::from("Rust");
字符串拼接
let hello = HipStr::from("Hello");
let world = HipStr::from("World");
// 使用+操作符拼接
let greeting = hello + " " + &world;
println!("{}", greeting); // 输出: Hello World
高效字符串格式化
use hipstr::format_hip;
let name = "Alice";
let age = 30;
let formatted = format_hip!("{} is {} years old", name, age);
println!("{}", formatted); // 输出: Alice is 30 years old
字符串切片操作
let text = HipStr::from("The quick brown fox");
// 获取子串
let quick = text.slice(4..9);
println!("{}", quick); // 输出: quick
// 分割字符串
let parts: Vec<HipStr> = text.split_whitespace().collect();
for part in parts {
println!("{}", part);
}
字符串替换
let text = HipStr::from("I like apples and apples are tasty");
let replaced = text.replace("apples", "oranges");
println!("{}", replaced); // 输出: I like oranges and oranges are tasty
高级功能
批量字符串处理
use hipstr::{HipStr, HipStrBuf};
let mut buf = HipStrBuf::new();
buf.push_str("Start ");
buf.push_str("middle ");
buf.push_str("end");
let result = buf.into_hip_str();
println!("{}", result); // 输出: Start middle end
性能优化技巧
// 预分配空间
let mut builder = HipStr::builder();
builder.reserve(100);
builder.push_str("This is a long string ");
builder.push_str("that we're building efficiently");
let optimized = builder.build();
与标准库互操作
let hip = HipStr::from("Standard interoperability");
let std_str: &str = hip.as_str();
let std_string: String = hip.into();
完整示例demo
use hipstr::{HipStr, HipStrBuf, format_hip};
fn main() {
// 创建HipStr示例
let s1 = HipStr::from("Hello");
let s2 = HipStr::from(String::from("World"));
let s3 = HipStr::from("Rust");
println!("创建示例: {}, {}, {}", s1, s2, s3);
// 字符串拼接示例
let greeting = s1 + " " + &s2;
println!("拼接结果: {}", greeting);
// 字符串格式化示例
let formatted = format_hip!("{} {} {}", greeting, "from", s3);
println!("格式化结果: {}", formatted);
// 字符串切片示例
let text = HipStr::from("The quick brown fox jumps over the lazy dog");
let quick = text.slice(4..9);
println!("子字符串: {}", quick);
// 字符串分割示例
println!("分割结果:");
for word in text.split_whitespace() {
println!("- {}", word);
}
// 字符串替换示例
let replaced = text.replace("fox", "cat");
println!("替换后: {}", replaced);
// 批量处理示例
let mut buf = HipStrBuf::new();
buf.push_str("批量");
buf.push_str("处理");
buf.push_str("示例");
println!("批量处理: {}", buf.into_hip_str());
// 性能优化示例
let mut builder = HipStr::builder();
builder.reserve(50);
builder.push_str("预分配空间");
builder.push_str("的示例");
println!("优化构建: {}", builder.build());
// 与标准库互操作
let std_str: &str = text.as_str();
let std_string: String = text.into();
println!("标准库互操作: {}, {}", std_str, std_string);
}
性能比较
hipstr在以下场景比标准库String表现更好:
- 大量小字符串拼接
- 频繁的子字符串操作
- 重复的字符串替换
- 格式化多个字符串
注意事项
- 对于非常短的字符串,标准库可能更高效
- 某些操作会触发内部缓存机制,第一次调用可能较慢
- 确保使用最新版本以获得最佳性能
hipstr为Rust开发者提供了一个强大的高性能字符串处理工具,特别适合需要处理大量文本数据的应用程序。