ender 0.5.2

An encoding library to work with any binary data format
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
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! An abstraction over the underlying IO implementation, removing
//! unneeded elements and functions, while improving the interoperability
//! with the library.<br>
//! Custom [`Write`], [`Read`], [`BorrowRead`] traits are provided, as well
//! as a compatibility layer with `std::io` (see [`Std`])

use crate::{EncodingError, EncodingResult, SeekError};

#[allow(unused)]
fn usize_to_u64(val: usize) -> u64 {
    // PANIC SAFETY
    // `as` conversion never fails, unless we are on a >64-bit system I guess?
    val as _
}

#[allow(unused)]
fn isize_to_i64(val: isize) -> i64 {
    // PANIC SAFETY
    // Same as above
    val as _
}

#[allow(unused)]
fn u64_to_usize(val: u64) -> usize {
    assert!(val <= isize::MAX as _);

    val as _
}

#[allow(unused)]
fn i64_to_isize(val: i64) -> isize {
    assert!(val <= isize::MAX as _);

    val as _
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
fn io_err(err: EncodingError) -> std::io::Error {
    match err {
        EncodingError::IOError(error) => {
            std::io::Error::from(<std::io::ErrorKind as From<_>>::from(error))
        }
        EncodingError::UnexpectedEnd => std::io::Error::from(std::io::ErrorKind::UnexpectedEof),
        error => std::io::Error::new(std::io::ErrorKind::Other, error),
    }
}

/// A compatibility layer between this crate's I/O traits and `std::io` traits.
///
/// If `T` implements either [`std::io::Write`], [`std::io::Read`], [`std::io::Seek`]
/// or any combination of those, `Std<T>` will implement either [`Write`], [`Read`], [`Seek`]
/// or any combination of those, and vice versa.
///
/// The memory layout is always guaranteed to be that of `T`.
#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
#[repr(transparent)]
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Std<T>(T);

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T> Std<T> {
    /// Wraps a `T`.
    #[inline]
    pub fn new(stream: T) -> Self {
        Self(stream)
    }
    /// Read-only reference to `T`.
    #[inline]
    pub fn inner(&self) -> &T {
        &self.0
    }
    /// Mutable reference to `T`.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.0
    }
    /// Unwraps `T` and returns it.
    #[inline]
    pub fn into_inner(self) -> T {
        self.0
    }
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T: Write> std::io::Write for Std<T> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        <T as Write>::write(&mut self.0, buf).map_err(io_err)?;
        Ok(buf.len())
    }
    #[inline]
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T: Read> std::io::Read for Std<T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        <T as Read>::read(&mut self.0, buf).map_err(io_err)?;
        Ok(buf.len())
    }
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T: Seek> std::io::Seek for Std<T> {
    #[inline]
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        let pos = match pos {
            std::io::SeekFrom::Start(off) => SeekFrom::Start(u64_to_usize(off)),
            std::io::SeekFrom::End(off) => SeekFrom::End(i64_to_isize(off)),
            std::io::SeekFrom::Current(off) => SeekFrom::Current(i64_to_isize(off)),
        };
        match <T as Seek>::seek(&mut self.0, pos) {
            Ok(off) => Ok(usize_to_u64(off)),
            Err(err) => Err(io_err(err)),
        }
    }
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T: std::io::Write> Write for Std<T> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()> {
        <T as std::io::Write>::write_all(&mut self.0, buf).map_err(Into::into)
    }
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T: std::io::Read> Read for Std<T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        <T as std::io::Read>::read_exact(&mut self.0, buf).map_err(Into::into)
    }
}

#[cfg(feature = "std")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "std")))]
impl<T: std::io::Seek> Seek for Std<T> {
    #[inline]
    fn seek(&mut self, seek: SeekFrom) -> EncodingResult<usize> {
        // PANIC SAFETY
        // `as` conversion never fails, unless we are on a >64-bit system I guess?
        let seek = match seek {
            SeekFrom::Start(off) => std::io::SeekFrom::Start(usize_to_u64(off)),
            SeekFrom::End(off) => std::io::SeekFrom::End(isize_to_i64(off)),
            SeekFrom::Current(off) => std::io::SeekFrom::Current(isize_to_i64(off)),
        };
        match <T as std::io::Seek>::seek(&mut self.0, seek) {
            Ok(off) => Ok(u64_to_usize(off)),
            Err(x) => Err(x.into()),
        }
    }
}

