1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use core::fmt;

use crate::buf::{Buf, BufMut};
use crate::error::Error;
use crate::zero_copy::ZeroCopy;

/// An absolute pointer to a location in a [`Buf`].
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Ptr {
    offset: usize,
}

impl Ptr {
    /// A pointer pointing to the start of a buffer.
    pub const ZERO: Self = Self { offset: 0 };

    #[inline]
    pub(crate) fn new(offset: usize) -> Self {
        Self { offset }
    }

    #[inline]
    pub(crate) fn offset(&self) -> usize {
        self.offset
    }
}

impl fmt::Debug for Ptr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Pointer(usize);

        impl fmt::Debug for Pointer {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Pointer::fmt(&(self.0 as *const ()), f)
            }
        }

        f.debug_tuple("Ptr").field(&Pointer(self.offset)).finish()
    }
}

unsafe impl ZeroCopy for Ptr {
    fn write_to<B: ?Sized>(&self, buf: &mut B) -> Result<(), Error>
    where
        B: BufMut,
    {
        buf.write(&self.offset)
    }

    fn read_from(buf: &Buf) -> Result<&Self, Error> {
        // SAFETY: Ptr is repr transparent over usize.
        unsafe { Ok(&*(usize::read_from(buf)? as *const usize).cast()) }
    }

    unsafe fn validate_aligned(_: &Buf) -> Result<(), Error> {
        Ok(())
    }
}