buffer/impls/
arrayvec.rs

1extern crate arrayvec;
2
3use Buffer;
4use BufferRef;
5use ToBufferRef;
6use self::arrayvec::Array;
7use self::arrayvec::ArrayVec;
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(slice::from_raw_parts_mut(start, remaining),
35                           &mut self.initialized)
36        }
37    }
38}
39
40impl<'d, A: Array<Item=u8>> Drop for ArrayVecBuffer<'d, A> {
41    fn drop(&mut self) {
42        let len = self.vec.len();
43        unsafe {
44            self.vec.set_len(len + self.initialized);
45        }
46    }
47}
48
49impl<'d, A: Array<Item=u8>> Buffer<'d> for &'d mut ArrayVec<A> {
50    type Intermediate = ArrayVecBuffer<'d, A>;
51    fn to_to_buffer_ref(self) -> Self::Intermediate {
52        ArrayVecBuffer::new(self)
53    }
54}
55
56impl<'d, A: Array<Item=u8>> ToBufferRef<'d> for ArrayVecBuffer<'d, A> {
57    fn to_buffer_ref<'s>(&'s mut self) -> BufferRef<'d, 's> {
58        self.buffer()
59    }
60}