How to get the byte offset between `&str`

后端 未结 2 1092
甜味超标
甜味超标 2020-12-07 02:37

I have two &str pointing to the same string, and I need to know the byte offset between them:

fn main() {
    let foo = \"  bar\";
         


        
相关标签:
2条回答
  • 2020-12-07 03:08

    This is of course kind of unsafe, but if you want arithmetic, you can just cast the pointers to usize with as and subtract that.

    (Note: it's not so unsafe that the compiler will actually complain.)

    0 讨论(0)
  • 2020-12-07 03:23

    but it turns out that Sub is not implemented on raw pointers.

    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);
    }
    

    There's also the unstable method 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.

    0 讨论(0)
提交回复
热议问题