Skip to content

Commit

Permalink
Merge pull request #80 from contain-rs/borsh-ser
Browse files Browse the repository at this point in the history
Optional Borsh serialization and deserialization
  • Loading branch information
pczarn authored May 31, 2024
2 parents 1bc71c9 + 16475e1 commit fec5564
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ keywords = ["data-structures", "bitvec", "bitmask", "bitmap", "bit"]
readme = "README.md"

[dependencies]
borsh = { version = "1.2.0", default-features = false, features = ["derive"], optional = true }
serde = { version = "1.0", default-features = false, features = ["derive"], optional = true }

[dev-dependencies]
Expand All @@ -22,4 +23,5 @@ rand_xorshift = "0.2"
default = ["std"]
serde_std = ["std", "serde/std"]
serde_no_std = ["serde/alloc"]
borsh_std = ["borsh/std"]
std = []
21 changes: 21 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ use std::vec::Vec;
extern crate serde;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "borsh")]
extern crate borsh;

#[cfg(not(feature = "std"))]
#[macro_use]
Expand Down Expand Up @@ -218,6 +220,10 @@ static FALSE: bool = false;
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshDeserialize, borsh::BorshSerialize)
)]
pub struct BitVec<B = u32> {
/// Internal representation of the bit vector
storage: Vec<B>,
Expand Down Expand Up @@ -2642,6 +2648,21 @@ mod tests {
assert_eq!(bit_vec, unserialized);
}

#[cfg(feature = "borsh")]
#[test]
fn test_borsh_serialization() {
let bit_vec: BitVec = BitVec::new();
let serialized = borsh::to_vec(&bit_vec).unwrap();
let unserialized: BitVec = borsh::from_slice(&serialized[..]).unwrap();
assert_eq!(bit_vec, unserialized);

let bools = vec![true, false, true, true];
let bit_vec: BitVec = bools.iter().map(|n| *n).collect();
let serialized = borsh::to_vec(&bit_vec).unwrap();
let unserialized = borsh::from_slice(&serialized[..]).unwrap();
assert_eq!(bit_vec, unserialized);
}

#[test]
fn test_bit_vec_unaligned_small_append() {
let mut a = BitVec::from_elem(8, false);
Expand Down

0 comments on commit fec5564

Please sign in to comment.