1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
//! # verstamp
//!
//! verstamp writes a two-byte version tag ahead of your payload and checks that
//! your decoder consumed all of it. Old payloads climb a forward migration chain
//! to the current type. This suits binary formats that do not describe
//! themselves.
//!
//! Compact binary formats (bincode, postcard, MessagePack in compact mode) leave
//! field names off the wire. Add a field to a struct and old data stops
//! decoding; worse, two layouts of the same length can decode into each other as
//! plausible values with no error, because nothing on the wire says which layout
//! the bytes hold. verstamp puts the version in front of the payload and routes
//! on it: old bytes climb a chain of [`Migrate`] steps to the current type,
//! current bytes decode in place, and a tag no decoder claims is an error rather
//! than a wrong value. verstamp owns the tag and the chain; you own the encoding.
//!
//! ## Reading
//!
//! [`read`] strips the tag, [`Frame::at`] names the oldest version you can
//! decode, each [`Chain::then`] adds the next version with a [`Migrate`] step,
//! and [`Chain::done`] returns the current type. Register versions in strictly
//! increasing order.
//!
//! A decoder is any `FnOnce(&[u8]) -> Result<(value, bytes_read), E>` whose
//! error converts into [`BoxError`](error::BoxError), that is `Box<dyn Error +
//! Send + Sync + 'static>`. bincode's [`decode_from_slice`] already has that
//! shape, so each step is one inline closure:
//!
//! ```
//! # use bincode::{Decode, Encode};
//! # fn cfg() -> bincode::config::Configuration { bincode::config::standard() }
//! # #[derive(Encode, Decode)] struct SaveV1 { x: u32 }
//! # #[derive(Encode, Decode)] struct SaveV2 { x: u32 }
//! # #[derive(Encode, Decode, Debug, PartialEq)] struct Save { x: u32 }
//! # impl verstamp::Migrate for SaveV2 { type From = SaveV1; fn migrate(v: SaveV1) -> SaveV2 { SaveV2 { x: v.x } } }
//! # impl verstamp::Migrate for Save { type From = SaveV2; fn migrate(v: SaveV2) -> Save { Save { x: v.x } } }
//! # let bytes: Vec<u8> = verstamp::frame(1, &bincode::encode_to_vec(SaveV1 { x: 7 }, cfg()).unwrap());
//! let save: Save = verstamp::read(&bytes)?
//! .at(1, |b| bincode::decode_from_slice::<SaveV1, _>(b, cfg()))
//! .then(2, |b| bincode::decode_from_slice::<SaveV2, _>(b, cfg()))
//! .then(3, |b| bincode::decode_from_slice::<Save, _>(b, cfg()))
//! .done()?;
//! # assert_eq!(save, Save { x: 7 });
//! # Ok::<(), verstamp::Error>(())
//! ```
//!
//! postcard's [`take_from_bytes`] returns the value and the leftover tail rather
//! than a count; wrap it in [`from_tail`] to get the same shape. Complete,
//! runnable programs for both are in the `examples/` directory.
//!
//! ## Writing
//!
//! [`frame`] prepends the tag to bytes you already encoded; [`write()`] prepends
//! it and then lets your encoder append the payload. Starting versions at 1 is a
//! recommendation: a reader that never registers version 0 then rejects an
//! all-zero buffer as [`Error::UnknownVersion`]. verstamp does not enforce it.
//!
//! ## Migrating
//!
//! A [`Migrate`] step describes how a value grows from the previous version to
//! the next. Its associated [`From`](Migrate::From) type names the version a
//! step migrates from, so each step runs `From` into `Self`; keeping that
//! direction pointed at newer versions is a convention you follow, not something
//! the compiler checks. The example below decodes a version-1 record and
//! migrates it forward with a hand-rolled fixed-width codec, so every byte is
//! visible. `SettingsV1` and the current `Settings` are both four bytes wide, so
//! only the tag separates them:
//!
//! ```
//! use verstamp::{frame, read, Migrate};
//!
//! #[derive(Debug, PartialEq)]
//! struct SettingsV1 { volume: u16, brightness: u16 } // 4 bytes
//! #[derive(Debug, PartialEq)]
//! struct Settings { volume: u16, brightness: u8, contrast: u8 } // also 4 bytes
//!
//! impl Migrate for Settings {
//! type From = SettingsV1;
//! fn migrate(v1: SettingsV1) -> Settings {
//! Settings { volume: v1.volume, brightness: v1.brightness.min(255) as u8, contrast: 0 }
//! }
//! }
//!
//! let old = frame(1, &[0, 5, 0, 210]); // volume 5, brightness 210
//! let settings: Settings = read(&old)?
//! .at(1, |b| {
//! if b.len() < 4 {
//! return Err("short");
//! }
//! Ok::<_, &str>((SettingsV1 {
//! volume: u16::from_be_bytes([b[0], b[1]]),
//! brightness: u16::from_be_bytes([b[2], b[3]]),
//! }, 4))
//! })
//! .then(2, |b| {
//! if b.len() < 4 {
//! return Err("short");
//! }
//! Ok::<_, &str>((Settings {
//! volume: u16::from_be_bytes([b[0], b[1]]), brightness: b[2], contrast: b[3],
//! }, 4))
//! })
//! .done()?;
//! assert_eq!(settings, Settings { volume: 5, brightness: 210, contrast: 0 });
//! # Ok::<(), verstamp::Error>(())
//! ```
//!
//! A reader that knows only version 1, handed the version-2 bytes this writer
//! frames, returns [`Error::ForwardIncompatible`] rather than decoding them as a
//! `SettingsV1`.
//!
//! ## What the checks catch
//!
//! The version tag routes the payload to one decoder. A tag newer than the
//! reader knows is [`Error::ForwardIncompatible`]; a tag with no registered
//! decoder is [`Error::UnknownVersion`]. Only the tag distinguishes two
//! equal-length layouts, the four-into-four case above; the byte count cannot.
//!
//! Each decoder also reports how many bytes it read. verstamp checks that count
//! against the payload length and rejects any remainder as
//! [`Error::TrailingBytes`], catching a wrong-length payload that decodes as a
//! prefix and stops short. [`decode_from_slice`] and [`take_from_bytes`] both
//! report the count; a decoder that yields only a value cannot be passed as is,
//! so wrap it to supply a count, and that count is what this check compares.
//!
//! Both checks assume the two-byte tag is intact and the selected decoder is
//! correct. verstamp routes on the tag and rejects mismatched byte counts; it
//! does not checksum the payload or validate a decoder's output. A corrupted
//! tag can select a registered decoder, and a decoder that reads the wrong type
//! yet consumes the whole payload still returns a value.
//!
//! ## Layout
//!
//! | module | role |
//! |---|---|
//! | [`wire`] | [`frame`]/[`write()`] add the version tag; [`read`] takes it off |
//! | [`chain`] | [`Migrate`] and the [`Chain`] that routes a tag to one decoder |
//! | [`error`] | the single [`Error`] type and the context each variant carries |
//!
//! ## Not in scope
//!
//! - **Backward or downgrade migration.** The chain runs one direction, old to
//! current. A newer tag is an error, not a downgrade.
//! - **Field renames, type changes, schema diffing.** verstamp never inspects
//! your payload. Whatever changed between versions, you express as a
//! [`Migrate`] step.
//! - **Encoding.** Bring your own format. verstamp owns two bytes and a chain.
//!
//! [`decode_from_slice`]: https://docs.rs/bincode/2/bincode/fn.decode_from_slice.html
//! [`take_from_bytes`]: https://docs.rs/postcard/1/postcard/fn.take_from_bytes.html
pub use ;
pub use Error;
pub use ;
/// Common imports.
///
/// ```
/// use verstamp::prelude::*;
/// ```