wincode 0.6.1

Fast bincode de/serialization with placement initialization
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use {
    crate::{
        ReadResult, SchemaRead, SchemaReadContext, SchemaWrite, TypeMeta, WriteResult,
        config::{Config, ConfigCore},
        containers::decode_into_slice_t,
        error::invalid_utf8_encoding,
        io::{Reader, Writer},
        len::SeqLen,
        schema::{size_of_elem_slice, write_elem_slice_prealloc_check},
    },
    alloc::alloc::Layout,
    bumpalo::{
        Bump,
        boxed::Box,
        collections::{String, Vec},
    },
    core::{mem::MaybeUninit, slice::from_raw_parts_mut},
};

unsafe impl<'de, 'bump, C: Config, T> SchemaReadContext<'de, C, &'bump Bump> for Vec<'bump, T>
where
    T: SchemaRead<'de, C>,
    T::Dst: 'bump,
{
    type Dst = Vec<'bump, T::Dst>;

    #[inline]
    fn read_with_context(
        ctx: &'bump Bump,
        mut reader: impl Reader<'de>,
        dst: &mut MaybeUninit<Self::Dst>,
    ) -> ReadResult<()> {
        let len = C::LengthEncoding::read_prealloc_check::<T::Dst>(reader.by_ref())?;
        let mut vec: Vec<'bump, T::Dst> = Vec::with_capacity_in(len, ctx);
        // SAFETY: `Vec::with_capacity_in(len, ctx)` allocated storage for at
        // least `len` elements, and `as_mut_ptr` points to that uninitialized
        // storage while `vec` is alive and not reallocated.
        let slice = unsafe { from_raw_parts_mut(vec.as_mut_ptr().cast::<MaybeUninit<_>>(), len) };
        decode_into_slice_t::<T, C>(reader, slice)?;
        // SAFETY: `decode_into_slice_t` initializes all `len` elements on success.
        unsafe { vec.set_len(len) };

        dst.write(vec);
        Ok(())
    }
}

unsafe impl<'bump, C: Config, T> SchemaWrite<C> for Vec<'bump, T>
where
    T: SchemaWrite<C>,
    T::Src: Sized,
{
    type Src = Vec<'bump, T::Src>;

    #[inline]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        size_of_elem_slice::<T, C::LengthEncoding, C>(src)
    }

    #[inline]
    fn write(writer: impl Writer, src: &Self::Src) -> WriteResult<()> {
        write_elem_slice_prealloc_check::<T, C::LengthEncoding, C>(writer, src)
    }
}

unsafe impl<'de, 'bump, C: Config> SchemaReadContext<'de, C, &'bump Bump> for String<'bump> {
    type Dst = String<'bump>;

    #[inline]
    fn read_with_context(
        ctx: &'bump Bump,
        reader: impl Reader<'de>,
        dst: &mut MaybeUninit<Self::Dst>,
    ) -> ReadResult<()> {
        let bytes = <Vec<u8> as SchemaReadContext<C, _>>::get_with_context(ctx, reader)?;
        match String::from_utf8(bytes) {
            Ok(s) => {
                dst.write(s);
                Ok(())
            }
            Err(e) => Err(invalid_utf8_encoding(e.utf8_error())),
        }
    }
}

unsafe impl<'bump, C: Config> SchemaWrite<C> for String<'bump> {
    type Src = String<'bump>;

    #[inline]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        <str as SchemaWrite<C>>::size_of(src)
    }

    #[inline]
    fn write(writer: impl Writer, src: &Self::Src) -> WriteResult<()> {
        C::LengthEncoding::prealloc_check::<u8>(src.len())?;
        <str as SchemaWrite<C>>::write(writer, src)
    }
}