/// Wraps a mutable `u8` slice providing [`Write`], [`Read`] and [`Seek`] implementations.
#[derive(Eq, PartialEq, Debug)]
pub struct SliceMut<'data> {
    slice: &'data mut [u8],
    pos: usize,
}

impl<'data> SliceMut<'data> {
    /// Wraps a mutable slice in an I/O object.
    #[inline]
    pub fn new(slice: &'data mut [u8]) -> Self {
        Self { slice, pos: 0 }
    }
    /// Read-only reference to the slice.
    #[inline]
    pub fn inner(&self) -> &[u8] {
        &self.slice
    }
    /// Mutable reference to the slice.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut [u8] {
        &mut self.slice
    }
    /// Unwraps the slice, returning it.
    #[inline]
    pub fn into_inner(self) -> &'data mut [u8] {
        self.slice
    }
}

impl Write for SliceMut<'_> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()> {
        let rem = self.slice.len() - self.pos;
        if buf.len() > rem {
            return Err(EncodingError::UnexpectedEnd);
        }
        let sub = &mut self.slice[self.pos..(self.pos + buf.len())];
        sub.copy_from_slice(buf);
        self.pos += buf.len();
        Ok(())
    }
}

impl Read for SliceMut<'_> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        let rem = self.slice.len() - self.pos;
        if buf.len() > rem {
            return Err(EncodingError::UnexpectedEnd);
        }
        let sub = &self.slice[self.pos..(self.pos + buf.len())];
        buf.copy_from_slice(sub);
        self.pos += buf.len();
        Ok(())
    }
}

impl Seek for SliceMut<'_> {
    #[inline]
    fn seek(&mut self, seek: SeekFrom) -> EncodingResult<usize> {
        let offset = seek.as_buf_offset(self.pos, self.slice.len())?;
        self.pos = offset;
        Ok(offset)
    }
}

/// Wraps an immutable `u8` slice providing [`Read`], [`BorrowRead`] and [`Seek`] implementations.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Slice<'data> {
    slice: &'data [u8],
    pos: usize,
}

impl<'data> Slice<'data> {
    /// Wraps an immutable slice in an I/O object.
    #[inline]
    pub fn new(slice: &'data [u8]) -> Self {
        Self { slice, pos: 0 }
    }
    /// Reference to the slice.
    #[inline]
    pub fn inner(&self) -> &[u8] {
        &self.slice
    }
    /// Unwraps the slice, returning it.
    #[inline]
    pub fn into_inner(self) -> &'data [u8] {
        self.slice
    }
}

impl Read for Slice<'_> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        let rem = self.slice.len() - self.pos;
        if buf.len() > rem {
            return Err(EncodingError::UnexpectedEnd);
        }
        let sub = &self.slice[self.pos..(self.pos + buf.len())];
        buf.copy_from_slice(sub);
        self.pos += buf.len();
        Ok(())
    }
}

impl<'data> BorrowRead<'data> for Slice<'data> {
    #[inline]
    fn peek(&self, len: usize) -> EncodingResult<&'data [u8]> {
        let rem = self.slice.len() - self.pos;
        if len > rem {
            return Err(EncodingError::UnexpectedEnd);
        }
        let sub = &self.slice[self.pos..(self.pos + len)];
        Ok(sub)
    }
    #[inline]
    fn borrow_read(&mut self, len: usize) -> EncodingResult<&'data [u8]> {
        let rem = self.slice.len() - self.pos;
        if len > rem {
            return Err(EncodingError::UnexpectedEnd);
        }
        let sub = &self.slice[self.pos..(self.pos + len)];
        self.pos += len;
        Ok(sub)
    }
}

impl Seek for Slice<'_> {
    #[inline]
    fn seek(&mut self, seek: SeekFrom) -> EncodingResult<usize> {
        let offset = seek.as_buf_offset(self.pos, self.slice.len())?;
        self.pos = offset;
        Ok(offset)
    }
}

