Skip to main content

libtw2_buffer/impls/
slice.rs

1use crate::wildly_unsafe;
2use crate::Buffer;
3use crate::BufferRef;
4use crate::ToBufferRef;
5
6/// The intermediate step from a byte slice to a `BufferRef`.
7pub struct SliceBuffer<'data> {
8    slice: &'data mut [u8],
9    initialized: usize,
10}
11
12impl<'d> SliceBuffer<'d> {
13    fn new(slice: &'d mut [u8]) -> SliceBuffer<'d> {
14        SliceBuffer {
15            slice: slice,
16            initialized: 0,
17        }
18    }
19    fn buffer<'s>(&'s mut self) -> BufferRef<'d, 's> {
20        unsafe {
21            // This is unsafe, we now have two unique (mutable) references to
22            // the same `Vec`. However, we will only access `self.vec.len`
23            // through `self` and only the contents through the `BufferRef`.
24            BufferRef::new(wildly_unsafe(self.slice), &mut self.initialized)
25        }
26    }
27}
28
29impl<'d> Buffer<'d> for &'d mut [u8] {
30    type Intermediate = SliceBuffer<'d>;
31    fn to_to_buffer_ref(self) -> Self::Intermediate {
32        SliceBuffer::new(self)
33    }
34}
35
36impl<'d> ToBufferRef<'d> for SliceBuffer<'d> {
37    fn to_buffer_ref<'s>(&'s mut self) -> BufferRef<'d, 's> {
38        self.buffer()
39    }
40}