Skip to content

Commit

Permalink
nested module works as-is with non-nested arrays
Browse files Browse the repository at this point in the history
Plan to leverage this by refactoring the `nested` module into lib.rs,
thereby supporting both "flat" and nested arrays with same simple syntax

refs #2
  • Loading branch information
Kromey committed May 11, 2021
1 parent 9ea4ee5 commit 5218afa
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/nested.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ impl<'a, T: Serialize, const N: usize> Serialize for ArrayWrap<'a, T, N> {
}
}

pub trait NestedArray<T: Serialize, const N: usize> {
pub trait SerializeArray<T: Serialize, const N: usize> {
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer;
}
impl<T: Serialize, const N: usize, const M: usize> NestedArray<T, N> for [[T; N]; M] {
impl<T: Serialize, const N: usize, const M: usize> SerializeArray<T, N> for [[T; N]; M] {
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
Expand All @@ -70,7 +70,7 @@ impl<T: Serialize, const N: usize, const M: usize> NestedArray<T, N> for [[T; N]
s.end()
}
}
impl<T: Serialize, const N: usize> NestedArray<T, N> for Vec<[T; N]> {
impl<T: Serialize, const N: usize> SerializeArray<T, N> for Vec<[T; N]> {
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
Expand All @@ -83,10 +83,18 @@ impl<T: Serialize, const N: usize> NestedArray<T, N> for Vec<[T; N]> {
s.end()
}
}
impl<T: Serialize, const N: usize> SerializeArray<T, N> for [T; N] {
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
super::serialize(self, ser)
}
}

pub fn serialize<A, S, T, const N: usize>(data: &A, ser: S) -> Result<S::Ok, S::Error>
where
A: NestedArray<T, N>,
A: SerializeArray<T, N>,
S: Serializer,
T: Serialize,
{
Expand Down
6 changes: 6 additions & 0 deletions tests/common/nested.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@ pub struct VecArray<const N: usize> {
#[serde(with = "serde_arrays::nested")]
pub arr: Vec<[u32; N]>,
}

#[derive(Serialize, Debug, PartialEq, Eq)]
pub struct FlatArray<const N: usize> {
#[serde(with = "serde_arrays::nested")]
pub arr: [u32; N],
}
7 changes: 7 additions & 0 deletions tests/serialize_nested.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,10 @@ fn serialize_nested_array() {
assert_eq!(json, &j_generic);
assert_eq!(json, &j_vecced);
}

#[test]
fn serialize_flat_as_nested() {
let flat = FlatArray { arr: [1; 3] };
let j_flat = serde_json::to_string(&flat).unwrap();
assert_eq!("{\"arr\":[1,1,1]}", &j_flat);
}

0 comments on commit 5218afa

Please sign in to comment.