我正在寻找实现这一目标的最佳方法(希望零成本):
fn to_str(str: *const u8, len: usize) -> Option<&str>;
Run Code Online (Sandbox Code Playgroud)
len是字符串的长度,可以或可以不是空终止,并且str是指向该字符串的指针。
我不想拥有该字符串的所有权,只需将其作为 传递&str。
Rust 的引用例如与生命周期&str相关联。此生命周期附加到拥有基础数据的值,通常是像,或数组这样的容器。因此,要获得有效的证书,您需要一个所有者。您不想拥有数据的所有权,因为您不想复制它。然而,拥有并不意味着复制,它只是意味着对变异和销毁数据承担全部责任。StringVec&str
要拥有由来自 C 的指针表示的数据malloc()而不复制数据,您可以包装该指针:
pub struct MyString {
data: *const u8,
length: usize,
}
impl MyString {
// safety: data must point to nul-terminated memory allocated with malloc()
pub unsafe fn new(data: *const u8, length: usize) -> MyString {
// Note: no reallocation happens here, we use `str::from_utf8()` only to
// check whether the pointer contains valid UTF-8.
// If panic is unacceptable, the constructor can return a `Result`
if std::str::from_utf8(std::slice::from_raw_parts(data, length)).is_err() {
panic!("invalid utf-8")
}
MyString { data, length }
}
pub fn as_str(&self) -> &str {
unsafe {
// from_utf8_unchecked is sound because we checked in the constructor
std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.data, self.length))
}
}
}
impl Drop for MyString {
fn drop(&mut self) {
unsafe {
libc::free(self.data as *mut _);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这仅在构造包装器时需要 unsafe MyString::new(),因为它需要一个原始指针,其有效性无法在编译时检查。然后,包装器为您提供&str可以传递的内容,而不会出现任何不安全的情况:
fn main() {
let raw_str = unsafe { libc::strdup(b"foo\0".as_ptr() as _) as *const u8 };
let s = unsafe { MyString::new(raw_str, 3) };
// from here on, it's all-safe code
let slice = s.as_str(); // now you get a slice to pass around
assert_eq!(slice, "foo");
}
Run Code Online (Sandbox Code Playgroud)
如果您不想MyString释放数据,则只需删除该Drop实现即可。无论哪种情况,都有一个安全不变量,即数据在活动new()期间不得被释放。MyString
C 字符串和 Rust 之间的最后一个区别&str是,Rust 字符串保证为 UTF-8,创建非 UTF-8 字符串(只能在不安全的代码中完成)会构成未定义的行为。这就是为什么MyString::new()或MyString::as_str()需要验证字符串是否包含有效的 UTF-8。进行检查new()可确保检查最多完成一次。您可以删除该检查,但随后new()会得到另一个安全不变量,创建字符串的 C 代码不太可能遵守该不变量。
要表示任意二进制数据,您可以使用&[u8]代替,或者使用像bstr&str这样的包,它为您提供“字节字符串”,具有所有便利,但不需要 UTF-8 要求。&str
| 归档时间: |
|
| 查看次数: |
2377 次 |
| 最近记录: |