Crate serde_arrays

Source
Expand description

Serialize and deserialize const generic or arbitrarily-large arrays with Serde.

Out of the box, Serde supports a lot of types, but unfortunately lacks support for arrays that use const generics. This library provides a module that, in combination with Serde’s with attribute, adds that support.

§Example usage

use serde::{Serialize, Deserialize};
use serde_json;

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct GenericArray<const N: usize> {
    #[serde(with = "serde_arrays")]
    arr: [u32; N],
}

let data = GenericArray{ arr: [1; 16] };
let json = serde_json::to_string(&data)?;
let de_data = serde_json::from_str(&json)?;

assert_eq!(data, de_data);

As an added bonus, this also adds support for arbitrarily large arrays beyond the 32 elements that Serde supports:

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct LargeArray {
    #[serde(with = "serde_arrays")]
    arr: [u32; 64],
}

Tuple structs are supported just as easily:

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct TupleStruct<const N: usize>(
    #[serde(with = "serde_arrays")]
    [u32; N],
);

Nested arrays can be serialized as well:

#[derive(Serialize, Debug, PartialEq, Eq)]
struct NestedArray {
    #[serde(with = "serde_arrays")]
    arr: [[u32; 64]; 64],
    #[serde(with = "serde_arrays")]
    vec: Vec<[u32; 96]>,
}

Currently, nested arrays cannot be deserialized. If you need to deserialize nested arrays, try using a wrapper struct:

#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
struct WrappedArray<const N: usize> (
   #[serde(with = "serde_arrays")]
  [u32; N],
);

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct NestedArray {
    #[serde(with = "serde_arrays")]
    arr: [WrappedArray<64>; 64],
    vec: Vec<WrappedArray<96>>,
}

§no_std Compatibility

This crate is no_std compatible by default.

If you need to support serialization of e.g. Vec<[T; N]> you can enable the alloc feature; alternatively, using a wrapper struct as shown above can be done without the alloc feature.

§MSRV

This library relies on the const generics feature introduced in Rust 1.51.0.

  • The Serde issue for const generics support
  • serde-big-array is a similar crate for large arrays and const generic arrays
  • serde_with is a much more flexible and powerful crate, but with arguably more complex ergonomics

Traits§

Serializable
Trait for types serializable using serde_arrays

Functions§

deserialize
Deserialize const generic or arbitrarily-large arrays
serialize
Serialize const generic or arbitrarily-large arrays