/// Wraps a `Vec` providing [`Write`], [`Read`] and [`Seek`] implementations.
///
/// The advantage of this over a [`SliceMut`] is that when the end of the
/// vector's capacity is reached, the backing memory is simply extended and writing can continue.
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "alloc")))]
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct VecStream {
    vec: alloc::vec::Vec<u8>,
    pos: usize,
    limit: usize
}

#[cfg(feature = "alloc")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "alloc")))]
impl VecStream {
    /// Wraps a `Vec` in a type implementing "infinite" read, write and seek.
    ///
    /// The `start` parameter is used to determine the initial value of the stream pointer.
    #[inline]
    pub fn new(vec: alloc::vec::Vec<u8>, start: usize) -> Self {
        let vec_len = vec.len();
        let mut this = Self { vec, pos: start, limit: vec_len.max(start) };
        this.ensure_capacity(this.pos);
        this
    }
    /// Read-only window into the contents of the vector written so far.
    #[inline]
    pub fn inner(&self) -> &[u8] {
        &self.vec[..self.limit]
    }
    /// Returns the vector, truncated to the length of the stream pointer at the moment
    /// of calling this function.
    #[inline]
    pub fn into_inner(mut self) -> alloc::vec::Vec<u8> {
        self.vec.truncate(self.limit);
        self.vec
    }

    // Ensure the capacity is at least `at_least`, if it isn't
    // then reserve the missing number of elements to reach that capacity,
    // then pad with zeros
    fn ensure_capacity(&mut self, at_least: usize) {
        if at_least > self.vec.capacity() {
            self.vec.reserve(at_least - self.vec.len());
            for _ in self.vec.len()..self.vec.capacity() {
                self.vec.push(0);
            }
        }
        self.limit = self.limit.max(at_least);
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "alloc")))]
impl Write for VecStream {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()> {
        self.ensure_capacity(self.pos + buf.len());
        let sub = &mut self.vec[self.pos..(self.pos + buf.len())];
        sub.copy_from_slice(buf);
        self.pos += buf.len();
        Ok(())
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "alloc")))]
impl Read for VecStream {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        self.ensure_capacity(self.pos + buf.len());
        let sub = &self.vec[self.pos..(self.pos + buf.len())];
        buf.copy_from_slice(sub);
        self.pos += buf.len();
        Ok(())
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(feature = "unstable", doc(cfg(feature = "alloc")))]
impl Seek for VecStream {
    #[inline]
    fn seek(&mut self, seek: SeekFrom) -> EncodingResult<usize> {
        if let SeekFrom::End(_) = seek {
            return Err(SeekError::UnknownRange.into());
        }

        let offset = seek.as_buf_offset(self.pos, 0)?;
        self.ensure_capacity(offset);
        self.pos = offset;
        Ok(offset)
    }
}

/// Wraps any type that implements [`Write`] or [`Read`] and keeps track of how many
/// bytes are written and read, separately.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct SizeTrack<T> {
    stream: T,
    wsize: usize,
    rsize: usize,
}

impl<T> SizeTrack<T> {
    /// Creates a new tracker for `T`.
    #[inline]
    pub fn new(stream: T) -> Self {
        Self {
            stream,
            wsize: 0,
            rsize: 0,
        }
    }

    /// Returns the number of bytes written so far.
    ///
    /// Note that if a write call fails, the value returned by
    /// this function is left unchanged.
    #[inline]
    pub fn size_written(&self) -> usize {
        self.wsize
    }

    /// Returns the number of bytes read so far.
    ///
    /// Note that if a read call fails, the value returned by
    /// this function is left unchanged.
    #[inline]
    pub fn size_read(&self) -> usize {
        self.rsize
    }

    /// Resets the internal counter of the number of bytes read and written.
    pub fn clear(&mut self) {
        self.wsize = 0;
        self.rsize = 0;
    }

    /// Read-only reference to `T`.
    #[inline]
    pub fn inner(&self) -> &T {
        &self.stream
    }

    /// Mutable reference to `T`.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.stream
    }

    /// Unwraps `T`, returning it.
    #[inline]
    pub fn into_inner(self) -> T {
        self.stream
    }
}

