Skip to main content

oneliner_runtime/
buffer.rs

1use super::Error;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum Access {
5    Ro,
6    Wo,
7    Rw,
8    Unknown,
9}
10
11#[derive(Clone, Copy)]
12pub struct Buffer {
13    pub ptr: *const u8,
14    pub len: usize,
15}
16
17impl Buffer {
18    pub fn new(ptr: *const u8, len: usize) -> Self {
19        Self::try_new(ptr, len).expect("invalid buffer reference")
20    }
21
22    fn try_new(ptr: *const u8, len: usize) -> Result<Self, Error> {
23        if ptr.is_null() {
24            return Err(Error::NullPointer);
25        }
26        Ok(Self { ptr, len })
27    }
28}
29
30#[derive(Clone, Copy)]
31pub struct BufferMut {
32    pub ptr: *mut u8,
33    pub len: usize,
34}
35
36impl BufferMut {
37    pub fn new(ptr: *mut u8, len: usize) -> Self {
38        Self::try_new(ptr, len).expect("invalid buffer reference")
39    }
40
41    fn try_new(ptr: *mut u8, len: usize) -> Result<Self, Error> {
42        if ptr.is_null() {
43            return Err(Error::NullPointer);
44        }
45        Ok(Self { ptr, len })
46    }
47}
48
49/// Converts a generated storage item into the `BufferRef` used by dispatch.
50///
51/// Input: a raw pointer to the generated storage item.
52/// Output: a `BufferRef` pointing at the buffer bytes.
53pub trait BufferSource {
54    /// Builds a `BufferRef` from a raw pointer to the implementing type.
55    ///
56    /// Input: pointer to converter-generated storage.
57    /// Output: buffer pointer and byte length.
58    ///
59    /// Safety: `ptr` must point to a valid value of `Self`.
60    unsafe fn to_buffer_ref(&self) -> Buffer;
61    unsafe fn to_buffer_mut(&mut self) -> BufferMut;
62}
63
64impl<const N: usize> BufferSource for [u8; N] {
65    /// Treats a static byte array as a buffer buffer.
66    ///
67    /// Input: pointer to `[u8; N]`.
68    /// Output: `BufferRef` with the array pointer and fixed length `N`.
69    ///
70    /// Safety: `ptr` must point to a valid byte array.
71    unsafe fn to_buffer_ref(&self) -> Buffer {
72        Buffer {
73            ptr: self as *const u8,
74            len: N,
75        }
76    }
77    unsafe fn to_buffer_mut(&mut self) -> BufferMut {
78        BufferMut {
79            ptr: self as *mut u8,
80            len: N,
81        }
82    }
83}
84
85#[derive(Clone, Copy)]
86pub struct BufferRange<T> {
87    pub buffer: T,
88    pub access: Access,
89    pub offset: usize,
90    pub length: usize,
91}
92
93#[derive(Clone, Copy)]
94pub enum AnyBuffer {
95    Ref(Buffer),
96    Mut(BufferMut),
97}
98
99impl AnyBuffer {
100    pub fn len(&self) -> usize {
101        match self {
102            AnyBuffer::Ref(t) => t.len,
103            AnyBuffer::Mut(t) => t.len,
104        }
105    }
106}
107
108impl From<Buffer> for AnyBuffer {
109    fn from(t: Buffer) -> Self {
110        AnyBuffer::Ref(t)
111    }
112}
113
114impl From<BufferMut> for AnyBuffer {
115    fn from(t: BufferMut) -> Self {
116        AnyBuffer::Mut(t)
117    }
118}
119
120pub type AnyBufferRange = BufferRange<AnyBuffer>;
121
122impl AnyBufferRange {
123    pub fn new(buffer: AnyBuffer, access: Access, offset: usize, length: usize) -> Self {
124        Self::try_new(buffer, access, offset, length).expect("invalid buffer range")
125    }
126
127    pub fn try_new(
128        buffer: AnyBuffer,
129        access: Access,
130        offset: usize,
131        length: usize,
132    ) -> Result<Self, Error> {
133        let buffer_len = buffer.len();
134
135        let end = offset
136            .checked_add(length)
137            .ok_or(Error::BufferRangeOutOfBounds {
138                offset,
139                length,
140                capacity: buffer_len,
141            })?;
142
143        if end > buffer_len {
144            return Err(Error::BufferRangeOutOfBounds {
145                offset,
146                length,
147                capacity: buffer_len,
148            });
149        }
150
151        let access_valid = matches!(
152            (buffer, access),
153            (AnyBuffer::Ref(_), Access::Ro)
154                | (AnyBuffer::Mut(_), Access::Ro)
155                | (AnyBuffer::Mut(_), Access::Wo)
156                | (AnyBuffer::Mut(_), Access::Rw)
157        );
158
159        if !access_valid {
160            return Err(Error::InvalidAccess {
161                access,
162                required: match buffer {
163                    AnyBuffer::Ref(_) => Access::Ro,
164                    AnyBuffer::Mut(_) => Access::Rw,
165                },
166            });
167        }
168
169        Ok(Self {
170            buffer: buffer,
171            access,
172            offset,
173            length,
174        })
175    }
176}
177
178/// Runs a group of generated commands sequentially.
179///
180/// Input: closure containing generated command calls.
181/// Output: no value; all effects are performed by the closure.
182pub fn concurrent<T>(commands: impl FnOnce() -> T) -> T {
183    commands()
184}
185
186/// Converts scalar fill values to the byte written by `fill`.
187///
188/// Input: scalar value.
189/// Output: low byte used to fill a buffer range.
190pub trait FillValue {
191    /// Converts this scalar into a byte fill value.
192    ///
193    /// Input: `self`.
194    /// Output: `u8` value passed to `write_bytes`.
195    fn to_u8(self) -> u8;
196}
197
198macro_rules! impl_fill_value {
199    ($($ty:ty),* $(,)?) => {
200        $(
201            impl FillValue for $ty {
202                /// Converts this integer into the byte used by `fill`.
203                ///
204                /// Input: integer value.
205                /// Output: low byte of the integer.
206                fn to_u8(self) -> u8 {
207                    self as u8
208                }
209            }
210        )*
211    };
212}
213
214impl_fill_value!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
215
216/// Fills a generated buffer range with one byte value.
217///
218/// # Safety
219///
220/// The buffer pointer must be valid and writable for the declared range.
221pub unsafe fn fill(target: AnyBufferRange, value: impl FillValue + Copy) -> Result<(), Error> {
222    match target.buffer {
223        AnyBuffer::Ref(_) => {
224            return Err(Error::InvalidAccess {
225                access: target.access,
226                required: Access::Rw,
227            });
228        }
229        AnyBuffer::Mut(buffer) => unsafe {
230            core::ptr::write_bytes(buffer.ptr.add(target.offset), value.to_u8(), target.length);
231        },
232    }
233
234    Ok(())
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    fn mutable_buffer(capacity: usize) -> AnyBuffer {
242        BufferMut {
243            ptr: core::ptr::dangling_mut(),
244            len: capacity,
245        }
246        .into()
247    }
248
249    #[test]
250    fn validates_buffer_ranges() {
251        let range = AnyBufferRange::try_new(mutable_buffer(16), Access::Rw, 4, 8).unwrap();
252        assert_eq!(range.offset, 4);
253        assert_eq!(range.length, 8);
254
255        assert!(AnyBufferRange::try_new(mutable_buffer(16), Access::Rw, 4, 0).is_ok());
256        assert!(matches!(
257            AnyBufferRange::try_new(mutable_buffer(16), Access::Rw, 17, 0),
258            Err(Error::BufferRangeOutOfBounds { .. })
259        ));
260        assert!(matches!(
261            AnyBufferRange::try_new(mutable_buffer(16), Access::Rw, 8, 9),
262            Err(Error::BufferRangeOutOfBounds { .. })
263        ));
264    }
265}