13

Some C interfaces return pointer to end of buffer. So then I need to convert the range to a slice. But slice can only be created from pointer and count. So how do I get the count.

Writing end - start simply gives me error: binary operation `-` cannot be applied to type `*mut i8` and std::ptr::PtrExt only has offset method to calculate end from the offset, but not the inverse operation.

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172

2 Answers2

14

A raw pointer can be cast to usize; you can then perform subtraction on those.

end as usize - start as usize
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • I don’t think that adding a method for it would be the right thing to do, but implementing `Sub<*const T, Output = isize>` for `*const T` mightn’t be such a bad idea. – Chris Morgan Mar 07 '15 at 03:22
  • 3
    Note that for x : *mut T, y = x.offset(z), then (y as usize - x as usize) == z * size_of::() as opposed to being equal to exactly z. – DanielV Dec 23 '19 at 18:53
14

Since 1.47.0 (October 2020), Rust has the offset_from method on the pointer type, allowing you to write:

let offset: isize = end.offset_from(start);

to get the offset from start to end.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
davidg
  • 5,868
  • 2
  • 33
  • 51