buffer-trait 0.2.2

A `Buffer` trait for reading into uninitialized buffers.
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
#![cfg_attr(doc, doc = include_str!("../README.md"))]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::slice;

/// A memory buffer that may be uninitialized.
///
/// When a function has a `Buffer` argument, the type of the argument
/// determines the return type of the function:
///
/// | If you pass a…          | You get back a… |
/// | ----------------------- | --------------- |
/// | `&mut [T]`              | `usize`, indicating the number of elements initialized. |
/// | `&mut [MaybeUninit<T>]` | `(&mut [T], &mut [MaybeUninit<T>])`, holding the initialized and uninitialized subslices. |
/// | [`SpareCapacity`]       | `usize`, indicating the number of elements initialized. And the `Vec` is extended. |
/// | `&mut` [`Cursor<T, B>`] | `usize`, indicating the number of elements initialized. And the `Cursor` is advanced. Be sure to call [`Cursor::finish`] when you're done writing to it. |
///
/// # Examples
///
/// Passing a `&mut [T]`:
///
/// ```
/// # use rustix::io::read;
/// # fn example(fd: rustix::fd::BorrowedFd) -> rustix::io::Result<()> {
/// let mut buf = [0_u8; 64];
/// let nread = read(fd, &mut buf)?;
/// // `nread` is the number of bytes read.
/// # Ok(())
/// # }
/// ```
///
/// Passing a `&mut [MaybeUninit<T>]`:
///
/// ```
/// # use rustix::io::read;
/// # use std::mem::MaybeUninit;
/// # fn example(fd: rustix::fd::BorrowedFd) -> rustix::io::Result<()> {
/// let mut buf = [MaybeUninit::<u8>::uninit(); 64];
/// let (init, uninit) = read(fd, &mut buf)?;
/// // `init` is a `&mut [u8]` with the initialized bytes.
/// // `uninit` is a `&mut [MaybeUninit<u8>]` with the remaining bytes.
/// # Ok(())
/// # }
/// ```
///
/// Passing a [`SpareCapacity`], via the [`spare_capacity`] helper function:
///
/// ```
/// # use rustix::io::read;
/// # use rustix::buffer::spare_capacity;
/// # fn example(fd: rustix::fd::BorrowedFd) -> rustix::io::Result<()> {
/// let mut buf = Vec::with_capacity(64);
/// let nread = read(fd, spare_capacity(&mut buf))?;
/// // `nread` is the number of bytes read.
/// // Also, `buf.len()` is now `nread` elements longer than it was before.
/// # Ok(())
/// # }
/// ```
///
/// Passing a `&mut` [`Cursor<T, B>`]:
///
/// ```no_run,ignore
/// # use rustix::io::read;
/// # fn example(fd: rustix::fd::BorrowedFd) -> rustix::io::Result<()> {
/// let mut buf = [0_u8; 64];
/// let mut cursor = Cursor::new(&mut buf);
/// let _nread = read(fd, &mut cursor)?;
/// let _nread = read(fd, &mut cursor)?;
/// let _nread = read(fd, &mut cursor)?;
/// let total_nread = cursor.finish();
/// // `total_nread` is the total number of bytes read.
/// # Ok(())
/// # }
/// ```
///
/// # Guide to error messages
///
/// Sometimes code using `Buffer` can encounter non-obvious error messages.
/// Here are some we've encountered, along with ways to fix them.
///
/// If you see errors like
/// "cannot move out of `self` which is behind a mutable reference"
/// and
/// "move occurs because `x` has type `&mut [u8]`, which does not implement the `Copy` trait",
/// replace `x` with `&mut *x`. See `error_buffer_wrapper` in
/// examples/buffer_errors.rs.
///
/// If you see errors like
/// "type annotations needed"
/// and
/// "cannot infer type of the type parameter `Buf` declared on the function `read`",
/// you may need to change a `&mut []` to `&mut [0_u8; 0]`. See
/// `error_empty_slice` in examples/buffer_errors.rs.
///
/// If you see errors like
/// "the trait bound `[MaybeUninit<u8>; 1]: Buffer<u8>` is not satisfied",
/// add a `&mut` to pass the array by reference instead of by value. See
/// `error_array_by_value` in examples/buffer_errors.rs.
///
/// If you see errors like
/// "cannot move out of `x`, a captured variable in an `FnMut` closure",
/// try replacing `x` with `&mut *x`, or, if that doesn't work, try moving a
/// `let` into the closure body. See `error_retry_closure` and
/// `error_retry_indirect_closure` in examples/buffer_errors.rs.
///
/// If you see errors like
/// "captured variable cannot escape `FnMut` closure body",
/// use an explicit loop instead of `retry_on_intr`, assuming you're using
/// that. See `error_retry_closure_uninit` in examples/buffer_errors.rs.
///
/// [`&mut Cursor<T, B>`]: crate::Cursor
pub trait Buffer<T>
where
    Self: Sized,
{
    /// The type of the value returned by functions with `Buffer` arguments.
    type Output;

    /// Return a raw mutable pointer to the underlying buffer.
    ///
    /// After using this pointer to initialize some elements, call
    /// [`assume_init`] to declare how many were initialized.
    ///
    /// [`assume_init`]: Self::assume_init
    fn buffer_ptr(&mut self) -> *mut T;

    /// Return the length in elements of the underlying buffer.
    fn buffer_len(&self) -> usize;

    /// Assert that `len` elements were written to, and provide a return value.
    ///
    /// # Safety
    ///
    /// At least the first `len` elements of the buffer must be initialized.
    unsafe fn assume_init(self, len: usize) -> Self::Output;

    /// Return a [`Cursor`] for safely writing to the buffer.
    ///
    /// Calling [`finish`] on the cursor returns the `Self::Output`.
    ///
    /// This is an alternative to `buffer_ptr`/`assume_init` which allows
    /// callers to avoid using `unsafe`.
    ///
    /// [`finish`]: Cursor::finish
    fn cursor(self) -> Cursor<T, Self> {
        Cursor::new(self)
    }
}

