Skip to main content

libtw2_buffer/impls/
cap_at.rs

1use crate::Buffer;
2use crate::BufferRef;
3use crate::CapAtImpl;
4use crate::ToBufferRef;
5use std::marker::PhantomData;
6
7/// The result of a `cap_at` call on a buffer.
8///
9/// See its documentation for more info.
10pub struct CapAt<'data, T: Buffer<'data>> {
11    buf: T,
12    cap_at: usize,
13    phantom: PhantomData<&'data ()>,
14}
15
16impl<'data, T: Buffer<'data>> CapAtImpl<'data> for T {
17    fn cap_at_impl(self, len: usize) -> CapAt<'data, Self> {
18        CapAt {
19            buf: self,
20            cap_at: len,
21            phantom: PhantomData,
22        }
23    }
24}
25
26/// The intermediate step from a `CapAt` to a `BufferRef`.
27pub struct CapAtBuffer<'data, T: ToBufferRef<'data>> {
28    intermediate: T,
29    cap_at: usize,
30    phantom: PhantomData<&'data ()>,
31}
32
33impl<'data, T: ToBufferRef<'data>> CapAtBuffer<'data, T> {
34    fn new<U: Buffer<'data, Intermediate = T>>(cap_at: CapAt<'data, U>) -> CapAtBuffer<'data, T> {
35        CapAtBuffer {
36            intermediate: cap_at.buf.to_to_buffer_ref(),
37            cap_at: cap_at.cap_at,
38            phantom: PhantomData,
39        }
40    }
41    fn buffer<'size>(&'size mut self) -> BufferRef<'data, 'size> {
42        self.intermediate.to_buffer_ref().cap_at(self.cap_at)
43    }
44}
45
46impl<'data, T: Buffer<'data>> Buffer<'data> for CapAt<'data, T> {
47    type Intermediate = CapAtBuffer<'data, T::Intermediate>;
48    fn to_to_buffer_ref(self) -> Self::Intermediate {
49        CapAtBuffer::new(self)
50    }
51}
52
53impl<'data, T: ToBufferRef<'data>> ToBufferRef<'data> for CapAtBuffer<'data, T> {
54    fn to_buffer_ref<'size>(&'size mut self) -> BufferRef<'data, 'size> {
55        self.buffer()
56    }
57}