如何获取`&str`之间的字节偏移量 [英] How to get the byte offset between `&str`
问题描述
我有两个 &str
指向同一个字符串,我需要知道它们之间的字节偏移量:
I have two &str
pointing to the same string, and I need to know the byte offset between them:
fn main() {
let foo = " bar";
assert_eq!(offset(foo, foo.trim()), Some(2));
let bar = "baz\nquz";
let mut lines = bar.lines();
assert_eq!(offset(bar, lines.next().unwrap()), Some(0));
assert_eq!(offset(bar, lines.next().unwrap()), Some(4));
assert_eq!(offset(foo, bar), None); // not a sub-string
let quz = "quz".to_owned();
assert_eq!(offset(bar, &quz), None); // not the same string, could also return `Some(4)`, I don't care
}
这与 str::find
基本相同,但由于第二个切片是第一个切片的子切片,我希望更快.如果多行相同,str::find
在 lines()
情况下也不起作用.
This is basically the same as str::find
, but since the second slice is a sub-slice of the first, I would have hoped something faster. Also str::find
won't work in the lines()
case if several lines are identical.
我以为我可以使用一些指针算术来做到这一点,例如 foo.trim().as_ptr() - foo.as_ptr()
但结果是 Sub
未在原始指针上实现.
I thought I could just use some pointer arithmetic to do that with something like foo.trim().as_ptr() - foo.as_ptr()
but it turns out that Sub
is not implemented on raw pointers.
推荐答案
但结果证明
Sub
没有在原始指针上实现.
but it turns out that
Sub
is not implemented on raw pointers.
您可以将指针转换为 usize
以对其进行数学运算:
You can convert the pointer to a usize
to do math on it:
fn main() {
let source = "hello, world";
let a = &source[1..];
let b = &source[5..];
let diff = b.as_ptr() as usize - a.as_ptr() as usize;
println!("{}", diff);
}
<小时>
还有不稳定的方法 offset_from代码>
:
#![feature(ptr_offset_from)]
fn main() {
let source = "hello, world";
let a = &source[1..];
let b = &source[5..];
// I copied this unsafe code from Stack Overflow without
// reading the text that told me how to know if this was safe
let diff = unsafe { b.as_ptr().offset_from(a.as_ptr()) };
println!("{}", diff);
}
请务必阅读此方法的文档,因为它描述了在什么情况下它不会导致未定义的行为.
Please be sure to read the documentation for this method as it describes under what circumstances it will not cause undefined behavior.
这篇关于如何获取`&str`之间的字节偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!