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
60
61
62
63
use crate::{builder::Builder, traits::*, Cursor, Offset};
use core::mem::MaybeUninit;

impl<T: ?Sized> Primitive for Offset<T> {
    const ALIGNMENT: usize = 4;
    const SIZE: usize = 4;
}

impl<T: ?Sized> WriteAsPrimitive<Offset<T>> for Offset<T> {
    #[inline]
    fn write<const N: usize>(&self, cursor: Cursor<'_, N>, buffer_position: u32) {
        cursor
            .assert_size()
            .finish(u32::to_le_bytes(buffer_position - self.offset));
    }
}

impl<T: ?Sized> WriteAsOffset<T> for Offset<T> {
    fn prepare(&self, _builder: &mut Builder) -> Offset<T> {
        *self
    }
}

impl<T: ?Sized> WriteAs<Offset<T>> for Offset<T> {
    type Prepared = Self;
    #[inline]
    fn prepare(&self, _builder: &mut Builder) -> Self {
        *self
    }
}

impl<T: ?Sized> WriteAsOptional<Offset<T>> for Offset<T> {
    type Prepared = Self;
    #[inline]
    fn prepare(&self, _builder: &mut Builder) -> Option<Self> {
        Some(*self)
    }
}

impl<T: ?Sized> VectorWrite<Offset<T>> for Offset<T> {
    const STRIDE: usize = 4;
    type Value = Offset<T>;

    #[inline]
    fn prepare(&self, _builder: &mut Builder) -> Self::Value {
        *self
    }

    #[inline]
    unsafe fn write_values(
        values: &[Offset<T>],
        bytes: *mut MaybeUninit<u8>,
        buffer_position: u32,
    ) {
        let bytes = bytes as *mut [MaybeUninit<u8>; 4];
        for (i, v) in values.iter().enumerate() {
            v.write(
                Cursor::new(&mut *bytes.add(i)),
                buffer_position - (Self::STRIDE * i) as u32,
            );
        }
    }
}