I would like to calculate the offset difference between pointer, it is fine for u8
type, but it fails to return correct value for structure.
#![feature(ptr_offset_from)]
#![allow(unused)]
#![allow(unused_variables)]
#[derive(Default, Debug, Clone)]
pub struct Node {
pub key: u64,
pub value: u32,
pub color: u16,
pub number: u8,
}
fn main() {
println!("Node::size = {}", std::mem::size_of::<Node>());
let a: Vec<u8> = vec![2, 3, 4];
let ptr0: *const u8 = &a[0];
let ptr2: *const u8 = &a[2];
unsafe { println!("offset_from 0 = {}", ptr2.offset_from(ptr0)) }
let ptr0: *const Node = &a[0] as *const u8 as *const Node;
let ptr2: *const Node = &a[2] as *const u8 as *const Node;
unsafe { println!("offset_from 0 = {}", ptr2.offset_from(ptr0)) }
}
output
Node::size = 16
offset_from 0 = 2
offset_from 0 = 0
// expect
Node::size = 16
offset_from 0 = 2
offset_from 0 = 2
any workaround for this?
Note: This is a nightly-only experimental API, is this the reason that this output appears?