impl<T: Write> Write for SizeTrack<T> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()> {
        let ok = self.stream.write(buf)?;
        self.wsize += buf.len();
        Ok(ok)
    }
}

impl<T: Read> Read for SizeTrack<T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        let ok = self.stream.read(buf)?;
        self.rsize += buf.len();
        Ok(ok)
    }
}

impl<'data, T: BorrowRead<'data>> BorrowRead<'data> for SizeTrack<T> {
    #[inline]
    fn peek(&self, len: usize) -> EncodingResult<&'data [u8]> {
        self.stream.peek(len)
    }
    #[inline]
    fn borrow_read(&mut self, len: usize) -> EncodingResult<&'data [u8]> {
        let ok = self.stream.borrow_read(len)?;
        self.rsize += len;
        Ok(ok)
    }
}

/// Wraps any type that implements [`Write`] or [`Read`] and limits how many
/// bytes can be written and read, separately.
#[derive(Clone, Debug)]
pub struct SizeLimit<T> {
    stream: T,
    wsize: usize,
    rsize: usize,
}

impl<T> SizeLimit<T> {
    /// Creates a new limiter for `T`.
    #[inline]
    pub fn new(stream: T, write_limit: usize, read_limit: usize) -> Self {
        Self {
            stream,
            wsize: write_limit,
            rsize: read_limit,
        }
    }

    /// Returns the number of bytes that can still be written.
    ///
    /// Note that if a write call fails, the value returned by
    /// this function is left unchanged.
    #[inline]
    pub fn remaining_writable(&self) -> usize {
        self.wsize
    }

    /// Returns the number of bytes that can still be read.
    ///
    /// Note that if a read call fails, the value returned by
    /// this function is left unchanged.
    #[inline]
    pub fn remaining_readable(&self) -> usize {
        self.rsize
    }

    /// Read-only reference to `T`.
    #[inline]
    pub fn inner(&self) -> &T {
        &self.stream
    }

    /// Mutable reference to `T`.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.stream
    }

    /// Unwraps `T`, returning it.
    #[inline]
    pub fn into_inner(self) -> T {
        self.stream
    }
}

impl<T: Write> Write for SizeLimit<T> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()> {
        if buf.len() > self.wsize {
            return Err(EncodingError::UnexpectedEnd);
        }
        let ok = self.stream.write(buf)?;
        self.wsize -= buf.len();
        Ok(ok)
    }
}

impl<T: Read> Read for SizeLimit<T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        if buf.len() > self.rsize {
            return Err(EncodingError::UnexpectedEnd);
        }
        let ok = self.stream.read(buf)?;
        self.rsize -= buf.len();
        Ok(ok)
    }
}

impl<'data, T: BorrowRead<'data>> BorrowRead<'data> for SizeLimit<T> {
    #[inline]
    fn peek(&self, len: usize) -> EncodingResult<&'data [u8]> {
        if len > self.rsize {
            return Err(EncodingError::UnexpectedEnd);
        }
        self.stream.peek(len)
    }
    #[inline]
    fn borrow_read(&mut self, len: usize) -> EncodingResult<&'data [u8]> {
        if len > self.rsize {
            return Err(EncodingError::UnexpectedEnd);
        }
        let ok = self.stream.borrow_read(len)?;
        self.rsize -= len;
        Ok(ok)
    }
}

/// A NOP stream, that ignores write and seek calls, and responds to read calls
/// with infinite zeroes.
#[derive(Clone)]
pub struct Zero;

impl Write for Zero {
    #[inline]
    fn write(&mut self, _buf: &[u8]) -> EncodingResult<()> {
        Ok(())
    }
}

impl Read for Zero {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        for x in buf {
            *x = 0;
        }
        Ok(())
    }
}

impl Seek for Zero {
    #[inline]
    fn seek(&mut self, _seek: SeekFrom) -> EncodingResult<usize> {
        Ok(0)
    }
}

/// Everything, be it a stream or buffer, which can be **encoded into**.
pub trait Write {
    /// Writes the entire contents of `buf`.
    ///
    /// No guarantees are made about flushing.
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()>;
}

