From 4e1a72796c8390d76f42d3b4002ead1141317f7b Mon Sep 17 00:00:00 2001 From: Victor Koenders Date: Sat, 16 Oct 2021 12:08:29 +0200 Subject: [PATCH] Added support for Cow, Rc and Arc --- src/features/impl_alloc.rs | 65 +++++++++++++++++++++++++++++++++++--- tests/alloc.rs | 9 ++++++ 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/src/features/impl_alloc.rs b/src/features/impl_alloc.rs index bbe3d1f..53fa85b 100644 --- a/src/features/impl_alloc.rs +++ b/src/features/impl_alloc.rs @@ -5,7 +5,7 @@ use crate::{ error::{DecodeError, EncodeError}, Config, }; -use alloc::{boxed::Box, vec::Vec}; +use alloc::{borrow::Cow, boxed::Box, rc::Rc, sync::Arc, vec::Vec}; #[derive(Default)] struct VecWriter { @@ -35,7 +35,7 @@ pub fn encode_to_vec_with_config( Ok(encoder.into_writer().inner) } -impl<'de, T> Decodable for Vec +impl Decodable for Vec where T: Decodable, { @@ -62,7 +62,7 @@ where } } -impl<'de, T> Decodable for Box +impl Decodable for Box where T: Decodable, { @@ -81,7 +81,7 @@ where } } -impl<'de, T> Decodable for Box<[T]> +impl Decodable for Box<[T]> where T: Decodable, { @@ -103,3 +103,60 @@ where Ok(()) } } + +impl<'cow, T> Decodable for Cow<'cow, T> +where + T: Decodable + Clone, +{ + fn decode(decoder: D) -> Result { + let t = T::decode(decoder)?; + Ok(Cow::Owned(t)) + } +} + +impl<'cow, T> Encodeable for Cow<'cow, T> +where + T: Encodeable + Clone, +{ + fn encode(&self, encoder: E) -> Result<(), EncodeError> { + self.as_ref().encode(encoder) + } +} + +impl Decodable for Rc +where + T: Decodable, +{ + fn decode(decoder: D) -> Result { + let t = T::decode(decoder)?; + Ok(Rc::new(t)) + } +} + +impl Encodeable for Rc +where + T: Encodeable, +{ + fn encode(&self, encoder: E) -> Result<(), EncodeError> { + T::encode(self, encoder) + } +} + +impl Decodable for Arc +where + T: Decodable, +{ + fn decode(decoder: D) -> Result { + let t = T::decode(decoder)?; + Ok(Arc::new(t)) + } +} + +impl Encodeable for Arc +where + T: Encodeable, +{ + fn encode(&self, encoder: E) -> Result<(), EncodeError> { + T::encode(self, encoder) + } +} diff --git a/tests/alloc.rs b/tests/alloc.rs index e051d77..2118b65 100644 --- a/tests/alloc.rs +++ b/tests/alloc.rs @@ -1,7 +1,12 @@ #![cfg(feature = "alloc")] +extern crate alloc; + mod utils; +use alloc::borrow::Cow; +use alloc::rc::Rc; +use alloc::sync::Arc; use utils::the_same; struct Foo { @@ -44,4 +49,8 @@ fn test_alloc_commons() { the_same::>(vec![1, 2, 3, 4, 5]); the_same(Box::::new(5)); the_same(Box::<[u32]>::from(vec![1, 2, 3, 4, 5])); + the_same(Cow::::Owned(5)); + the_same(Cow::::Borrowed(&5)); + the_same(Rc::::new(5)); + the_same(Arc::::new(5)); }