Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ Foo {bar: 12}
serde does not support arrays with more than 32 elements or using const-generics.
The `serde_as` attribute allows circumventing this restriction, even for nested types and nested arrays.

On top of it, `[u8; N]` (aka, bytes) can use the specialized `"Bytes"` for efficiency much like the `serde_bytes` crate.

[![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/um0xyi)
```rust
#[serde_as]
Expand All @@ -80,13 +82,17 @@ struct Arrays<const N: usize, const M: usize> {

#[serde_as(as = "Option<[_; M]>")]
optional: Option<[u8; M]>,

#[serde_as(as = "Bytes")]
bytes: [u8; M],
}

// This allows us to serialize a struct like this
let arrays: Arrays<100, 128> = Arrays {
constgeneric: [true; 100],
nested: Box::new([[111; 64]; 100]),
optional: Some([222; 128])
optional: Some([222; 128]),
bytes: [0x42; 128],
};
assert!(serde_json::to_string(&arrays).is_ok());
```
Expand Down
10 changes: 8 additions & 2 deletions serde_with/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,14 @@
//! serde does not support arrays with more than 32 elements or using const-generics.
//! The `serde_as` attribute allows circumventing this restriction, even for nested types and nested arrays.
//!
//! On top of it, `[u8; N]` (aka, bytes) can use the specialized `"Bytes"` for efficiency much like the `serde_bytes` crate.
//!
//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/um0xyi)
//! ```rust
//! # #[cfg(feature = "macros")]
//! # use serde::{Deserialize, Serialize};
//! # #[cfg(feature = "macros")]
//! # use serde_with::serde_as;
//! # use serde_with::{serde_as, Bytes};
//! # #[cfg(feature = "macros")]
//! #[serde_as]
//! # #[derive(Debug, Eq, PartialEq)]
Expand All @@ -141,14 +143,18 @@
//!
//! #[serde_as(as = "Option<[_; M]>")]
//! optional: Option<[u8; M]>,
//!
//! #[serde_as(as = "Bytes")]
//! bytes: [u8; M],
//! }
//!
//! # #[cfg(all(feature = "macros", feature = "json"))] {
//! // This allows us to serialize a struct like this
//! let arrays: Arrays<100, 128> = Arrays {
//! constgeneric: [true; 100],
//! nested: Box::new([[111; 64]; 100]),
//! optional: Some([222; 128])
//! optional: Some([222; 128]),
//! bytes: [0x42; 128],
//! };
//! assert!(serde_json::to_string(&arrays).is_ok());
//! # }
Expand Down