From e4025193ef0e26f57849271acd68a985451a8f47 Mon Sep 17 00:00:00 2001 From: Valentin Date: Sat, 1 Feb 2025 12:21:55 +0100 Subject: [PATCH] in to_extend take collection by mutable reference Currently the function takes the collection by value. Taking by mutable reference is better because it is more flexible. Whenever you have a value, you can also pass by mutable reference, but sometimes you only have a mutable reference and cannot pass by value. This also fixes another problem with the current API: It keeps the collection on error. On success it returns it to the caller, but on error it does not. This makes the caller lose the collection. --- source/postcard/src/ser/flavors.rs | 14 +++++++------- source/postcard/src/ser/mod.rs | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/source/postcard/src/ser/flavors.rs b/source/postcard/src/ser/flavors.rs index 7bca90ef..8434b9bd 100644 --- a/source/postcard/src/ser/flavors.rs +++ b/source/postcard/src/ser/flavors.rs @@ -213,25 +213,25 @@ impl IndexMut for Slice<'_> { } /// Wrapper over a [`core::iter::Extend`] that implements the flavor trait -pub struct ExtendFlavor { - iter: T, +pub struct ExtendFlavor<'a, T> { + iter: &'a mut T, } -impl ExtendFlavor +impl<'a, T> ExtendFlavor<'a, T> where T: core::iter::Extend, { /// Create a new [`Self`] flavor from a given [`core::iter::Extend`] - pub fn new(iter: T) -> Self { + pub fn new(iter: &'a mut T) -> Self { Self { iter } } } -impl Flavor for ExtendFlavor +impl Flavor for ExtendFlavor<'_, T> where T: core::iter::Extend, { - type Output = T; + type Output = (); #[inline(always)] fn try_push(&mut self, data: u8) -> Result<()> { @@ -246,7 +246,7 @@ where } fn finalize(self) -> Result { - Ok(self.iter) + Ok(()) } } diff --git a/source/postcard/src/ser/mod.rs b/source/postcard/src/ser/mod.rs index e2fa32ac..a01fcdf0 100644 --- a/source/postcard/src/ser/mod.rs +++ b/source/postcard/src/ser/mod.rs @@ -262,11 +262,11 @@ where /// use postcard::to_extend; /// let mut vec = Vec::new(); /// -/// let ser = to_extend(&true, vec).unwrap(); -/// let vec = to_extend("Hi!", ser).unwrap(); +/// to_extend(&true, &mut vec).unwrap(); +/// to_extend("Hi!", &mut vec).unwrap(); /// assert_eq!(&vec[0..5], &[0x01, 0x03, b'H', b'i', b'!']); /// ``` -pub fn to_extend(value: &T, writer: W) -> Result +pub fn to_extend(value: &T, writer: &mut W) -> Result<()> where T: Serialize + ?Sized, W: core::iter::Extend,