Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for bincode #130

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ autocfg = "1"

[dependencies]
serde = { version = "1.0.95", optional = true, default-features = false, features = ["alloc"] }
bincode = { version = "2.0.0-rc", optional = true, default-features = false }
Comment on lines 27 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're not going to add a release candidate as a dependency. Upgrading to the real 2.0.0 when it is released would be a breaking change.


[dev-dependencies]
rustversion = "1"
serde = { version = "1", features = ["derive"] }
bincode = { version = "2.0.0-rc" }
serde_test = "1"
58 changes: 58 additions & 0 deletions src/bincode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use super::{builder::Builder, Slab};
use bincode::de::{BorrowDecoder, Decoder};
use bincode::enc::Encoder;
use bincode::error::{DecodeError, EncodeError};
use bincode::{BorrowDecode, Decode, Encode};

// Since Slab is stored as a map of usize to T, its implementations are quite similar to those of HashMap<usize, T>:
// https://github.com/bincode-org/bincode/blob/v2.0.0-rc.2/src/features/impl_std.rs#L409-L469.

impl<T: Encode> Encode for Slab<T> {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
// https://docs.rs/bincode/2.0.0-rc.2/bincode/config/struct.Configuration.html#method.with_fixed_int_encoding
// With fixed integer encoding, usize is always encoded as a u64,
// so there's no need to worry about varying sizes of usize.
self.len().encode(encoder)?;
for (key, value) in self {
key.encode(encoder)?;
value.encode(encoder)?;
}
Ok(())
}
}

impl<T: Decode> Decode for Slab<T> {
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
let len = usize::decode(decoder)?;
decoder.claim_container_read::<(usize, T)>(len)?;

let mut builder = Builder::with_capacity(len);
for _ in 0..len {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<(usize, T)>());

let key = usize::decode(decoder)?;
let value = T::decode(decoder)?;
builder.pair(key, value);
}
Ok(builder.build())
}
}

impl<'de, T: BorrowDecode<'de>> BorrowDecode<'de> for Slab<T> {
fn borrow_decode<D: BorrowDecoder<'de>>(decoder: &mut D) -> Result<Self, DecodeError> {
let len = usize::decode(decoder)?;
decoder.claim_container_read::<(usize, T)>(len)?;

let mut builder = Builder::with_capacity(len);
for _ in 0..len {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<(usize, T)>());

let key = usize::borrow_decode(decoder)?;
let value = T::borrow_decode(decoder)?;
builder.pair(key, value);
}
Ok(builder.build())
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ extern crate std as alloc;
#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "bincode")]
mod bincode;

mod builder;

use alloc::vec::{self, Vec};
Expand Down
35 changes: 35 additions & 0 deletions tests/bincode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#![cfg(feature = "bincode")]
#![warn(rust_2018_idioms)]

mod partial_eq;

use bincode::{Decode, Encode};
use partial_eq::SlabPartialEq;
use slab::Slab;
use std::fmt::Debug;

fn assert_bytes<T: Encode + Decode + PartialEq + Debug>(val: &T, bytes: &[u8]) {
let config = bincode::config::standard();

let encoded = bincode::encode_to_vec(val, config).unwrap();
assert_eq!(encoded, bytes);

let (decoded, decoded_len) = bincode::decode_from_slice::<T, _>(bytes, config).unwrap();
assert_eq!(decoded_len, bytes.len());
assert_eq!(&decoded, val);
}

#[test]
fn test_bincode_empty() {
let slab = Slab::<usize>::new();
assert_bytes(&SlabPartialEq(slab), &[0]);
}

#[test]
fn test_bincode() {
let slab = [(1, 2), (3, 4), (5, 6)]
.iter()
.copied()
.collect::<Slab<_>>();
assert_bytes(&SlabPartialEq(slab), &[3, 1, 4, 3, 8, 5, 12]);
}
19 changes: 19 additions & 0 deletions tests/partial_eq.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use slab::Slab;

#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
// bincode struct is transparent by design
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
pub struct SlabPartialEq<T>(pub Slab<T>);

impl<T: PartialEq> PartialEq for SlabPartialEq<T> {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len()
&& self
.0
.iter()
.zip(other.0.iter())
.all(|(this, other)| this.0 == other.0 && this.1 == other.1)
}
}
19 changes: 3 additions & 16 deletions tests/serde.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,12 @@
#![cfg(feature = "serde")]
#![warn(rust_2018_idioms)]

use serde::{Deserialize, Serialize};
mod partial_eq;

use partial_eq::SlabPartialEq;
use serde_test::{assert_tokens, Token};
use slab::Slab;

#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
struct SlabPartialEq<T>(Slab<T>);

impl<T: PartialEq> PartialEq for SlabPartialEq<T> {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len()
&& self
.0
.iter()
.zip(other.0.iter())
.all(|(this, other)| this.0 == other.0 && this.1 == other.1)
}
}

#[test]
fn test_serde_empty() {
let slab = Slab::<usize>::new();
Expand Down