unsafe impl<'de, 'bump, C: ConfigCore, T> SchemaReadContext<'de, C, &'bump Bump> for Box<'bump, T>
where
    T: SchemaRead<'de, C>,
    T::Dst: 'bump,
{
    type Dst = Box<'bump, T::Dst>;

    const TYPE_META: TypeMeta = T::TYPE_META.keep_zero_copy(false);

    #[inline]
    fn read_with_context(
        ctx: &'bump Bump,
        reader: impl Reader<'de>,
        dst: &mut MaybeUninit<Self::Dst>,
    ) -> ReadResult<()> {
        let ptr = ctx.alloc_layout(Layout::new::<T::Dst>()).as_ptr();

        // SAFETY: `ptr` was allocated with `Layout::new::<T::Dst>()`, so it is
        // non-null, properly aligned, and valid for one `MaybeUninit<T::Dst>`.
        T::read(reader, unsafe { &mut *ptr.cast::<MaybeUninit<T::Dst>>() })?;
        // SAFETY: `T::read` initialized the allocation on success, and
        // `Box::from_raw` accepts pointers allocated by this `Bump`.
        let boxed = unsafe { Box::from_raw(ptr.cast::<T::Dst>()) };
        dst.write(boxed);

        Ok(())
    }
}

unsafe impl<'bump, C: ConfigCore, T> SchemaWrite<C> for Box<'bump, T>
where
    T: SchemaWrite<C>,
{
    type Src = Box<'bump, T::Src>;

    const TYPE_META: TypeMeta = T::TYPE_META.keep_zero_copy(false);

    #[inline]
    fn size_of(src: &Self::Src) -> WriteResult<usize> {
        <T as SchemaWrite<C>>::size_of(src)
    }

    #[inline]
    fn write(writer: impl Writer, src: &Self::Src) -> WriteResult<()> {
        <T as SchemaWrite<C>>::write(writer, src)
    }
}

/// Borrowed elements in bumpalo containers must not outlive the input bytes they reference.
///
/// ```compile_fail
/// use bumpalo::{Bump, collections::Vec};
/// use wincode::{deserialize_with_context, serialize};
///
/// let bump = Bump::new();
/// let deserialized: Vec<&[u8]>;
///
/// {
///     let src = [b"borrowed".as_slice()];
///     let serialized = serialize(&src[..]).unwrap();
///     deserialized = deserialize_with_context(&bump, &serialized).unwrap();
/// }
///
/// assert_eq!(deserialized[0], b"borrowed");
/// ```
#[expect(dead_code)]
fn bumpalo_vec_of_borrowed_slices_cannot_outlive_input() {}

/// References to elements stored in bumpalo containers must not outlive the container.
///
/// ```compile_fail
/// use bumpalo::{Bump, collections::Vec};
/// use wincode::{deserialize_with_context, serialize};
///
/// let serialized = serialize(&[b"borrowed".as_slice()][..]).unwrap();
/// let slot_ref: &&[u8];
///
/// {
///     let bump = Bump::new();
///     let vec: Vec<&[u8]> = deserialize_with_context(&bump, &serialized).unwrap();
///     slot_ref = &vec[0];
/// }
///
/// assert_eq!(*slot_ref, b"borrowed");
/// ```
#[expect(dead_code)]
fn bumpalo_vec_element_references_cannot_outlive_container() {}

/// Owned bumpalo values must not outlive the `Bump` allocator that stores their contents.
///
/// ```compile_fail
/// use bumpalo::{Bump, collections::String};
/// use wincode::{deserialize_with_context, serialize};
///
/// let deserialized: String;
///
/// {
///     let bump = Bump::new();
///     let serialized = serialize("owned in bump").unwrap();
///     deserialized = deserialize_with_context(&bump, &serialized).unwrap();
/// }
///
/// assert_eq!(deserialized.as_str(), "owned in bump");
/// ```
#[expect(dead_code)]
fn bumpalo_owned_values_cannot_outlive_arena() {}

