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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! [`Reader`] and [`Writer`] implementations.
use {
core::{
mem::{self, transmute, MaybeUninit},
ptr,
slice::{from_raw_parts, from_raw_parts_mut},
},
thiserror::Error,
};
#[derive(Error, Debug)]
pub enum ReadError {
#[error("Attempting to read {0} bytes")]
ReadSizeLimit(usize),
#[error(
"Unsupported zero-copy operation: reader does not support deserializing zero-copy types"
)]
UnsupportedZeroCopy,
#[cfg(feature = "std")]
#[error(transparent)]
Io(#[from] std::io::Error),
}
pub type ReadResult<T> = core::result::Result<T, ReadError>;
#[cold]
pub const fn read_size_limit(len: usize) -> ReadError {
ReadError::ReadSizeLimit(len)
}
#[inline(always)]
pub(super) const fn transpose<const N: usize, T>(
src: &mut MaybeUninit<[T; N]>,
) -> &mut [MaybeUninit<T>; N] {
unsafe { transmute(src) }
}
/// Trait for structured reading of bytes from a source into potentially uninitialized memory.
///
/// # Advancement semantics
/// - `fill_*` methods never advance.
/// - `copy_into_*` and `borrow_*` methods advance by the number of bytes read.
/// - [`Reader::as_trusted_for`] advances the parent by the number of bytes requested.
///
/// # Zero-copy semantics
/// Only implement [`Reader::borrow_exact`] for sources where stable borrows into the backing storage are possible.
/// Callers should prefer [`Reader::fill_exact`] to remain compatible with readers that don’t support zero-copy.
/// Returns [`ReadError::UnsupportedZeroCopy`] for readers that do not support zero-copy.
pub trait Reader<'a> {
/// A variant of the [`Reader`] that can elide bounds checking within a given window.
///
/// Trusted variants of the [`Reader`] should generally not be constructed directly,
/// but rather by calling [`Reader::as_trusted_for`] on a trusted [`Reader`].
/// This will ensure that the safety invariants are upheld.
type Trusted<'b>: Reader<'a>
where
Self: 'b;
/// Return up to `n_bytes` from the internal buffer without advancing. Implementations may
/// read more data internally to satisfy future requests. Returns fewer than `n_bytes` at EOF.
///
/// This is _not_ required to return exactly `n_bytes`, it is required to return _up to_ `n_bytes`.
/// Use [`Reader::fill_exact`] if you need exactly `n_bytes`.
#[deprecated(
since = "0.4.6",
note = "use `copy_into_slice` if you ultimately intend to copy the slice, or \
`take_scoped` for a call-scoped borrow. Be advised that `take_scoped` may not be \
implemented for all readers."
)]
fn fill_buf(&mut self, n_bytes: usize) -> ReadResult<&[u8]>;
/// Return exactly `n_bytes` without advancing.
///
/// Errors if the source cannot provide enough bytes.
#[deprecated(
since = "0.4.6",
note = "use `copy_into_slice` if you ultimately intend to copy the slice, or \
`take_scoped` for a call-scoped borrow. Be advised that `take_scoped` may not be \
implemented for all readers."
)]
#[expect(deprecated)]
fn fill_exact(&mut self, n_bytes: usize) -> ReadResult<&[u8]> {
let src = self.fill_buf(n_bytes)?;
if src.len() != n_bytes {
return Err(read_size_limit(n_bytes));
}
Ok(src)
}
/// Return exactly `N` bytes as `&[u8; N]` without advancing.
///
/// Errors if fewer than `N` bytes are available.
#[deprecated(
since = "0.4.6",
note = "peek and consume APIs will be removed in 0.5."
)]
#[expect(deprecated)]
fn fill_array<const N: usize>(&mut self) -> ReadResult<&[u8; N]> {
let src = self.fill_exact(N)?;
// SAFETY:
// - `fill_exact` ensures we read N bytes.
Ok(unsafe { &*src.as_ptr().cast::<[u8; N]>() })
}
/// Return exactly `N` bytes as `&[u8; N]` without advancing.
///
/// Errors if fewer than `N` bytes are available.
#[inline]
#[deprecated(
since = "0.4.9",
note = "peek and consume APIs will be removed in 0.5."
)]
#[expect(deprecated)]
fn peek_array<const N: usize>(&mut self) -> ReadResult<&[u8; N]> {
let src = self.fill_exact(N)?;
// SAFETY:
// - `fill_exact` ensures we read N bytes.
Ok(unsafe { &*src.as_ptr().cast::<[u8; N]>() })
}
/// Return exactly `N` bytes as `[u8; N]` and advance by `N`.
///
/// Errors if fewer than `N` bytes are available.
#[inline(always)]
fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
let mut ar = MaybeUninit::<[u8; N]>::uninit();
self.copy_into_slice(transpose(&mut ar))?;
Ok(unsafe { ar.assume_init() })
}
/// Return the next byte and advance by `1`.
///
/// Errors if the reader is exhausted.
#[inline(always)]
fn take_byte(&mut self) -> ReadResult<u8> {
Ok(self.take_array::<1>()?[0])
}
/// Zero-copy: return a borrowed slice of exactly `len` bytes and advance by `len`.
///
/// The returned slice is tied to `'a`. Prefer [`Reader::take_scoped`] unless you truly need zero-copy.
/// Errors for readers that don't support zero-copy.
#[inline]
#[deprecated(since = "0.4.6", note = "use `take_borrowed`.")]
fn borrow_exact(&mut self, len: usize) -> ReadResult<&'a [u8]> {
Self::take_borrowed(self, len)
}
/// Return a borrowed slice of exactly `len` bytes and advance
/// the reader by `len`.
///
/// The returned slice is tied to the reader's backing lifetime `'a`.
/// This means the slice may outlive the borrow of the call, and is
/// valid after the reader is dropped or reborrowed.
///
/// This stronger guarantee is typically only possible for readers backed
/// by stable storage (for example `&'a [u8]` or memory-mapped buffers).
///
/// Prefer [`Reader::take_scoped`] unless you specifically require a slice
/// that lives for `'a`. Prefer [`Reader::copy_into_slice`] if you ultimately
/// intend to copy the slice.
///
/// Errors if the reader cannot provide `len` bytes or does not support
/// borrowing into stable storage that outlives the reader.
#[inline]
fn take_borrowed(&mut self, len: usize) -> ReadResult<&'a [u8]> {
Self::take_borrowed_mut(self, len).map(|s| &*s)
}
/// Zero-copy: return a borrowed mutable slice of exactly `len` bytes and advance by `len`.
///
/// Errors for readers that don't support mutable zero-copy.
#[deprecated(since = "0.4.6", note = "use `take_borrowed_mut`.")]
#[inline]
fn borrow_exact_mut(&mut self, len: usize) -> ReadResult<&'a mut [u8]> {
self.take_borrowed_mut(len)
}
/// Return a mutably borrowed slice of exactly `len` bytes and advance
/// the reader by `len`.
///
/// The returned slice is tied to the reader's backing lifetime `'a`.
/// This means the slice may outlive the borrow of the call, and is
/// valid after the reader is dropped or reborrowed.
///
/// This stronger guarantee is typically only possible for readers backed
/// by stable storage (for example `&'a mut [u8]` or memory-mapped buffers).
///
/// Errors if the reader cannot provide `len` bytes or does not support
/// mutable borrowing into stable, mutable storage that outlives the reader.
#[expect(unused_variables)]
fn take_borrowed_mut(&mut self, len: usize) -> ReadResult<&'a mut [u8]> {
// Return a more specific error for readers that don't support mutable borrowing
// in the next breaking release.
Err(ReadError::UnsupportedZeroCopy)
}
/// Return a call-site scoped slice of exactly `len` bytes and advance by `len`.
///
/// The returned slice is tied to the borrow of `self`, meaning it is only
/// valid while the current borrow of the reader is alive. Implementations
/// are free to return slices backed by internal buffers or transient windows
/// into the underlying source.
///
/// Prefer [`Reader::copy_into_slice`] if you ultimately intend to copy the slice.
///
/// Errors for readers that don't support call-site scoped borrowing.
#[inline]
#[expect(unused_variables)]
fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
// Return a more specific error for readers that don't support scoped borrowing
// in the next breaking release.
Err(ReadError::UnsupportedZeroCopy)
}
/// Advance by exactly `amt` bytes without bounds checks.
///
/// May panic if fewer than `amt` bytes remain.
///
/// # Safety
///
/// - `amt` must be less than or equal to the number of bytes remaining in the reader.
#[deprecated(
since = "0.4.9",
note = "peek and consume APIs will be removed in 0.5."
)]
unsafe fn consume_unchecked(&mut self, amt: usize);
/// Advance the reader exactly `amt` bytes, returning an error if the source does not have enough bytes.
#[deprecated(
since = "0.4.9",
note = "peek and consume APIs will be removed in 0.5."
)]
fn consume(&mut self, amt: usize) -> ReadResult<()>;
/// Advance the parent by `n_bytes` and return a [`Reader`] that can elide bounds checks within
/// that `n_bytes` window.
///
/// Implementors must:
/// - Ensure that either at least `n_bytes` bytes are available backing the
/// returned reader, or return an error.
/// - Arrange that the returned `Trusted` reader's methods operate within
/// that `n_bytes` window (it may buffer or prefetch arbitrarily).
///
/// Note:
/// - `as_trusted_for` is intended for callers that know they will operate
/// within a fixed-size window and want to avoid intermediate bounds checks.
/// - If you simply want to advance the parent by `n_bytes` without using
/// a trusted window, prefer `consume(n_bytes)` instead.
///
/// # Safety
///
/// The caller must ensure that, through the returned reader, they do not
/// cause more than `n_bytes` bytes to be logically read or consumed
/// without performing additional bounds checks.
///
/// Concretely:
/// - The total number of bytes accessed/consumed via the `Trusted` reader
/// (`fill_*`, `copy_into_*`, `consume`, etc.) must be **<= `n_bytes`**.
///
/// Violating this is undefined behavior, because `Trusted` readers are
/// permitted to elide bounds checks within the `n_bytes` window; reading past the
/// `n_bytes` window may read past the end of the underlying buffer.
unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> ReadResult<Self::Trusted<'_>>;
/// Return a reference to the next byte without advancing.
///
/// May buffer more bytes if necessary. Errors if no bytes remain.
#[inline]
#[deprecated(since = "0.4.6", note = "use `peek_byte`.")]
#[expect(deprecated)]
fn peek(&mut self) -> ReadResult<&u8> {
self.fill_buf(1)?.first().ok_or_else(|| read_size_limit(1))
}
/// Get the next byte without advancing.
///
/// Errors if no bytes remain.
#[inline]
#[expect(deprecated)]
#[deprecated(
since = "0.4.9",
note = "peek and consume APIs will be removed in 0.5."
)]
fn peek_byte(&mut self) -> ReadResult<u8> {
Ok(self.peek_array::<1>()?[0])
}
/// Get a mutable reference to the [`Reader`].
///
/// Useful in situations where one only has an `impl Reader<'de>` that
/// needs to be passed to mulitple functions requiring `impl Reader<'de>`.
///
/// Always prefer this over `&mut reader` to avoid recursive borrows.
///
/// ```
/// # use wincode::{io::Reader, ReadResult, config::Config, SchemaRead};
/// # use core::mem::MaybeUninit;
/// struct FooBar {
/// foo: u32,
/// bar: u32,
/// }
///
/// unsafe impl<'de, C: Config> SchemaRead<'de, C> for FooBar {
/// type Dst = Self;
///
/// fn read(mut reader: impl Reader<'de>, dst: &mut MaybeUninit<Self>) -> ReadResult<()> {
/// // `reader.by_ref()`; Good âś…
/// let foo = <u32 as SchemaRead<'de, C>>::get(reader.by_ref())?;
/// let bar = <u32 as SchemaRead<'de, C>>::get(reader)?;
/// dst.write(FooBar { foo, bar });
/// Ok(())
/// }
/// }
/// ```
#[inline(always)]
fn by_ref(&mut self) -> impl Reader<'a> {
self
}
/// Copy and consume exactly `dst.len()` bytes from the [`Reader`] into `dst`.
///
/// # Safety
///
/// - `dst` must not overlap with the internal buffer.
#[inline]
#[expect(deprecated)]
fn copy_into_slice(&mut self, dst: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
let src = self.fill_exact(dst.len())?;
// SAFETY:
// - `fill_exact` must do the appropriate bounds checking.
unsafe {
ptr::copy_nonoverlapping(src.as_ptr().cast(), dst.as_mut_ptr(), dst.len());
self.consume_unchecked(dst.len());
}
Ok(())
}
/// Copy and consume exactly `N` bytes from the [`Reader`] into `dst`.
///
/// # Safety
///
/// - `dst` must not overlap with the internal buffer.
#[inline]
#[expect(deprecated)]
#[deprecated(since = "0.4.6", note = "use `take_array` or `copy_into_slice`.")]
fn copy_into_array<const N: usize>(
&mut self,
dst: &mut MaybeUninit<[u8; N]>,
) -> ReadResult<()> {
let src = self.fill_array::<N>()?;
// SAFETY:
// - `fill_array` must do the appropriate bounds checking.
unsafe {
ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), 1);
self.consume_unchecked(N);
}
Ok(())
}
/// Copy and consume exactly `size_of::<T>()` bytes from the [`Reader`] into `dst`.
///
/// # Safety
///
/// - `T` must be initialized by reads of `size_of::<T>()` bytes.
/// - `dst` must not overlap with the internal buffer.
#[inline]
unsafe fn copy_into_t<T>(&mut self, dst: &mut MaybeUninit<T>) -> ReadResult<()> {
// SAFETY: Caller ensures that `T` is initialized by reads of `size_of::<T>()` bytes.
let dst = unsafe {
from_raw_parts_mut(dst.as_mut_ptr().cast::<MaybeUninit<u8>>(), size_of::<T>())
};
self.copy_into_slice(dst)
}
/// Copy and consume exactly `dst.len() * size_of::<T>()` bytes from the [`Reader`] into `dst`.
///
/// # Safety
///
/// - `T` must be initialized by reads of `size_of::<T>()` bytes.
/// - `dst` must not overlap with the internal buffer.
#[inline]
unsafe fn copy_into_slice_t<T>(&mut self, dst: &mut [MaybeUninit<T>]) -> ReadResult<()> {
let len = size_of_val(dst);
// SAFETY: Caller ensures that `T` is initialized by reads of `size_of::<T>()` bytes.
let dst = unsafe { from_raw_parts_mut(dst.as_mut_ptr().cast::<MaybeUninit<u8>>(), len) };
self.copy_into_slice(dst)
}
}
impl<'a, R: Reader<'a> + ?Sized> Reader<'a> for &mut R {
type Trusted<'b>
= R::Trusted<'b>
where
Self: 'b;
#[inline(always)]
fn by_ref(&mut self) -> impl Reader<'a> {
&mut **self
}
#[inline(always)]
#[expect(deprecated)]
fn fill_buf(&mut self, n_bytes: usize) -> ReadResult<&[u8]> {
(*self).fill_buf(n_bytes)
}
#[inline(always)]
#[expect(deprecated)]
fn fill_exact(&mut self, n_bytes: usize) -> ReadResult<&[u8]> {
(*self).fill_exact(n_bytes)
}
#[inline(always)]
#[expect(deprecated)]
fn fill_array<const N: usize>(&mut self) -> ReadResult<&[u8; N]> {
(*self).fill_array()
}
#[inline(always)]
#[expect(deprecated)]
fn peek_array<const N: usize>(&mut self) -> ReadResult<&[u8; N]> {
(*self).peek_array()
}
#[inline(always)]
fn take_array<const N: usize>(&mut self) -> ReadResult<[u8; N]> {
(*self).take_array()
}
#[inline(always)]
fn take_byte(&mut self) -> ReadResult<u8> {
(*self).take_byte()
}
#[inline(always)]
#[expect(deprecated)]
fn borrow_exact(&mut self, len: usize) -> ReadResult<&'a [u8]> {
(*self).borrow_exact(len)
}
#[inline(always)]
fn take_borrowed(&mut self, len: usize) -> ReadResult<&'a [u8]> {
(*self).take_borrowed(len)
}
#[inline(always)]
#[expect(deprecated)]
fn borrow_exact_mut(&mut self, len: usize) -> ReadResult<&'a mut [u8]> {
(*self).borrow_exact_mut(len)
}
#[inline(always)]
fn take_borrowed_mut(&mut self, len: usize) -> ReadResult<&'a mut [u8]> {
(*self).take_borrowed_mut(len)
}
#[inline(always)]
fn take_scoped(&mut self, len: usize) -> ReadResult<&[u8]> {
(*self).take_scoped(len)
}
#[inline(always)]
#[expect(deprecated)]
unsafe fn consume_unchecked(&mut self, amt: usize) {
(*self).consume_unchecked(amt)
}
#[inline(always)]
#[expect(deprecated)]
fn consume(&mut self, amt: usize) -> ReadResult<()> {
(*self).consume(amt)
}
#[inline(always)]
unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> ReadResult<Self::Trusted<'_>> {
(*self).as_trusted_for(n_bytes)
}
#[inline(always)]
#[expect(deprecated)]
fn peek(&mut self) -> ReadResult<&u8> {
(*self).peek()
}
#[inline(always)]
#[expect(deprecated)]
fn peek_byte(&mut self) -> ReadResult<u8> {
(*self).peek_byte()
}
#[inline(always)]
fn copy_into_slice(&mut self, dst: &mut [MaybeUninit<u8>]) -> ReadResult<()> {
(*self).copy_into_slice(dst)
}
#[inline(always)]
#[expect(deprecated)]
fn copy_into_array<const N: usize>(
&mut self,
dst: &mut MaybeUninit<[u8; N]>,
) -> ReadResult<()> {
(*self).copy_into_array(dst)
}
#[inline(always)]
unsafe fn copy_into_t<T>(&mut self, dst: &mut MaybeUninit<T>) -> ReadResult<()> {
(*self).copy_into_t(dst)
}
#[inline(always)]
unsafe fn copy_into_slice_t<T>(&mut self, dst: &mut [MaybeUninit<T>]) -> ReadResult<()> {
(*self).copy_into_slice_t(dst)
}
}
#[derive(Error, Debug)]
pub enum WriteError {
#[error("Attempting to write {0} bytes")]
WriteSizeLimit(usize),
#[cfg(feature = "std")]
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[cold]
const fn write_size_limit(len: usize) -> WriteError {
WriteError::WriteSizeLimit(len)
}
pub type WriteResult<T> = core::result::Result<T, WriteError>;
/// Trait for structured writing of bytes into a source of potentially uninitialized memory.
pub trait Writer {
/// A variant of the [`Writer`] that can elide bounds checking within a given window.
///
/// Trusted variants of the [`Writer`] should generally not be constructed directly,
/// but rather by calling [`Writer::as_trusted_for`] on a trusted [`Writer`].
/// This will ensure that the safety invariants are upheld.
type Trusted<'a>: Writer
where
Self: 'a;
/// Get a mutable reference to the [`Writer`].
///
/// Useful in situations where one has an `impl Writer` that
/// needs to be passed to mulitple functions requiring `impl Writer`.
///
/// Always prefer this over `&mut writer` to avoid recursive borrows.
///
/// ```
/// # use wincode::{io::Writer, WriteResult, config::Config, SchemaWrite};
/// # use core::mem::MaybeUninit;
/// struct FooBar {
/// foo: u32,
/// bar: u32,
/// }
///
/// unsafe impl<C: Config> SchemaWrite<C> for FooBar {
/// type Src = Self;
/// #
/// # fn size_of(src: &Self::Src) -> WriteResult<usize> {
/// # let foo = <u32 as SchemaWrite<C>>::size_of(&src.foo)?;
/// # let bar = <u32 as SchemaWrite<C>>::size_of(&src.bar)?;
/// # Ok(foo + bar)
/// # }
///
/// fn write(mut writer: impl Writer, src: &Self::Src) -> WriteResult<()> {
/// // `writer.by_ref()`; Good âś…
/// let foo = <u32 as SchemaWrite<C>>::write(writer.by_ref(), &src.foo)?;
/// let bar = <u32 as SchemaWrite<C>>::write(writer, &src.bar)?;
/// Ok(())
/// }
/// }
/// ```
#[inline(always)]
fn by_ref(&mut self) -> impl Writer {
self
}
/// Finalize the writer by performing any required cleanup or flushing.
///
/// # Regarding trusted writers
///
/// Trusted writers are not guaranteed to live as long as the parent [`Writer`] that
/// created them, and are typically short-lived. wincode will call `finish` after
/// trusted writers have completed their work, so they may rely on `finish` perform
/// local cleanup when needed. Importantly, trusted writers must not perform actions
/// that would invalidate the parent [`Writer`].
///
/// For example, a file writer may buffer internally and delegate to trusted
/// sub-writers with their own buffers. These trusted writers should not close
/// the underlying file descriptor or other parent-owned resources, as that would
/// invalidate the parent writer.
fn finish(&mut self) -> WriteResult<()> {
Ok(())
}
/// Write exactly `src.len()` bytes from the given `src` into the writer.
fn write(&mut self, src: &[u8]) -> WriteResult<()>;
/// Advance the parent by `n_bytes` and return a [`Writer`] that can elide bounds checks within
/// that `n_bytes` window.
///
/// Implementors must:
/// - Ensure that either at least `n_bytes` bytes are available backing the
/// returned writer, or return an error.
/// - Arrange that the returned `Trusted` writer's methods operate within
/// that `n_bytes` window (it may buffer or prefetch arbitrarily).
///
/// Note:
/// - `as_trusted_for` is intended for callers that know they will operate
/// within an exact-size window and want to avoid intermediate bounds checks.
///
/// # Safety
///
/// The caller must treat the returned writer as having exclusive access to
/// exactly `n_bytes` bytes of **uninitialized** output space in the parent,
/// and must:
///
/// - Ensure that no write performed through the `Trusted` writer can
/// address memory outside of that `n_bytes` window.
/// - In case the caller does not return an error, ensure that, before the
/// `Trusted` writer is finished or the parent writer is used again,
/// **every byte** in that `n_bytes` window has been initialized at least
/// once via the `Trusted` writer.
/// - In case the caller does not return an error, call [`Writer::finish`]
/// on the `Trusted` writer when writing is complete and before the parent
/// writer is used again.
///
/// Concretely:
/// - All writes performed via the `Trusted` writer (`write`, `write_t`,
/// `write_slice_t`, etc.) must stay within the `[0, n_bytes)` region of
/// the reserved space.
/// - It is permitted to overwrite the same bytes multiple times, but if the
/// caller returns no error, the union of all bytes written must cover the
/// entire `[0, n_bytes)` window.
///
/// Violating this is undefined behavior, because:
/// - `Trusted` writers are permitted to elide bounds checks within the
/// `n_bytes` window; writing past the window may write past the end of
/// the underlying destination.
/// - Failing to initialize all `n_bytes` without returning an error may
/// leave uninitialized memory in the destination that later safe code
/// assumes to be fully initialized.
unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> WriteResult<Self::Trusted<'_>>;
/// Write `T` as bytes into the source.
///
/// # Safety
///
/// - `T` must be plain ol' data.
#[inline]
unsafe fn write_t<T: ?Sized>(&mut self, src: &T) -> WriteResult<()> {
let src = from_raw_parts((src as *const T).cast::<u8>(), size_of_val(src));
self.write(src)?;
Ok(())
}
/// Write `[T]` as bytes into the source.
///
/// # Safety
///
/// - `T` must be plain ol' data.
#[inline]
unsafe fn write_slice_t<T>(&mut self, src: &[T]) -> WriteResult<()> {
let len = size_of_val(src);
let src = from_raw_parts(src.as_ptr().cast::<u8>(), len);
self.write(src)?;
Ok(())
}
}
impl<W: Writer + ?Sized> Writer for &mut W {
type Trusted<'a>
= W::Trusted<'a>
where
Self: 'a;
#[inline(always)]
fn by_ref(&mut self) -> impl Writer {
&mut **self
}
#[inline(always)]
fn finish(&mut self) -> WriteResult<()> {
(*self).finish()
}
#[inline(always)]
fn write(&mut self, src: &[u8]) -> WriteResult<()> {
(*self).write(src)
}
#[inline(always)]
unsafe fn as_trusted_for(&mut self, n_bytes: usize) -> WriteResult<Self::Trusted<'_>> {
(*self).as_trusted_for(n_bytes)
}
#[inline(always)]
unsafe fn write_t<T: ?Sized>(&mut self, src: &T) -> WriteResult<()> {
(*self).write_t(src)
}
#[inline(always)]
unsafe fn write_slice_t<T>(&mut self, src: &[T]) -> WriteResult<()> {
(*self).write_slice_t(src)
}
}
mod cursor;
mod slice;
#[cfg(feature = "alloc")]
mod vec;
pub use {cursor::Cursor, slice::*};