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
extern crate arrayvec;
use Buffer;
use BufferRef;
use ToBufferRef;
use self::arrayvec::Array;
use self::arrayvec::ArrayVec;
use std::slice;
pub struct ArrayVecBuffer<'data, A: 'data+Array<Item=u8>> {
vec: &'data mut ArrayVec<A>,
initialized: usize,
}
impl<'d, A: Array<Item=u8>> ArrayVecBuffer<'d, A> {
fn new(vec: &'d mut ArrayVec<A>) -> ArrayVecBuffer<'d, A> {
ArrayVecBuffer {
vec: vec,
initialized: 0,
}
}
fn buffer<'s>(&'s mut self) -> BufferRef<'d, 's> {
let len = self.vec.len();
let remaining = self.vec.capacity() - len;
unsafe {
let start = self.vec.as_mut_ptr().offset(len as isize);
BufferRef::new(slice::from_raw_parts_mut(start, remaining),
&mut self.initialized)
}
}
}
impl<'d, A: Array<Item=u8>> Drop for ArrayVecBuffer<'d, A> {
fn drop(&mut self) {
let len = self.vec.len();
unsafe {
self.vec.set_len(len + self.initialized);
}
}
}
impl<'d, A: Array<Item=u8>> Buffer<'d> for &'d mut ArrayVec<A> {
type Intermediate = ArrayVecBuffer<'d, A>;
fn to_to_buffer_ref(self) -> Self::Intermediate {
ArrayVecBuffer::new(self)
}
}
impl<'d, A: Array<Item=u8>> ToBufferRef<'d> for ArrayVecBuffer<'d, A> {
fn to_buffer_ref<'s>(&'s mut self) -> BufferRef<'d, 's> {
self.buffer()
}
}