From 0c13c891c5f9d217589fce6d823721f672d22c92 Mon Sep 17 00:00:00 2001 From: Trangar Date: Mon, 25 Oct 2021 10:26:23 +0200 Subject: [PATCH] Updated readme.md and added a test for the examples (#417) * Updated readme.md and added a test for the examples * Removed tests/readme.rs and made the readme doctest a (hidden) part of lib.rs --- README.md | 22 +++++++++++++--------- src/lib.rs | 6 ++++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index a0a68e0..5e321d9 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ -![CI](https://github.com/bincode-org/bincode/workflows/CI/badge.svg) -[![](https://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode) +[![CI](https://github.com/bincode-org/bincode/workflows/CI/badge.svg)](https://github.com/bincode-org/bincode/actions) +[![](https://img.shields.io/crates/v/bincode.svg)](https://crates.io/crates/bincode) [![](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Matrix](https://img.shields.io/matrix/bincode:matrix.org?label=Matrix%20Chat)](https://matrix.to/#/#bincode:matrix.org) @@ -30,26 +30,30 @@ library. ## Example ```rust -use serde::{Serialize, Deserialize}; +use bincode::{config::Configuration, Decode, Encode}; -#[derive(Serialize, Deserialize, PartialEq, Debug)] +#[derive(Encode, Decode, PartialEq, Debug)] struct Entity { x: f32, y: f32, } -#[derive(Serialize, Deserialize, PartialEq, Debug)] +#[derive(Encode, Decode, PartialEq, Debug)] struct World(Vec); fn main() { + let config = Configuration::standard(); + let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]); - let encoded: Vec = bincode::serialize(&world).unwrap(); + let encoded: Vec = bincode::encode_to_vec(&world, config).unwrap(); - // 8 bytes for the length of the vector, 4 bytes per float. - assert_eq!(encoded.len(), 8 + 4 * 4); + // The length of the vector is encoded as a varint u64, which in this case gets collapsed to a single byte + // See the documentation on varint for more info for that. + // The 4 floats are encoded in 4 bytes each. + assert_eq!(encoded.len(), 1 + 4 * 4); - let decoded: World = bincode::deserialize(&encoded[..]).unwrap(); + let decoded: World = bincode::decode_from_slice(&encoded[..], config).unwrap(); assert_eq!(world, decoded); } diff --git a/src/lib.rs b/src/lib.rs index 5403aec..512f8a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,3 +143,9 @@ pub fn decode_from_reader( pub mod spec { #![doc = include_str!("../docs/spec.md")] } + +// Test the examples in readme.md +#[cfg(all(feature = "alloc", feature = "derive", doctest))] +mod readme { + #![doc = include_str!("../readme.md")] +}