/// Everything, be it a stream or buffer, which can be **decoded from**.
pub trait Read {
    /// Reads `buf.len()` bytes into `buf`.
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()>;
}

/// A buffer that is capable of lending data, in order to perform **zero copy decoding**.
pub trait BorrowRead<'data>: Read {
    /// Exactly the same as [`borrow_read`][`Self::borrow_read`], except the stream position
    /// is not advanced. E.G. multiple subsequent calls to this function are guaranteed to produce
    /// the same output.
    fn peek(&self, len: usize) -> EncodingResult<&'data [u8]>;

    /// Borrows a slice of bytes from the buffer, incrementing the buffer position.
    /// The slice's lifetime is bound to the buffer's lifetime.
    fn borrow_read(&mut self, len: usize) -> EncodingResult<&'data [u8]>;
}

/// The argument to a call to [`Seek::seek`].
///
/// Supports seeking relative to the current position, the beginning or the end
/// of a stream or buffer.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum SeekFrom {
    /// Offsets `n` bytes from the beginning of the stream or buffer.
    ///
    /// If `n` is beyond the end, a [`SeekError`][`crate::SeekError`]
    /// is returned.
    Start(usize),
    /// Offsets `n` bytes from the end of the stream or buffer.
    ///
    /// If `n` is before the beginning of the stream, or if it is beyond the end of the stream,
    /// a [`SeekError`][`crate::SeekError`] is returned.
    End(isize),
    /// Offsets `n` bytes from the current position in the stream or buffer.
    ///
    /// If `n` is before the beginning of the stream, or if it is beyond the end of the stream,
    /// a [`SeekError`][`crate::SeekError`] is returned.
    Current(isize),
}

impl SeekFrom {
    /// A [`SeekFrom`] such that when passed to [`Seek::seek`],
    /// the position is left unchanged and the return value of the call
    /// will contain the current position.
    pub const POSITION: Self = Self::Current(0);

    /// Calculates the new stream position in the case a seek operation is applied
    /// to a buffer, given the current position and the length of the buffer.
    ///
    /// Returns the offset, or a [`SeekError`] if the resulting offset would
    /// be outside of bounds.
    #[inline]
    pub const fn as_buf_offset(&self, pos: usize, len: usize) -> Result<usize, SeekError> {
        assert!(pos <= isize::MAX as _);
        assert!(len <= isize::MAX as _);

        let offset = match *self {
            SeekFrom::Start(off) => off as isize,
            SeekFrom::End(off) => len as isize + off,
            SeekFrom::Current(off) => pos as isize + off,
        };

        if offset > len as isize {
            Err(SeekError::AfterEnd(offset as usize))
        } else if offset < 0 {
            Err(SeekError::BeforeBeginning(offset))
        } else {
            Ok(offset as usize)
        }
    }
}

/// Any stream or buffer that supports moving the stream position forwards and backwards,
/// as well as returning the current position.
pub trait Seek {
    /// Offsets the stream position using the given [`SeekFrom`] argument.
    ///
    /// In general, a seek beyond the end or to a negative offset
    /// will yield a [`SeekError`][`crate::SeekError`].
    ///
    /// Returns the new position, as an offset from the start of the stream.
    fn seek(&mut self, seek: SeekFrom) -> EncodingResult<usize>;
}

impl<T: Write> Write for &mut T {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> EncodingResult<()> {
        <T as Write>::write(self, buf)
    }
}

impl<T: Read> Read for &mut T {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> EncodingResult<()> {
        <T as Read>::read(self, buf)
    }
}

impl<T: Seek> Seek for &mut T {
    #[inline]
    fn seek(&mut self, seek: SeekFrom) -> EncodingResult<usize> {
        <T as Seek>::seek(self, seek)
    }
}

impl<'data, T: BorrowRead<'data>> BorrowRead<'data> for &mut T {
    #[inline]
    fn peek(&self, len: usize) -> EncodingResult<&'data [u8]> {
        <T as BorrowRead<'data>>::peek(self, len)
    }
    #[inline]
    fn borrow_read(&mut self, len: usize) -> EncodingResult<&'data [u8]> {
        <T as BorrowRead<'data>>::borrow_read(self, len)
    }
}