logo
pub fn signed_offset(from: usize, to: usize) -> Result<isize, OffsetError>
Expand description

Calculates the offset between two positions as an isize.

This function exists solely to get the distance between two usizes as an isize with a full range of values.

Examples

use rkyv::rel_ptr::{signed_offset, OffsetError};

assert_eq!(signed_offset(0, 1), Ok(1));
assert_eq!(signed_offset(1, 0), Ok(-1));
assert_eq!(signed_offset(0, isize::MAX as usize), Ok(isize::MAX));
assert_eq!(signed_offset(isize::MAX as usize, 0), Ok(-isize::MAX));
assert_eq!(signed_offset(0, isize::MAX as usize + 1), Err(OffsetError::IsizeOverflow));
assert_eq!(signed_offset(isize::MAX as usize + 1, 0), Ok(isize::MIN));
assert_eq!(signed_offset(0, isize::MAX as usize + 2), Err(OffsetError::IsizeOverflow));
assert_eq!(signed_offset(isize::MAX as usize + 2, 0), Err(OffsetError::IsizeOverflow));