impl<T> Buffer<T> for &mut [T] {
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        len
    }
}

impl<T, const N: usize> Buffer<T> for &mut [T; N] {
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        N
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        len
    }
}

// `Vec` implements `DerefMut` to `&mut [T]`, however it doesn't get
// auto-derefed in a `impl Buffer<T>`, so we add this `impl` so that our users
// don't have to add an extra `*` in these situations.
#[cfg(feature = "alloc")]
impl<T> Buffer<T> for &mut Vec<T> {
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        len
    }
}

// Similarly, `Box<[T]>` implements `DerefMut` to `&mut [T]`, however it
// doesn't get auto-derefed in a `impl Buffer<u8>`, so we add this `impl` so
// that our users don't have to add an extra `*` in these situations.
#[cfg(feature = "alloc")]
impl<T> Buffer<T> for &mut Box<[T]> {
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        len
    }
}

impl<'a, T> Buffer<T> for &'a mut [MaybeUninit<T>] {
    type Output = (&'a mut [T], &'a mut [MaybeUninit<T>]);

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr().cast::<T>()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        let (init, uninit) = self.split_at_mut(len);

        // Convert `init` from `&mut [MaybeUninit<T>]` to `&mut [T]`.
        //
        // SAFETY: The caller asserts that at least `len` elements of the
        // buffer have been initialized.
        let init = unsafe { slice::from_raw_parts_mut(init.as_mut_ptr().cast::<T>(), init.len()) };

        (init, uninit)
    }
}

impl<'a, T, const N: usize> Buffer<T> for &'a mut [MaybeUninit<T>; N] {
    type Output = (&'a mut [T], &'a mut [MaybeUninit<T>]);

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr().cast::<T>()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        N
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        let (init, uninit) = self.split_at_mut(len);

