bin_layout/types/
wrapper.rs

1use crate::*;
2use std::{
3    borrow::Cow,
4    cell::{Cell, RefCell},
5    rc::Rc,
6    sync::Arc,
7};
8
9macro_rules! impls {
10    [Encoder for $($name:ty),*] => ($(
11        impl<T: Encoder + ?Sized> Encoder for $name {
12            #[inline]
13            fn encoder(&self, c: &mut impl Write) -> io::Result<()> { (**self).encoder(c) }
14        }
15    )*);
16    [Decoder for $($name:ident),*] => ($(
17        impl<'de, T: Decoder<'de>> Decoder<'de> for $name<T> {
18            #[inline]
19            fn decoder(c: &mut &'de [u8]) -> Result<Self> { T::decoder(c).map(Self::from) }
20        }
21    )*);
22}
23
24impls!(Encoder for &T, &mut T, Box<T>, Rc<T>, Arc<T>);
25impls!(Decoder for Box, Rc, Arc, Cell, RefCell);
26
27macro_rules! impl_sp {
28    [$($name: ident),*] => ($(
29        impl<'de> Decoder<'de> for $name<str> {
30            #[inline] fn decoder(c: &mut &'de [u8]) -> Result<Self> { <&'de str>::decoder(c).map(Self::from) }
31        }
32        impl<'de, T: Decoder<'de>> Decoder<'de> for $name<[T]> {
33            #[inline] fn decoder(c: &mut &'de [u8]) -> Result<Self> { Vec::<T>::decoder(c).map(Self::from) }
34        }
35    )*);
36}
37impl_sp!(Box, Rc, Arc);
38
39impl<T> Encoder for std::marker::PhantomData<T> {
40    #[inline]
41    fn encoder(&self, _: &mut impl Write) -> io::Result<()> {
42        Ok(())
43    }
44}
45
46impl<T> Decoder<'_> for std::marker::PhantomData<T> {
47    #[inline]
48    fn decoder(_: &mut &[u8]) -> Result<Self> {
49        Ok(std::marker::PhantomData)
50    }
51}
52
53impl<T: Encoder + Copy> Encoder for Cell<T> {
54    #[inline]
55    fn encoder(&self, c: &mut impl Write) -> io::Result<()> {
56        self.get().encoder(c)
57    }
58}
59
60impl<T: Encoder> Encoder for RefCell<T> {
61    #[inline]
62    fn encoder(&self, c: &mut impl Write) -> io::Result<()> {
63        self.try_borrow().map_err(invalid_input)?.encoder(c)
64    }
65}
66
67impl<'a, T> Encoder for Cow<'a, T>
68where
69    T: ?Sized + Encoder + ToOwned,
70{
71    fn encoder(&self, c: &mut impl Write) -> io::Result<()> {
72        (**self).encoder(c)
73    }
74}
75
76impl<'de, 'a, T: ?Sized> Decoder<'de> for Cow<'a, T>
77where
78    T: ToOwned,
79    T::Owned: Decoder<'de>,
80{
81    #[inline]
82    fn decoder(c: &mut &'de [u8]) -> Result<Self> {
83        T::Owned::decoder(c).map(Cow::Owned)
84    }
85}