From 7ae65f9aa4c44289b277ea4a3eb703ae90e8a0df Mon Sep 17 00:00:00 2001 From: Peter Farr Date: Tue, 19 Mar 2024 14:59:21 -0400 Subject: [PATCH] Add bitcode support This commit adds support for bitcode Encode and Decode. It does so gated behind a feature flag. The bitcode version is set to 0, with default features turned off, only derive feature added, and optional set to true. This allows libraries to specify the verison of bitcode they would prefer, and avoids using any other functionality of bitcode. --- Cargo.toml | 2 ++ src/lib.rs | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 15bb926..e101d7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ rand = { version = "0.8", optional = true } uuid = { version = "1.1", optional = true } postgres-types = { version = "0.2.6", optional = true } bytes = { version = "1.4.0", optional = true } +bitcode = { version = "0", features = ["derive"], default-features = false, optional = true } [target.wasm32-unknown-unknown.dependencies] getrandom = { version = "0.2", features = ["js"] } @@ -31,6 +32,7 @@ web-time = "1" [dev-dependencies] bencher = "0.1" serde_derive = "1.0" +bitcode = "0.5" [target.wasm32-unknown-unknown.dev-dependencies] wasm-bindgen-test = "0.3" diff --git a/src/lib.rs b/src/lib.rs index bf5e868..42d3f8c 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -73,6 +73,7 @@ pub(crate) use bitmask; /// Of the 128-bits, the first 48 are a unix timestamp in milliseconds. The /// remaining 80 are random. The first 48 provide for lexicographic sorting and /// the remaining 80 ensure that the identifier is unique. +#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))] #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash, Clone, Copy)] pub struct Ulid(pub u128); @@ -422,3 +423,18 @@ mod tests { println!("{}", DecodeError::InvalidChar); } } + +#[cfg(all(test, feature = "std", feature = "bitcode"))] +mod bitcode_tests { + use super::*; + use bitcode; + + #[test] + fn bitcode_roundtrip() { + let ulid = Ulid::new(); + let encoded: Vec = bitcode::encode(&ulid).expect("failed to encode"); + let decoded: Ulid = bitcode::decode(&encoded).expect("failed to decode"); + + assert_eq!(ulid, decoded); + } +}