Information
Revision is a framework for revision-tolerant serialization and deserialization with support for schema evolution over time. It allows for easy revisioning of structs and enums for data storage requirements which need to support backwards compatibility, but where the design of the data structures evolve over time. Revision enables data that was serialized at older revisions to be seamlessly deserialized and converted into the latest data structures. It uses bincode for serialization and deserialization.
The Revisioned trait is automatically implemented for the following primitives: u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, char, String, Vec<T>, Arrays up to 32 elements, Option<T>, Box<T>, Bound<T>, Wrapping<T>, Reverse<T>, (A, B), (A, B, C), (A, B, C, D), (A, B, C, D, E), Duration, HashMap<K, V>, BTreeMap<K, V>, HashSet<T>, BTreeSet<T>, BinaryHeap<T>, Result<T, E>, Cow<'_, T>, Decimal, regex::Regex, uuid::Uuid, chrono::Duration, chrono::DateTime<Utc>, geo::Point, geo::LineString geo::Polygon, geo::MultiPoint, geo::MultiLineString, geo::MultiPolygon, and ordered_float::NotNan.
Feature Flags
Revision supports the following feature flags:
specialised-vectors(default): Enables specialised implementations for certain vector types that provide serialisation and deserialisation performance improvements.fixed-width-encoding: Uses fixed-width encoding for integers instead of variable-length encoding. By default, Revision uses variable-length encoding which is more space-efficient for small values but has overhead for large values. With this feature enabled, all integers use their full size (2 bytes foru16/i16, 4 bytes foru32/i32, 8 bytes foru64/i64, 16 bytes foru128/i128), providing predictable serialization sizes, and improved serialisation and deserialisation performance.skip(disabled by default): EnablesSkipRevisioned/SkipCheckRevisioned,skip_slice/skip_check_slice(plusskip_reader/skip_check_readeraliases), slice fast paths, and matching derive output (#[revisioned(..., skip = false)]opts out per type). Library crates should forwardskip = ["revision/skip"]and documentfeatures = ["skip"]for dependents; see Skipping encoded values below.
Integer Encoding Trade-offs
Variable-length encoding (default):
- Small values (0-250) use only 1 byte
- More compact for typical workloads with mostly small values
- Variable serialization size based on value magnitude
- Slight overhead for very large values
Fixed-width encoding (fixed-width-encoding feature):
- Predictable, constant serialization size per type
- No branching or size checks during encoding/decoding
- Less compact for small values
- More efficient for workloads with large values
Benchmarking
To compare variable-length vs fixed-width encoding performance:
# Benchmark with default variable-length encoding
# Benchmark with fixed-width encoding
The varint_comparison benchmark tests serialization and deserialization performance across different data distributions (small values, large values, and mixed distributions) for all integer types.
Inspiration
This code takes inspiration from the Versionize library developed for Amazon Firecracker snapshot-restore development previews.
Revision in action
use Error;
use revisioned;
// The test structure is at revision 3.
// The test structure is at revision 3.
Skipping encoded values
Use the skip feature when you handle revisioned bytes but only need to extract certain fields from the binary data - without deserializing full structs or maps into memory.
Extracting one field from a struct
A #[revisioned] struct is laid out as struct revision (u16), then fields in source order. Read only what you need and call SkipRevisioned::skip_revisioned on &mut reader for the rest (or use skip_slice::<T> to skip a whole nested value in one go when you have a sub-slice).
use ;
let row = Row ;
let bytes = to_vec.unwrap;
assert_eq!;
Extracting one entry from a BTreeMap
Maps are encoded as length (usize), then key / value pairs in sorted key order. Typical pattern: deserialize each key, compare, deserialize the value you care about, otherwise skip the value with the appropriate skip_revisioned call.
use ;
use BTreeMap;
let cfg = Config ;
let bytes = to_vec.unwrap;
assert_eq!;
For map values that are themselves #[revisioned] enums or structs, deserialize the discriminant / nested revision as you would when fully deserializing, and call MyValue::skip_revisioned on entries you discard (see benches/skip_mixed_btreemap_nested.rs).
Use skip_check_* when you want validation that matches stricter deserialize checks (e.g. UTF-8 for String). Disable skip for a type with #[revisioned(revision = N, skip = false)].
Walking encoded values
WalkRevisioned is a higher-level companion to SkipRevisioned: it lets a caller progress element-by-element through revisioned bytes, deciding per-element whether to decode, skip, or walk into further structure — without rewriting the byte-arithmetic by hand each time. The trait sits between DeserializeRevisioned (decode the entire value) and SkipRevisioned (consume the whole encoding).
The derive macro emits WalkRevisioned for every #[revisioned(...)] type by default (controlled by the same flag as deserialize). Opt out per type with #[revisioned(revision = N, walk = false)].
For each #[revisioned(...)] type the derive emits a per-type walker (<TypeName>Walker<'r, R>) with named per-field / per-variant methods. This is in addition to the generic StructWalker / EnumWalker / MapWalker / SeqWalker types that hand-written WalkRevisioned impls can return.
Walking a struct
use ;
Walking a map
BTreeMap<K, V> returns a MapWalker whose next_entry borrows one key/value pair at a time. Decode the key, then either decode/skip/walk the value before moving on:
use ;
use BTreeMap;
let mut map: = new;
map.insert;
map.insert;
let bytes = to_vec.unwrap;
let mut reader = bytes.as_slice;
let mut walker: = walk_revisioned?;
let mut found = None;
while let Some = walker.next_entry
assert_eq!;
Walking an enum
For each variant, the derive emits an into_<variant> consuming method that descends into the variant's payload (for unit and single-field tuple variants), and a per-revision walk_revisioned_variant_name(wire_rev, disc) lookup:
use ;
let bytes = to_vec.unwrap;
let mut reader = bytes.as_slice;
let walker = walk_revisioned?;
if walker.is_circle
Walking across revisions
WalkRevisioned honours the same cross-revision contract as DeserializeRevisioned: any wire revision in 1..=current is accepted, and the walker presents the latest schema view. There are two internal modes:
- Wire mode (the fast path) is used when the wire revision matches the current schema, and for any older revision of a type that does not use
convert_fn. Per-field methods branch onwire_revagainst the field'sstartannotation: fields added after the wire revision are synthesised viaDefault::default()(or the user-supplieddefault_fn); no allocations. - Materialised mode is used when the wire revision differs from the current schema and the type has at least one
convert_fn. The walker internally callsSelf::deserialize_revisioned(which honoursconvert_fn), re-encodes the result at the current revision, and then byte-walks those new bytes. The user-facing API is identical; the cost is a singleVec<u8>allocation plus the deserialize/serialize roundtrip.
The walker's mode selection happens at construction; per-method code paths do not branch beyond a single match on the internal repr.
use ;
let bytes = to_vec.unwrap;
let mut r = bytes.as_slice;
let mut walker = walk_revisioned?;
let kind = walker.decode_kind?; // exists at all revisions
let flags = walker.decode_flags?; // synthesised default at wire rev 1
assert_eq!;
Performance characteristics
| Path | Cost |
|---|---|
| Wire rev = current | identical to the current-rev hot path; per-field methods inline |
Wire rev < current, type without convert_fn |
one extra branch per field; allocation-free |
Wire rev < current, type with convert_fn |
deserialize + serialize + walk; rare in practice |
Zero-copy peeking
When a walker visits a value whose wire format is usize len || raw bytes — a string, a Vec<u8>, a PathBuf, or any newtype wrapping one — the caller usually wants to compare those bytes against a needle, hash them, or stream them somewhere. Decoding the value just to throw the owned String / Vec<u8> / Bytes away is pure overhead.
Two small traits unlock zero-copy peeking on those payloads:
| Trait | Implemented for | Purpose |
|---|---|---|
BorrowedReader |
&[u8], [SliceReader] |
A Read whose buffer is addressable, so a slice of upcoming bytes can be borrowed without copying. |
LengthPrefixedBytes |
String, &str, Box<str>, Arc<str>, Cow<'_, str>, Vec<u8>, Vec<i8>, PathBuf, bytes::Bytes (feature-gated), and downstream newtypes |
Marker: this type's SerializeRevisioned writes exactly `usize len |
When both are satisfied, walkers expose the following methods:
| Walker | Method | Reader bound | Element bound |
|---|---|---|---|
LeafWalker<T> |
with_bytes |
BorrowedReader |
T: LengthPrefixedBytes |
MapWalker<K, V> |
find_bytes |
BorrowedReader |
K: LengthPrefixedBytes |
MapEntry<K, V> |
with_key_bytes |
BorrowedReader |
K: LengthPrefixedBytes |
MapEntry<K, V> |
with_value_bytes |
BorrowedReader |
V: LengthPrefixedBytes |
SeqItem<T> |
with_bytes |
BorrowedReader |
T: LengthPrefixedBytes |
Worked example: matching a map key by raw bytes
MapWalker::find_bytes is the direct analogue of find, but the predicate sees the key's wire bytes instead of a decoded K:
use BTreeMap;
use ;
let mut table = new;
table.insert;
table.insert;
table.insert;
let bytes = to_vec.unwrap;
let mut r = bytes.as_slice;
let walker: =
walk_revisioned.unwrap;
// Compare keys as `&[u8]` — no Strand / String allocated per visit.
let value = walker
.find_bytes
.unwrap
.map
.transpose
.unwrap;
assert_eq!;
Worked example: peeking a single key during streaming iteration
MapEntry::with_key_bytes is the per-entry counterpart. Use it when iterating with next_entry and you want to decide what to do with the value based on the key's bytes:
use BTreeMap;
use ;
let mut table = new;
table.insert;
table.insert;
table.insert;
let bytes = to_vec.unwrap;
let mut r = bytes.as_slice;
let mut walker: =
walk_revisioned.unwrap;
let mut beta = None;
while let Some = walker.next_entry
assert_eq!;
Worked example: filtering a map by value bytes
MapEntry::with_value_bytes mirrors with_key_bytes for the value slot. Useful when the key has already been handled (decoded or skipped) and the caller wants to filter based on the value's raw bytes:
use BTreeMap;
use ;
let mut table: = new;
table.insert;
table.insert;
let bytes = to_vec.unwrap;
let mut r = bytes.as_slice;
let mut walker: =
walk_revisioned.unwrap;
let mut hits = 0;
while let Some = walker.next_entry
assert_eq!;
Worked example: scanning a sequence of strings
SeqItem::with_bytes lets a scan over Vec<String> (or any SeqWalker whose item type implements LengthPrefixedBytes) compare items as raw bytes without paying for a per-item allocation:
use ;
let v = vec!;
let bytes = to_vec.unwrap;
let mut r = bytes.as_slice;
let mut walker: =
walk_revisioned.unwrap;
let mut found = false;
while let Some = walker.next_item
assert!;
When zero-copy peeking does not apply
- The reader is a streaming source (
std::fs::File,TcpStream, …).BorrowedReaderis only implemented for slice-backed readers. - The element type is a derived
#[revisioned(...)]type. Its wire format includes au16revision header followed by the body, not bare length-prefixed bytes; usedecode/walkand let the walker read past the header. - The element is a primitive numeric (
u32,f64, …) or a fixed-size array. There is no length prefix; the wire bytes are the value bytes. Usedecodedirectly.
Limitations
-
Untrusted inputs: Wire lengths are
usizelength prefixes like everywhere else inrevision; they bound how much is read, skipped, or materialised. Walkers add no extra caps or validation — same trust model asDeserializeRevisioned/SkipRevisioned. -
MapWalker::find/find_bytes: On a match you only get aLeafWalkerfor that entry's value. The method consumes theMapWalker; you cannot resumenext_entryon it. Key–value pairs that sort after the match remain on the underlying reader for other callers, not for the same walker instance (by design). Both methods assume wire visit order matches sorted-map encoding (as when serialisingBTreeMap). Using an ordering predicate on bytes produced from unsorted maps (HashMapinsertion order, …) can match incorrectly or discard the tail underOrdering::Greater. -
LengthPrefixedByteson custom types: The marker must match the type's realSerializeRevisionedlayout (usize len || raw bytes). A wrong impl breakswith_bytes/find_bytesand related paths — it is an explicit contract, not something the library can detect (same class of risk as any incorrectRevisionedimpl). -
The derive emits two flavours of nested walk per field.
walk_<field>(&mut self)borrows the parent walker so the caller can keep reading siblings after the sub-walker is dropped.into_walk_<field>(self)consumes the parent and hands the reader to the sub-walker for the original'r, trading sibling access for a longer-lived sub-walker. Both error withError::Conversionin materialised mode (older revs ofconvert_fn-bearing types); callers that hit that path shoulddecode_<field>instead. -
into_<variant>is currently emitted for unit variants and single-field tuple variants. Multi-field tuple variants and struct variants are reachable viadiscriminant()+decode_<field>on the underlying bytes. -
Vec<T>usesspecialised-vectorsbulk encoding for several element types when that Cargo feature is enabled (the default): primitives,bool, and — if the optionaluuid/rust_decimalcrate features are also enabled —uuid::Uuidandrust_decimal::Decimal(seetry_specialized!insrc/implementations/vecs.rs).Vec<T>::walk_revisionedrejects each suchTwith [Error::Deserialize] before reading the sequence length, leaving the reader unchanged — useDeserializeRevisionedorSkipRevisionedinstead. Withspecialised-vectorsdisabled, everyVec<T>uses per-element layout and is safe to walk.HashSet<T>,BTreeSet<T>,BinaryHeap<T>, and theimblcollections always use per-element framing, so they are walkable regardless of element type. -
[
MapEntry] methods enforce key/value ordering in every build: callingdecode_valuebeforedecode_key/skip_key, or repeatingdecode_key, returns [Error::Deserialize] without advancing the reader when the check fails before I/O. -
[
SeqItem::walk], [MapEntry::walk_value], and [StructWalker::walk] advance counters (remaining,position) only afterwalk_revisionedsucceeds, so a failed nested walk does not desynchronise the parent walker from the byte stream. -
A type using
convert_fnrequires bothserialize = trueanddeserialize = trueforwalkto be derivable (the default). The derive errors at compile time ifwalk = trueis combined with either disabled, since the materialised cross-revision path needs to deserialize at the wire revision and re-serialize at the current revision. Setwalk = falseon such a type if you don't need walker support. -
Cow<'_, T>is treated as opaque by the walker. ItsWalkeris aLeafWalker<T::Owned>, sodecode()returnsT::Owned(e.g.StringforCow<'_, str>), not aCow. UseDeserializeRevisionedif you need aCowback, or descend throughT::Owned::walk_revisioneddirectly.