        // Convert `init` from `&mut [MaybeUninit<T>]` to `&mut [T]`.
        //
        // SAFETY: The caller asserts that at least `len` elements of the
        // buffer have been initialized.
        let init = unsafe { slice::from_raw_parts_mut(init.as_mut_ptr().cast::<T>(), init.len()) };

        (init, uninit)
    }
}

#[cfg(feature = "alloc")]
impl<'a, T> Buffer<T> for &'a mut Vec<MaybeUninit<T>> {
    type Output = (&'a mut [T], &'a mut [MaybeUninit<T>]);

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr().cast::<T>()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        let (init, uninit) = self.split_at_mut(len);

        // Convert `init` from `&mut [MaybeUninit<T>]` to `&mut [T]`.
        //
        // SAFETY: The caller asserts that at least `len` elements of the
        // buffer have been initialized.
        let init = unsafe { slice::from_raw_parts_mut(init.as_mut_ptr().cast::<T>(), init.len()) };

        (init, uninit)
    }
}

#[cfg(feature = "alloc")]
impl<'a, T> Buffer<T> for &'a mut Box<[MaybeUninit<T>]> {
    type Output = (&'a mut [T], &'a mut [MaybeUninit<T>]);

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.as_mut_ptr().cast::<T>()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        let (init, uninit) = self.split_at_mut(len);

        // Convert `init` from `&mut [MaybeUninit<T>]` to `&mut [T]`.
        //
        // SAFETY: The caller asserts that at least `len` elements of the
        // buffer have been initialized.
        let init = unsafe { slice::from_raw_parts_mut(init.as_mut_ptr().cast::<T>(), init.len()) };

        (init, uninit)
    }
}

// Similarly, `IoSliceMut` implements `DerefMut` to `&mut [u8]`, however it
// doesn't get auto-derefed in a `impl Buffer<u8>`, so we add this `impl` so
// that our users don't have to add an extra `*` in these situations.
#[cfg(feature = "std")]
impl<'a> Buffer<u8> for &mut std::io::IoSliceMut<'a> {
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut u8 {
        self.as_mut_ptr()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        len
    }
}

/// A type that implements [`Buffer`] by appending to a `Vec`, up to its
/// capacity.
///
/// To use this, use the [`spare_capacity`] function.
///
/// Because this uses the capacity, and never reallocates, the `Vec` should
/// have some non-empty spare capacity.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub struct SpareCapacity<'a, T>(&'a mut Vec<T>);

/// Construct a [`SpareCapacity`], which implements [`Buffer`].
///
/// This wraps a `&mut Vec` and uses the spare capacity of the `Vec` as the
/// buffer to receive data in, automatically calling `set_len` on the `Vec` to
/// set the length to include the received elements.
///
/// This uses the existing capacity, and never allocates, so the `Vec` should
/// have some non-empty spare capacity!
///
/// # Examples
///
/// ```
/// # fn test(input: rustix::fd::BorrowedFd) -> rustix::io::Result<()> {
/// use rustix::buffer::spare_capacity;
/// use rustix::io::{Errno, read};
///
/// let mut buf = Vec::with_capacity(1024);
/// match read(input, spare_capacity(&mut buf)) {
///     Ok(0) => { /* end of stream */ }
///     Ok(n) => { /* `buf` is now `n` bytes longer */ }
///     Err(Errno::INTR) => { /* `buf` is unmodified */ }
///     Err(e) => {
///         return Err(e);
///     }
/// }
///
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn spare_capacity<'a, T>(v: &'a mut Vec<T>) -> SpareCapacity<'a, T> {
    debug_assert_ne!(
        v.capacity(),
        0,
        "`extend` uses spare capacity, and never allocates new memory, so the `Vec` passed to it \
         should have some spare capacity."
    );

    SpareCapacity(v)
}

