From 696cb078deb6b33399dd0ee6011567307cbfc196 Mon Sep 17 00:00:00 2001 From: "Augusto F. Hack" Date: Fri, 1 Dec 2023 17:58:50 +0100 Subject: [PATCH] serde: add support for arrays --- utils/core/src/serde/mod.rs | 50 +++++++++---------------------------- 1 file changed, 12 insertions(+), 38 deletions(-) diff --git a/utils/core/src/serde/mod.rs b/utils/core/src/serde/mod.rs index 471aa96c7..ed84ea3d2 100644 --- a/utils/core/src/serde/mod.rs +++ b/utils/core/src/serde/mod.rs @@ -3,7 +3,7 @@ // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. -use super::{flatten_slice_elements, DeserializationError, Vec}; +use super::{DeserializationError, Vec}; mod byte_reader; pub use byte_reader::{ByteReader, SliceReader}; @@ -197,43 +197,15 @@ impl Serializable for &Vec { } } -impl Serializable for String { - fn write_into(&self, target: &mut W) { - target.write_u64(self.len() as u64); - target.write_bytes(self.as_bytes()); - } -} - -impl Serializable for &String { - fn write_into(&self, target: &mut W) { - (*self).write_into(target) - } -} - -impl Serializable for Vec<[T; N]> { - fn write_into(&self, target: &mut W) { - let source = flatten_slice_elements(self); - T::write_batch_into(source, target); - } -} - -impl Serializable for &Vec<[T; N]> { - fn write_into(&self, target: &mut W) { - let source = flatten_slice_elements(self); - T::write_batch_into(source, target); - } -} - impl Serializable for &[T] { fn write_into(&self, target: &mut W) { T::write_batch_into(self, target); } } -impl Serializable for &[[T; N]] { +impl Serializable for [T; C] { fn write_into(&self, target: &mut W) { - let source = flatten_slice_elements(self); - T::write_batch_into(source, target); + T::write_batch_into(self, target); } } @@ -426,14 +398,16 @@ impl Deserializable for Option { } } -impl Deserializable for String { +impl Deserializable for [T; C] { fn read_from(source: &mut R) -> Result { - let length = source - .read_u64()? - .try_into() - .map_err(|err| DeserializationError::InvalidValue(format!("{err}",)))?; - let data = source.read_vec(length)?; + let data: Vec = T::read_batch_from(source, C)?; + + // SAFETY: the call above only returns a Vec if there are `C` elements, this conversion + // always succeeds + let res = data.try_into().unwrap_or_else(|v: Vec| { + panic!("Expected a Vec of length {} but it was {}", C, v.len()) + }); - String::from_utf8(data).map_err(|err| DeserializationError::InvalidValue(format!("{err}"))) + Ok(res) } }