Skip to main content

libtw2_buffer/impls/
arrayvec.rs

1extern crate arrayvec;
2
3use self::arrayvec::Array;
4use self::arrayvec::ArrayVec;
5use crate::Buffer;
6use crate::BufferRef;
7use crate::ToBufferRef;
8use std::slice;
9
10/// The intermediate step from a `ArrayVec` to a `BufferRef`.
11pub struct ArrayVecBuffer<'data, A: 'data + Array<Item = u8>> {
12    // Will only touch the length of the `ArrayVec` through this reference,
13    // except in `ArrayVecBuffer::buffer`.
14    vec: &'data mut ArrayVec<A>,
15    initialized: usize,
16}
17
18impl<'d, A: Array<Item = u8>> ArrayVecBuffer<'d, A> {
19    fn new(vec: &'d mut ArrayVec<A>) -> ArrayVecBuffer<'d, A> {
20        ArrayVecBuffer {
21            vec: vec,
22            initialized: 0,
23        }
24    }
25    fn buffer<'s>(&'s mut self) -> BufferRef<'d, 's> {
26        let len = self.vec.len();
27        let remaining = self.vec.capacity() - len;
28        unsafe {
29            let start = self.vec.as_mut_ptr().offset(len as isize);
30            // This is unsafe, we now have two unique (mutable) references
31            // to the same `ArrayVec`. However, we will only access
32            // `self.vec.len` through `self` and only the contents through
33            // the `BufferRef`.
34            BufferRef::new(
35                slice::from_raw_parts_mut(start, remaining),
36                &mut self.initialized,
37            )
38        }
39    }
40}
41
42impl<'d, A: Array<Item = u8>> Drop for ArrayVecBuffer<'d, A> {
43    fn drop(&mut self) {
44        let len = self.vec.len();
45        unsafe {
46            self.vec.set_len(len + self.initialized);
47        }
48    }
49}
50
51impl<'d, A: Array<Item = u8>> Buffer<'d> for &'d mut ArrayVec<A> {
52    type Intermediate = ArrayVecBuffer<'d, A>;
53    fn to_to_buffer_ref(self) -> Self::Intermediate {
54        ArrayVecBuffer::new(self)
55    }
56}
57
58impl<'d, A: Array<Item = u8>> ToBufferRef<'d> for ArrayVecBuffer<'d, A> {
59    fn to_buffer_ref<'s>(&'s mut self) -> BufferRef<'d, 's> {
60        self.buffer()
61    }
62}