#[cfg(feature = "alloc")]
impl<'a, T> Buffer<T> for SpareCapacity<'a, T> {
    /// The number of elements written into the buffer.
    ///
    /// This is somewhat redundant, as `set_len` is also called on the
    /// referenced `Vec`, however it can be convenient in some cases, such as
    /// for testing for end-of-stream.
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        self.0.spare_capacity_mut().as_mut_ptr().cast::<T>()
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.0.capacity() - self.0.len()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        // SAFETY: The caller asserts that at least `len` elements of the spare
        // capacity region have been initialized.
        unsafe {
            self.0.set_len(self.0.len() + len);
        }
        len
    }
}

/// A cursor for safely writing into an uninitialized buffer.
///
/// A `Cursor` is returned from [`Buffer::cursor`], which provides way to
/// write to a [`Buffer`] without needing to use `unsafe`.
///
/// # Examples
///
/// ```ignore
/// # use buffer_trait::{Cursor, spare_capacity};
/// let mut buf = Vec::with_capacity(256);
/// let mut cursor = Cursor::new(spare_capacity(&mut buf));
/// let _nread = read(&input, &mut cursor).unwrap();
/// let _nread = read(&input, &mut cursor).unwrap();
/// let _nread = read(&input, &mut cursor).unwrap();
/// let total_read = cursor.finish();
/// ```
pub struct Cursor<T, B: Buffer<T>> {
    pos: usize,
    b: B,
    phantom: PhantomData<T>,
}

impl<T, B: Buffer<T>> Cursor<T, B> {
    /// Construct a new `Cursor`.
    pub const fn new(b: B) -> Self {
        Self {
            pos: 0,
            b,
            phantom: PhantomData,
        }
    }

    /// Return the remaining amount of space in the buffer.
    pub fn remaining(&self) -> usize {
        self.b.buffer_len() - self.pos
    }

    /// Write an element to the buffer.
    ///
    /// # Panics
    ///
    /// Panics if this cursor has already reached the end of the buffer.
    pub fn write(&mut self, t: T) {
        let ptr = self.b.buffer_ptr();
        let len = self.b.buffer_len();

        assert!(
            self.pos < len,
            "element would extend beyond the end of the buffer"
        );

        // SAFETY: `Cursor::new` requires that `ptr` and `len` are valid, and we
        // just bounds-checked `pos`.
        unsafe {
            ptr.add(self.pos).write(t);
        }

        // Count how many elements we've initialized.
        self.pos += 1;
    }

    /// Write multiple elements to the buffer.
    ///
    /// # Panics
    ///
    /// Panics if this cursor is already within `t.len()` elements of the end
    /// of the buffer.
    pub fn write_slice(&mut self, t: &[T])
    where
        T: Copy,
    {
        let ptr = self.b.buffer_ptr();
        let len = self.b.buffer_len();

        assert!(
            len - self.pos >= t.len(),
            "elements would extend beyond the end of the buffer"
        );

        // SAFETY: We've required that `T` implements `Copy`, bounds-checked
        // the length, `buffer_ptr` should have given us a correct pointer, and
        // `buffer_len` should have given us a correct length.
        unsafe {
            core::ptr::copy_nonoverlapping(t.as_ptr(), ptr, t.len());
        }

        // Count how many elements we've initialized.
        self.pos += t.len();
    }

    /// Finish writing to the buffer and return the output value.
    pub fn finish(self) -> B::Output {
        // SAFETY: `Cursor` ensures that exactly `pos` elements have been
        // written.
        unsafe { self.b.assume_init(self.pos) }
    }
}

impl<T, B: Buffer<T>> Buffer<T> for Cursor<T, B> {
    type Output = B::Output;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        // SAFETY: We ensure that `self.pos` is always within the bounds
        // of the buffer.
        unsafe { self.b.buffer_ptr().add(self.pos) }
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.remaining()
    }

    #[inline]
    unsafe fn assume_init(mut self, len: usize) -> Self::Output {
        // Count how many elements we've initialized.
        self.pos += len;
        self.finish()
    }
}

