Skip to content

Commit

Permalink
Document serialization of bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
Flix committed Sep 29, 2024
1 parent 63a7bc8 commit a93f126
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
11 changes: 8 additions & 3 deletions examples/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@ struct MyData<'a> {
#[serde(borrow)]
borrowed_bytes: &'a Bytes,
owned_bytes: ByteBuf,
#[serde(with = "serde_bytes")]
byte_vec: Vec<u8>,
}

fn main() {
let data =
MyData { borrowed_bytes: Bytes::new(&[1, 2, 3]), owned_bytes: ByteBuf::from([1, 2, 3]) };
let data = MyData {
borrowed_bytes: Bytes::new(&[1, 2, 3]),
owned_bytes: ByteBuf::from([1, 2, 3]),
byte_vec: vec![1, 2, 3],
};

let mut output = [0; 41];
let mut output = [0; 56];
let bytes = serde_brief::to_slice(&data, &mut output).unwrap();
let parsed: MyData = serde_brief::from_slice(bytes).unwrap();
assert_eq!(parsed, data);
Expand Down
25 changes: 24 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
//!
//! - Convenient to use for developers: Integrates into the Rust ecosystem via `serde`, supporting
//! all of its features in its derived implementations (e.g. renaming, flattening, ..).
//! - Compatibility: Easy to add or re-order fields/variants without breakage.
//! - Compatibility: Easy to add or re-order fields/variants without breakage. Detects wrong data
//! types.
//! - `#![no_std]` and std compatible.
//! - Resource efficient: High performance, low memory usage.
//! - Interoperability: Different architectures can communicate flawlessly.
Expand Down Expand Up @@ -72,6 +73,28 @@
//! let parsed: MyBorrowedData = serde_brief::from_slice(&output).unwrap();
//! assert_eq!(parsed, data);
//! ```
//!
//! ### Bytes Serialization/Deserialization
//!
//! Serde serializes byte arrays, such as `[u8; N]` or `Vec<u8>`, as sequences by default (due to
//! missing specialization support in Rust). To serialize these types as proper bytes, making the
//! format way more efficient, you can use `serde_bytes` or your own serde-trait-implementations.
//!
//! Example using `serde_bytes`:
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//! use serde_bytes::{ByteBuf, Bytes};
//!
//! #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
//! struct MyData<'a> {
//! owned_bytes: ByteBuf,
//! #[serde(borrow)]
//! borrowed_bytes: &'a Bytes,
//! #[serde(with = "serde_bytes")]
//! byte_vec: Vec<u8>,
//! }
//! ```
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
Expand Down

0 comments on commit a93f126

Please sign in to comment.