tree_buf/internal/rust_std/
smart_pointers.rs

1use crate::prelude::*;
2use std::ops::Deref;
3
4// TODO: impl Encodable for () {
5#[cfg(feature = "encode")]
6#[derive(Default)]
7pub struct BoxEncoderArray<T> {
8    inner: T,
9}
10
11#[cfg(feature = "encode")]
12impl<T: Encodable> Encodable for Box<T> {
13    type EncoderArray = BoxEncoderArray<T::EncoderArray>;
14    fn encode_root<O: EncodeOptions>(&self, stream: &mut EncoderStream<'_, O>) -> RootTypeId {
15        self.deref().encode_root(stream)
16    }
17}
18
19#[cfg(feature = "decode")]
20pub struct BoxDecoderArray<T> {
21    inner: T,
22}
23
24#[cfg(feature = "decode")]
25impl<T: Decodable> Decodable for Box<T> {
26    type DecoderArray = BoxDecoderArray<T::DecoderArray>;
27    fn decode(sticks: DynRootBranch<'_>, options: &impl DecodeOptions) -> DecodeResult<Self> {
28        Ok(Box::new(T::decode(sticks, options)?))
29    }
30}
31
32#[cfg(feature = "encode")]
33impl<T: Encodable> EncoderArray<Box<T>> for BoxEncoderArray<T::EncoderArray> {
34    fn buffer_one<'a, 'b: 'a>(&'a mut self, value: &'b Box<T>) {
35        self.inner.buffer_one(&value)
36    }
37    fn flush<O: EncodeOptions>(self, stream: &mut EncoderStream<'_, O>) -> ArrayTypeId {
38        self.inner.flush(stream)
39    }
40}
41
42#[cfg(feature = "decode")]
43impl<T: DecoderArray> DecoderArray for BoxDecoderArray<T> {
44    type Decode = Box<T::Decode>;
45    type Error = T::Error;
46    fn new(sticks: DynArrayBranch<'_>, options: &impl DecodeOptions) -> DecodeResult<Self> {
47        Ok(BoxDecoderArray { inner: T::new(sticks, options)? })
48    }
49    fn decode_next(&mut self) -> Result<Self::Decode, Self::Error> {
50        Ok(Box::new(self.inner.decode_next()?))
51    }
52}