// TODO: Is is too surprising to have `&mut Cursor<T, B>` use a different
// `Output` type than `Cursor<T, B>`?
impl<T, B: Buffer<T>> Buffer<T> for &mut Cursor<T, B> {
    type Output = usize;

    #[inline]
    fn buffer_ptr(&mut self) -> *mut T {
        // SAFETY: We ensure that `self.pos` is always within the bounds
        // of the buffer.
        unsafe { self.b.buffer_ptr().add(self.pos) }
    }

    #[inline]
    fn buffer_len(&self) -> usize {
        self.remaining()
    }

    #[inline]
    unsafe fn assume_init(self, len: usize) -> Self::Output {
        // Count how many elements we've initialized.
        self.pos += len;
        len
    }
}

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use super::*;

    /// Test type signatures.
    #[cfg(not(windows))]
    #[test]
    fn test_compilation() {
        use core::mem::MaybeUninit;

        fn read<B: Buffer<u8>>(b: B) -> Result<B::Output, ()> {
            Ok(b.cursor().finish())
        }

        let mut buf = vec![0_u8; 3];
        buf.reserve(32);
        let _x: usize = read(spare_capacity(&mut buf)).unwrap();
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(buf.spare_capacity_mut()).unwrap();
        let _x: usize = read(&mut buf).unwrap();
        let _x: usize = read(&mut *buf).unwrap();
        let _x: usize = read(&mut buf[..]).unwrap();
        let _x: usize = read(&mut (*buf)[..]).unwrap();

        let mut buf = [0, 0, 0];
        let _x: usize = read(&mut buf).unwrap();
        let _x: usize = read(&mut buf[..]).unwrap();

        let mut buf = vec![0, 0, 0];
        let _x: usize = read(&mut buf).unwrap();
        let _x: usize = read(&mut buf[..]).unwrap();

        let mut buf = vec![0, 0, 0].into_boxed_slice();
        let _x: usize = read(&mut buf).unwrap();
        let _x: usize = read(&mut buf[..]).unwrap();

        let mut buf = [
            MaybeUninit::uninit(),
            MaybeUninit::uninit(),
            MaybeUninit::uninit(),
        ];
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(&mut buf).unwrap();
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(&mut buf[..]).unwrap();

        let mut buf = vec![
            MaybeUninit::uninit(),
            MaybeUninit::uninit(),
            MaybeUninit::uninit(),
        ];
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(&mut buf).unwrap();
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(&mut buf[..]).unwrap();

        let mut buf = vec![
            MaybeUninit::uninit(),
            MaybeUninit::uninit(),
            MaybeUninit::uninit(),
        ]
        .into_boxed_slice();
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(&mut buf).unwrap();
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = read(&mut buf[..]).unwrap();

        let mut buf = Cursor::new(&mut buf);
        let _x: usize = read(&mut buf).unwrap();
        let _x: (&mut [u8], &mut [MaybeUninit<u8>]) = buf.finish();

        let mut buf = [0, 0, 0];
        let mut io_slice = std::io::IoSliceMut::new(&mut buf);
        let _x: usize = read(&mut io_slice).unwrap();
        let _x: usize = read(&mut io_slice[..]).unwrap();
    }

    /// Test passing a `&mut [u8]` to `read`.
    #[cfg(not(windows))]
    #[test]
    fn test_slice() {
        use std::io::{Seek, SeekFrom};

        // We need to obtain input stream with contents that we can compare
        // against, so open our own source file.
        let mut input = std::fs::File::open("src/lib.rs").unwrap();

        let mut buf = [0_u8; 64];
        let nread = read(&input, &mut buf).unwrap();
        assert_eq!(nread, buf.len());
        assert_eq!(
            &buf[..54],
            b"#![cfg_attr(doc, doc = include_str!(\"../README.md\"))]\n"
        );
        input.seek(SeekFrom::End(-1)).unwrap();
        let nread = read(&input, &mut buf).unwrap();
        assert_eq!(nread, 1);
        assert_eq!(buf[0], b'\n');
        input.seek(SeekFrom::End(0)).unwrap();
        let nread = read(&input, &mut buf).unwrap();
        assert_eq!(nread, 0);
    }

    /// Test passing a `&mut [MaybeUninit<u8>]` to `read`.
    #[cfg(not(windows))]
    #[test]
    fn test_slice_uninit() {
        use core::mem::MaybeUninit;
        use std::io::{Seek, SeekFrom};

        // We need to obtain input stream with contents that we can compare
        // against, so open our own source file.
        let mut input = std::fs::File::open("src/lib.rs").unwrap();

        let mut buf = [MaybeUninit::<u8>::uninit(); 64];
        let (init, uninit) = read(&input, &mut buf).unwrap();
        assert_eq!(uninit.len(), 0);
        assert_eq!(
            &init[..54],
            b"#![cfg_attr(doc, doc = include_str!(\"../README.md\"))]\n"
        );
        assert_eq!(init.len(), buf.len());
        assert_eq!(
            unsafe { core::mem::transmute::<&mut [MaybeUninit<u8>], &mut [u8]>(&mut buf[..54]) },
            b"#![cfg_attr(doc, doc = include_str!(\"../README.md\"))]\n"
        );
        input.seek(SeekFrom::End(-1)).unwrap();
        let (init, uninit) = read(&input, &mut buf).unwrap();
        assert_eq!(init.len(), 1);
        assert_eq!(init[0], b'\n');
        assert_eq!(uninit.len(), buf.len() - 1);
        input.seek(SeekFrom::End(0)).unwrap();
        let (init, uninit) = read(&input, &mut buf).unwrap();
        assert_eq!(init.len(), 0);
        assert_eq!(uninit.len(), buf.len());
    }

    /// Test passing a `SpareCapacity` to `read`.
    #[cfg(not(windows))]
    #[test]
    fn test_spare_capacity() {
        use std::io::{Seek, SeekFrom};

        // We need to obtain input stream with contents that we can compare
        // against, so open our own source file.
        let mut input = std::fs::File::open("src/lib.rs").unwrap();

        let mut buf = Vec::with_capacity(64);
        let nread = read(&input, spare_capacity(&mut buf)).unwrap();
        assert_eq!(nread, buf.capacity());
        assert_eq!(nread, buf.len());
        assert_eq!(
            &buf[..54],
            b"#![cfg_attr(doc, doc = include_str!(\"../README.md\"))]\n"
        );
        buf.clear();
        input.seek(SeekFrom::End(-1)).unwrap();
        let nread = read(&input, spare_capacity(&mut buf)).unwrap();
        assert_eq!(nread, 1);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], b'\n');
        buf.clear();
        input.seek(SeekFrom::End(0)).unwrap();
        let nread = read(&input, spare_capacity(&mut buf)).unwrap();
        assert_eq!(nread, 0);
        assert!(buf.is_empty());
    }

    /// Test passing a `Cursor` to `read`.
    #[test]
    fn test_cursor_as_buffer() {
        use std::io::{Seek, SeekFrom};

        // We need to obtain input stream with contents that we can compare
        // against, so open our own source file.
        let mut input = std::fs::File::open("src/lib.rs").unwrap();

        let mut total_read = 0;

        let mut buf = Vec::with_capacity(256);
        let mut cursor = Cursor::new(spare_capacity(&mut buf));
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39);
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39 * 2);
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39 * 3);

        assert_eq!(total_read, 39 * 3);

        let cursor_read = cursor.finish();
        assert_eq!(cursor_read, total_read);

        assert_eq!(buf.len(), 39 * 3);
        assert_eq!(buf.capacity(), 256);
        assert_eq!(
            buf,
            b"// The comment at the end of the file!\n// The comment at the end of the file!\n// The comment at the end of the file!\n"
        );
    }

    /// Test nesting `Cursor`s inside of `Cursor`s.
    #[test]
    fn test_nesting() {
        use std::io::{Seek, SeekFrom};

        // We need to obtain input stream with contents that we can compare
        // against, so open our own source file.
        let mut input = std::fs::File::open("src/lib.rs").unwrap();

        let mut total_read = 0;

        let mut buf = Vec::with_capacity(256);
        let mut cursor = Cursor::new(spare_capacity(&mut buf));
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39);
        input.seek(SeekFrom::End(-39)).unwrap();
        let mut nested_cursor = Cursor::new(&mut cursor);
        let nested_nread = read(&input, &mut nested_cursor).unwrap();
        assert_eq!(nested_nread, 39);
        assert_eq!(nested_cursor.remaining(), 256 - 39 * 2);
        input.seek(SeekFrom::End(-39)).unwrap();
        let mut nested_nested_cursor = Cursor::new(&mut nested_cursor);
        let nested_nested_nread = read(&input, &mut nested_nested_cursor).unwrap();
        assert_eq!(nested_nested_nread, 39);
        assert_eq!(nested_nested_cursor.remaining(), 256 - 39 * 3);
        let inner_nread = nested_nested_cursor.finish();
        assert_eq!(inner_nread, 39);
        assert_eq!(nested_cursor.remaining(), 256 - 39 * 3);
        let nread = nested_cursor.finish();
        total_read += nread;

        assert_eq!(total_read, 39 * 3);
        assert_eq!(cursor.remaining(), 256 - 39 * 3);

        let cursor_read = cursor.finish();
        assert_eq!(cursor_read, total_read);

        assert_eq!(buf.len(), 39 * 3);
        assert_eq!(buf.capacity(), 256);
        assert_eq!(
            &buf[..39*3],
            b"// The comment at the end of the file!\n// The comment at the end of the file!\n// The comment at the end of the file!\n"
        );
    }

    /// Test using a `Cursor` to read into a `MaybeUninit` buffer in multiple
    /// reads, ultimately producing a single initialized slice.
    #[test]
    fn test_incremental() {
        use std::io::{Seek, SeekFrom};

        // We need to obtain input stream with contents that we can compare
        // against, so open our own source file.
        let mut input = std::fs::File::open("src/lib.rs").unwrap();

        let mut total_read = 0;

        let mut buf = [MaybeUninit::<u8>::zeroed(); 256];
        let mut cursor = Cursor::new(&mut buf);
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39);
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39 * 2);
        input.seek(SeekFrom::End(-39)).unwrap();
        let nread = read(&input, &mut cursor).unwrap();
        total_read += nread;
        assert_eq!(cursor.remaining(), 256 - 39 * 3);

        assert_eq!(total_read, 39 * 3);

        let (init, uninit) = cursor.finish();
        assert_eq!(init.len(), total_read);
        assert_eq!(uninit.len(), 256 - total_read);

        assert_eq!(
            init,
            b"// The comment at the end of the file!\n// The comment at the end of the file!\n// The comment at the end of the file!\n"
        );
    }

    fn read<B: Buffer<u8>>(input: &std::fs::File, mut b: B) -> std::io::Result<B::Output> {
        use std::os::fd::AsRawFd;
        let ptr = b.buffer_ptr();
        let len = b.buffer_len();
        let n = unsafe { libc::read(input.as_raw_fd(), ptr.cast(), len) };
        if let Ok(n) = usize::try_from(n) {
            unsafe { Ok(b.assume_init(n)) }
        } else {
            Err(std::io::Error::last_os_error())
        }
    }
}

// The comment at the end of the file!