/// Borrowed values from bumpalo-backed input bytes must not outlive the input buffer.
///
/// ```compile_fail
/// use bumpalo::{Bump, collections::Vec};
/// use wincode::{deserialize, serialize};
///
/// let deserialized: &[u8];
///
/// {
///     let bump = Bump::new();
///     let serialized = serialize(b"borrowed".as_slice()).unwrap();
///     let bytes = Vec::from_iter_in(serialized, &bump);
///     deserialized = deserialize(&bytes).unwrap();
/// }
///
/// assert_eq!(deserialized, b"borrowed");
/// ```
#[expect(dead_code)]
fn borrowed_values_from_bumpalo_input_cannot_outlive_input_buffer() {}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{deserialize_with_context, proptest_config::proptest_cfg, serialize},
        proptest::prelude::*,
    };

    #[test]
    fn vec_round_trip() {
        proptest!(proptest_cfg(), |(val: alloc::vec::Vec<u64>)| {
            let bump = Bump::new();
            let val = Vec::from_iter_in(val, &bump);

            let serialized = serialize(&val).unwrap();

            let deserialized: Vec<u64> = deserialize_with_context(&bump, &serialized).unwrap();
            prop_assert_eq!(deserialized, val);
        });
    }

    #[test]
    fn string_round_trip() {
        proptest!(proptest_cfg(), |(val: alloc::string::String)| {
            let bump = Bump::new();
            let val = String::from_str_in(&val, &bump);

            let serialized = serialize(&val).unwrap();

            let deserialized: String = deserialize_with_context(&bump, &serialized).unwrap();
            prop_assert_eq!(deserialized, val);
        });
    }

    #[test]
    fn box_round_trip() {
        #[derive(SchemaWrite, SchemaRead, Debug, PartialEq, proptest_derive::Arbitrary)]
        #[wincode(internal)]
        struct Test {
            foo: u64,
            bar: alloc::string::String,
            baz: bool,
        }

        proptest!(proptest_cfg(), |(val: Test)| {
            let bump = Bump::new();
            let val = Box::new_in(val, &bump);

            let serialized = serialize(&val).unwrap();

            let deserialized: Box<Test> = deserialize_with_context(&bump, &serialized).unwrap();
            prop_assert_eq!(deserialized, val);
        });
    }

    /// Owned bumpalo values can outlive the input bytes because their contents live in the `Bump`.
    #[test]
    fn owned_string_can_outlive_input_bytes() {
        let bump = Bump::new();
        let deserialized: String;

        {
            // bumpalo::String owns its contents, so `deserialized` should outlive the block,
            // even though input bytes are temporary.
            let serialized = serialize("owned in bump").unwrap();
            deserialized = deserialize_with_context(&bump, &serialized).unwrap();
        }

        assert_eq!(deserialized.as_str(), "owned in bump");
    }

    /// Copied element references can outlive the bumpalo container they were stored in.
    #[test]
    fn copied_input_borrow_can_outlive_bumpalo_container() {
        let serialized = serialize(&[b"borrowed".as_slice()][..]).unwrap();
        let bytes_ref: &[u8];

        {
            let bump = Bump::new();
            let vec: Vec<&[u8]> = deserialize_with_context(&bump, &serialized).unwrap();
            bytes_ref = vec[0];
        }

        assert_eq!(bytes_ref, b"borrowed");
    }

    #[test]
    fn context_derive_struct_can_outlive_input_bytes() {
        #[derive(SchemaRead, SchemaWrite, Debug, PartialEq)]
        #[wincode(internal, context = "&'bump Bump")]
        struct Foo<'bump> {
            id: u32,
            #[wincode(context)]
            bar: String<'bump>,
            #[wincode(context)]
            baz: Vec<'bump, u8>,
        }
        let bump = Bump::new();
        let foo = Foo {
            id: 42,
            bar: String::from_str_in("bar", &bump),
            baz: bumpalo::vec![in &bump; 1, 2, 3],
        };
        let deserialized: Foo = {
            let serialized = serialize(&foo).unwrap();
            deserialize_with_context(&bump, &serialized).unwrap()
        };

        assert_eq!(deserialized, foo);
    }

    #[test]
    fn context_derive_supports_generic_fields_and_other_lifetimes() {
        #[derive(SchemaRead, SchemaWrite, Debug, PartialEq)]
        #[wincode(internal, context = "&'bump Bump")]
        struct Foo<'bump, 'input, T> {
            #[wincode(context)]
            values: Vec<'bump, T>,
            borrowed: &'input u8,
        }

        let bump = Bump::new();
        let borrowed = 42;
        let foo = Foo {
            values: bumpalo::vec![in &bump; 1_u16, 2, 3],
            borrowed: &borrowed,
        };
        let deserialized_values = {
            let serialized = serialize(&foo).unwrap();
            let deserialized: Foo<u16> = deserialize_with_context(&bump, &serialized).unwrap();
            assert_eq!(deserialized.borrowed, foo.borrowed);
            deserialized.values
        };

        // The context-backed generic field can outlive the input, while the field
        // with the independent `'input` lifetime remains scoped to it.
        assert_eq!(deserialized_values, foo.values);
    }

    #[test]
    fn context_derive_enum_can_outlive_input_bytes() {
        #[derive(SchemaRead, SchemaWrite, Debug, PartialEq)]
        #[wincode(internal, context = "&'bump Bump")]
        enum Foo<'bump> {
            Unit,
            Data {
                id: u32,
                #[wincode(context)]
                value: String<'bump>,
            },
        }

        let bump = Bump::new();
        let foo = Foo::Data {
            id: 42,
            value: String::from_str_in("value", &bump),
        };
        let deserialized: Foo = {
            let serialized = serialize(&foo).unwrap();
            deserialize_with_context(&bump, &serialized).unwrap()
        };

        assert_eq!(deserialized, foo);
    }

    #[test]
    fn context_derive_supports_with_adapter() {
        struct StringAdapter<'bump>(core::marker::PhantomData<&'bump Bump>);

        unsafe impl<'de, 'bump, C: Config> SchemaReadContext<'de, C, &'bump Bump> for StringAdapter<'bump> {
            type Dst = String<'bump>;

            const TYPE_META: TypeMeta =
                <String<'bump> as SchemaReadContext<'de, C, &'bump Bump>>::TYPE_META;

            fn read_with_context(
                ctx: &'bump Bump,
                reader: impl Reader<'de>,
                dst: &mut MaybeUninit<Self::Dst>,
            ) -> ReadResult<()> {
                <String<'bump> as SchemaReadContext<'de, C, &'bump Bump>>::read_with_context(
                    ctx, reader, dst,
                )
            }
        }

        unsafe impl<'bump, C: Config> SchemaWrite<C> for StringAdapter<'bump> {
            type Src = String<'bump>;

            const TYPE_META: TypeMeta = <String<'bump> as SchemaWrite<C>>::TYPE_META;

            fn size_of(src: &Self::Src) -> WriteResult<usize> {
                <String<'bump> as SchemaWrite<C>>::size_of(src)
            }

            fn write(writer: impl Writer, src: &Self::Src) -> WriteResult<()> {
                <String<'bump> as SchemaWrite<C>>::write(writer, src)
            }
        }

        #[derive(SchemaRead, SchemaWrite, Debug, PartialEq)]
        #[wincode(internal, context = "&'bump Bump")]
        struct Foo<'bump> {
            #[wincode(with = "StringAdapter<'bump>", context)]
            value: String<'bump>,
        }

        let bump = Bump::new();
        let foo = Foo {
            value: String::from_str_in("value", &bump),
        };
        let deserialized: Foo = {
            let serialized = serialize(&foo).unwrap();
            deserialize_with_context(&bump, &serialized).unwrap()
        };

        assert_eq!(deserialized, foo);
    }
}