Skip to content

Commit

Permalink
serde: add support for arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
hackaugusto committed Dec 1, 2023
1 parent a0e2a72 commit 5971f6a
Showing 1 changed file with 17 additions and 18 deletions.
35 changes: 17 additions & 18 deletions utils/core/src/serde/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -210,30 +210,15 @@ impl Serializable for &String {
}
}

impl<T: Serializable, const N: usize> Serializable for Vec<[T; N]> {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
let source = flatten_slice_elements(self);
T::write_batch_into(source, target);
}
}

impl<T: Serializable, const N: usize> Serializable for &Vec<[T; N]> {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
let source = flatten_slice_elements(self);
T::write_batch_into(source, target);
}
}

impl<T: Serializable> Serializable for &[T] {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
T::write_batch_into(self, target);
}
}

impl<T: Serializable, const N: usize> Serializable for &[[T; N]] {
impl<T: Serializable, const C: usize> Serializable for [T; C] {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
let source = flatten_slice_elements(self);
T::write_batch_into(source, target);
T::write_batch_into(self, target);
}
}

Expand Down Expand Up @@ -437,3 +422,17 @@ impl Deserializable for String {
String::from_utf8(data).map_err(|err| DeserializationError::InvalidValue(format!("{err}")))
}
}

impl<T: Deserializable, const C: usize> Deserializable for [T; C] {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let data: Vec<T> = 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<T>| {
panic!("Expected a Vec of length {} but it was {}", C, v.len())
});

Ok(res)
}
}

0 comments on commit 5971f6a

Please sign in to comment.