revision 0.25.0

A serialization and deserialization implementation which allows for schema-evolution.
Documentation
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Walker support for optimised-encoded types.
//!
//! The walker's `walk_revisioned` constructor reads the u16 wire revision and
//! advances past the optimised envelope (`u32_le payload_length` + optional
//! indexed prologue) for revisions that opt into `optimised`.
//! Field reads on the resulting Wire walker then succeed as normal.

use revision::prelude::*;

#[revisioned(revision(1, optimised))]
struct OptStruct {
	a: u32,
	b: u32,
}

#[revisioned(revision(1, optimised, indexed_struct))]
struct IndexedStruct {
	a: u32,
	b: u32,
	c: u32,
}

#[revisioned(revision(1), revision(2, optimised))]
struct MixedHistory {
	a: u32,
	b: u32,
}

#[revisioned(revision(1, optimised))]
enum OptEnum {
	#[revision(size = "inline")]
	Unit,
	#[revision(size = "varlen")]
	Varlen(String),
}

#[test]
fn walker_decodes_optimised_struct() {
	let v = OptStruct {
		a: 42,
		b: 100,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let mut w = OptStruct::walk_revisioned(&mut r).unwrap();
	let a = w.decode_a().unwrap();
	let b = w.decode_b().unwrap();
	assert_eq!(a, 42);
	assert_eq!(b, 100);
}

#[test]
fn walker_decodes_indexed_optimised_struct() {
	let v = IndexedStruct {
		a: 10,
		b: 20,
		c: 30,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let mut w = IndexedStruct::walk_revisioned(&mut r).unwrap();
	let a = w.decode_a().unwrap();
	let b = w.decode_b().unwrap();
	let c = w.decode_c().unwrap();
	assert_eq!(a, 10);
	assert_eq!(b, 20);
	assert_eq!(c, 30);
}

#[test]
fn walker_handles_mixed_history_optimised_rev() {
	// Encoded at rev 2 (optimised); walker advances past the envelope.
	let v = MixedHistory {
		a: 7,
		b: 11,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let mut w = MixedHistory::walk_revisioned(&mut r).unwrap();
	assert_eq!(w.decode_a().unwrap(), 7);
	assert_eq!(w.decode_b().unwrap(), 11);
}

#[test]
fn walker_handles_mixed_history_legacy_rev() {
	// Shadow type at rev 1 (legacy) — walker stays on the Wire path with no
	// envelope skipping required.
	#[revisioned(revision(1))]
	struct ShadowRev1 {
		a: u32,
		b: u32,
	}
	let s = ShadowRev1 {
		a: 7,
		b: 11,
	};
	let bytes = revision::to_vec(&s).unwrap();
	let mut r: &[u8] = &bytes;
	let mut w = MixedHistory::walk_revisioned(&mut r).unwrap();
	assert_eq!(w.decode_a().unwrap(), 7);
	assert_eq!(w.decode_b().unwrap(), 11);
}

#[test]
fn walker_on_optimised_enum_decodes_unit_variant() {
	let v = OptEnum::Unit;
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = OptEnum::walk_revisioned(&mut r).unwrap();
	// Unit is the first declared variant — its discriminant is 0 by default.
	assert_eq!(w.discriminant(), 0);
	assert!(w.is_unit());
	assert!(!w.is_varlen());
}

#[test]
fn walker_on_optimised_enum_decodes_varlen_variant() {
	let v = OptEnum::Varlen("hello".into());
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = OptEnum::walk_revisioned(&mut r).unwrap();
	// Varlen is the second variant — discriminant 1.
	assert_eq!(w.discriminant(), 1);
	assert!(w.is_varlen());
	assert!(!w.is_unit());
	// `decode_<variant>` works on every walker repr (Wire,
	// OptimisedBorrowed, ConvertedOwned), so it's the right way to
	// extract the inner value from an optimised enum walker.
	let inner = w.decode_varlen().unwrap();
	assert_eq!(inner, "hello");
}

#[test]
fn walker_decode_variant_works_on_legacy_enum() {
	// Sanity: decode_<variant> on a Wire (legacy) walker also works,
	// keeping the API symmetric.
	#[revisioned(revision(1))]
	#[derive(Debug)]
	enum LegacyEnum {
		Unit,
		Tup(u64),
	}

	let v = LegacyEnum::Tup(0xDEADBEEF);
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = LegacyEnum::walk_revisioned(&mut r).unwrap();
	let inner = w.decode_tup().unwrap();
	assert_eq!(inner, 0xDEADBEEF);
}

#[test]
fn walker_variant_view_works_on_optimised_enum() {
	// `<variant>_view` returns a VariantView holding the variant body
	// bytes. Works on every walker repr — Wire (legacy enums),
	// OptimisedBorrowed (optimised enums), and ConvertedOwned
	// (cross-rev `convert_fn`).
	let v = OptEnum::Varlen("hello".into());
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = OptEnum::walk_revisioned(&mut r).unwrap();
	let view = w.varlen_view().unwrap();
	// The view owns the variant's body bytes — caller can construct their
	// own walker / decoder from them.
	let body = view.as_bytes();
	let mut br: &[u8] = body;
	let inner: String =
		<String as revision::DeserializeRevisioned>::deserialize_revisioned(&mut br).unwrap();
	assert_eq!(inner, "hello");
}

#[test]
fn walker_variant_view_borrows_from_source_for_optimised_enum() {
	// Surrealdb-style descent pattern: walk into an optimised enum, get the
	// variant body as a borrowed slice, then construct an inner walker over
	// the borrowed bytes — zero allocations for the variant body.
	//
	// This is what the `WalkRevisioned: BorrowedReader` bound + Cow<'r, [u8]>
	// in the walker repr enables.
	#[revisioned(revision(1, optimised))]
	#[derive(Debug, PartialEq)]
	enum Value {
		#[revision(size = "inline")]
		Null,
		#[revision(size = "varlen")]
		Array(Vec<u32>),
	}

	let v = Value::Array(vec![1, 2, 3, 4, 5]);
	let bytes = revision::to_vec(&v).unwrap();

	// Outer walk: optimised enum, body bytes are borrowed from `bytes`.
	let mut r: &[u8] = &bytes;
	let w = Value::walk_revisioned(&mut r).unwrap();
	let view = w.array_view().unwrap();

	// `as_bytes` returns a slice into the source `bytes` — same buffer, no
	// copy. Verify three properties that together prove the no-alloc claim:
	//
	// 1. The body pointer lies inside the source buffer (not in a fresh allocation).
	// 2. The body length is strictly less than the source length (the source
	//    has at least the tag + length prefix on top of the body).
	// 3. The body bytes match the corresponding sub-slice of the source (would
	//    fail if the bytes were copied through a buffer that mangled them).
	let body: &[u8] = view.as_bytes();
	let src_start = bytes.as_ptr() as usize;
	let src_end = src_start + bytes.len();
	let body_start = body.as_ptr() as usize;
	let body_end = body_start + body.len();
	assert!(
		body_start >= src_start && body_end <= src_end,
		"view's bytes should lie inside the source buffer; got body={body_start:#x}..{body_end:#x}, source={src_start:#x}..{src_end:#x} (an alloc would land in a different range)"
	);
	assert!(
		body.len() < bytes.len(),
		"body ({}) must be strictly shorter than the full envelope ({}) — the envelope carries the tag + length prefix on top",
		body.len(),
		bytes.len()
	);
	let offset = body_start - src_start;
	assert_eq!(
		body,
		&bytes[offset..offset + body.len()],
		"body slice should equal the corresponding range of the source verbatim"
	);

	// Construct an inner walker over the borrowed body. Streaming descent.
	let mut cursor: &[u8] = body;
	let inner: Vec<u32> =
		<Vec<u32> as revision::DeserializeRevisioned>::deserialize_revisioned(&mut cursor).unwrap();
	assert_eq!(inner, vec![1, 2, 3, 4, 5]);
}

#[test]
fn walker_decode_variant_errors_on_wrong_variant() {
	let v = OptEnum::Unit;
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = OptEnum::walk_revisioned(&mut r).unwrap();
	let err = w.decode_varlen().expect_err("Unit is not Varlen — should error");
	match err {
		revision::Error::Deserialize(msg) => {
			assert!(msg.contains("variant mismatch"), "expected variant-mismatch, got: {msg}");
		}
		other => panic!("expected Deserialize error, got {other:?}"),
	}
}

// ---------------------------------------------------------------------------
// `into_<field>_bytes` accessor — borrowed wire bytes without inner decode.
//
// This is the escape hatch for `indexed_struct` types whose plain (non-
// `indexed_*`) fields can't be walked via `into_walk_<field>` on an
// `IndexedBorrowed` parent. The caller takes the bytes and constructs a
// child walker themselves (`T::walk_revisioned(&mut bytes)`).
// ---------------------------------------------------------------------------

#[test]
fn into_field_bytes_on_indexed_borrowed_round_trips() {
	let v = IndexedStruct {
		a: 11,
		b: 22,
		c: 33,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = IndexedStruct::walk_revisioned(&mut r).unwrap();
	// Take the middle field's bytes and decode them independently — the
	// returned slice borrows from the original payload (`Cow::Borrowed`).
	let b_bytes = w.into_b_bytes().unwrap();
	let mut sub: &[u8] = &b_bytes;
	let b: u32 =
		<u32 as revision::DeserializeRevisioned>::deserialize_revisioned(&mut sub).unwrap();
	assert_eq!(b, 22);
}

#[test]
fn into_field_bytes_on_indexed_borrowed_handles_first_and_last_fields() {
	let v = IndexedStruct {
		a: 100,
		b: 200,
		c: 300,
	};
	let bytes = revision::to_vec(&v).unwrap();

	// First field (offset table → bytes[0..4]).
	{
		let mut r: &[u8] = &bytes;
		let w = IndexedStruct::walk_revisioned(&mut r).unwrap();
		let a_bytes = w.into_a_bytes().unwrap();
		let mut sub: &[u8] = &a_bytes;
		let a: u32 =
			<u32 as revision::DeserializeRevisioned>::deserialize_revisioned(&mut sub).unwrap();
		assert_eq!(a, 100);
	}
	// Last field (extends to payload end — exercises the open-ended slice).
	{
		let mut r: &[u8] = &bytes;
		let w = IndexedStruct::walk_revisioned(&mut r).unwrap();
		let c_bytes = w.into_c_bytes().unwrap();
		let mut sub: &[u8] = &c_bytes;
		let c: u32 =
			<u32 as revision::DeserializeRevisioned>::deserialize_revisioned(&mut sub).unwrap();
		assert_eq!(c, 300);
	}
}

#[test]
fn into_field_bytes_on_wire_round_trips() {
	// Optimised (no `indexed_struct`) — the walker enters the Wire arm
	// rather than IndexedBorrowed, so the accessor goes through the
	// remaining()-snapshot + skip-and-recover path.
	let v = OptStruct {
		a: 42,
		b: 100,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = OptStruct::walk_revisioned(&mut r).unwrap();
	let a_bytes = w.into_a_bytes().unwrap();
	// `a` is the first field — bytes should be exactly the u32_le encoding
	// of `a` (4 bytes under the default codec).
	let mut sub: &[u8] = &a_bytes;
	let a: u32 =
		<u32 as revision::DeserializeRevisioned>::deserialize_revisioned(&mut sub).unwrap();
	assert_eq!(a, 42);
	assert_eq!(sub.len(), 0, "into_a_bytes should return exactly the field's bytes");
}

#[test]
fn into_field_bytes_on_wire_returns_borrowed_not_owned() {
	// The Wire arm uses the `BorrowedReader` contract to lifetime-extend
	// the consumed slice — verify we get `Cow::Borrowed` and not an
	// allocated `Cow::Owned`.
	let v = OptStruct {
		a: 1,
		b: 2,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = OptStruct::walk_revisioned(&mut r).unwrap();
	let a_bytes = w.into_a_bytes().unwrap();
	assert!(matches!(a_bytes, std::borrow::Cow::Borrowed(_)));
}

#[test]
fn into_field_bytes_on_indexed_borrowed_returns_borrowed_not_owned() {
	let v = IndexedStruct {
		a: 1,
		b: 2,
		c: 3,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = IndexedStruct::walk_revisioned(&mut r).unwrap();
	let b_bytes = w.into_b_bytes().unwrap();
	assert!(matches!(b_bytes, std::borrow::Cow::Borrowed(_)));
}

#[test]
fn into_field_bytes_errors_when_field_not_yet_introduced() {
	// `GuardedField` is `revision(1), revision(2)` — field `b` is added at
	// rev 2. Encoding a v1 shadow without `b` and walking it (wire_rev=1)
	// must reject `into_b_bytes()` with the conversion error emitted by
	// the macro's revision guard.
	#[revisioned(revision(1), revision(2))]
	struct GuardedField {
		a: u32,
		#[revision(start = 2, default_fn = "default_b")]
		b: u32,
	}
	impl GuardedField {
		fn default_b(_rev: u16) -> Result<u32, revision::Error> {
			Ok(0)
		}
	}

	#[revisioned(revision(1))]
	struct ShadowV1 {
		a: u32,
	}

	let bytes = revision::to_vec(&ShadowV1 {
		a: 99,
	})
	.unwrap();
	let mut r: &[u8] = &bytes;
	let w = GuardedField::walk_revisioned(&mut r).unwrap();
	let err = w.into_b_bytes().expect_err("b doesn't exist at wire rev 1 — must error");
	match err {
		revision::Error::Conversion(msg) => {
			assert!(
				msg.contains("into_b_bytes") && msg.contains("wire revision 1"),
				"unexpected guard message: {msg}",
			);
		}
		other => panic!("expected Conversion error, got {other:?}"),
	}
}

#[test]
fn into_field_bytes_works_on_mixed_history_at_optimised_rev() {
	// `MixedHistory` is `revision(1), revision(2, optimised)` — the
	// encoder emits rev 2 (Wire arm with envelope-skipped reader).
	let v = MixedHistory {
		a: 7,
		b: 11,
	};
	let bytes = revision::to_vec(&v).unwrap();
	let mut r: &[u8] = &bytes;
	let w = MixedHistory::walk_revisioned(&mut r).unwrap();
	let a_bytes = w.into_a_bytes().unwrap();
	let mut sub: &[u8] = &a_bytes;
	let a: u32 =
		<u32 as revision::DeserializeRevisioned>::deserialize_revisioned(&mut sub).unwrap();
	assert_eq!(a, 7);
}