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
// =============================================================================
// Copyright (c) 2026 Haixing Hu.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0.
// =============================================================================
use crateAsyncInput;
/// An asynchronous input whose items are bytes.
///
/// This trait adds no methods. Every [`AsyncInput<Item = u8>`](AsyncInput),
/// including unsized streams, implements it automatically. Implement
/// [`AsyncInput`] to provide the operations; no separate implementation of
/// `AsyncByteInput` is needed.
///
/// The inherited polling methods retain their pinning and readiness contracts;
/// implementors do not need to be `Unpin`.
///
/// # Examples
/// `ByteSlice` is always ready and reads from an in-memory byte slice:
///
/// ```
/// use std::io;
/// use std::pin::Pin;
/// use std::task::Context;
/// use std::task::Poll;
/// use std::task::Waker;
///
/// use qubit_io::AsyncByteInput;
/// use qubit_io::AsyncInput;
///
/// struct ByteSlice<'a> {
/// items: &'a [u8],
/// position: usize,
/// }
///
/// impl AsyncInput for ByteSlice<'_> {
/// type Item = u8;
///
/// unsafe fn poll_read_unchecked(
/// self: Pin<&mut Self>,
/// _cx: &mut Context<'_>,
/// output: &mut [u8],
/// index: usize,
/// count: usize,
/// ) -> Poll<io::Result<usize>> {
/// let this = self.get_mut();
/// let n = count.min(this.items.len() - this.position);
/// output[index..index + n]
/// .copy_from_slice(&this.items[this.position..this.position + n]);
/// this.position += n;
/// Poll::Ready(Ok(n))
/// }
/// }
///
/// fn read<S: AsyncByteInput + ?Sized>(
/// stream: Pin<&mut S>,
/// cx: &mut Context<'_>,
/// output: &mut [u8],
/// ) -> Poll<io::Result<usize>> {
/// stream.poll_read(cx, output)
/// }
///
/// let mut stream = ByteSlice {
/// items: b"QBIT",
/// position: 0,
/// };
/// let mut cx = Context::from_waker(Waker::noop());
/// let mut output = [0; 4];
/// assert!(matches!(
/// read(Pin::new(&mut stream), &mut cx, &mut output),
/// Poll::Ready(Ok(4))
/// ));
/// assert_eq!(&output, b"QBIT");
/// assert!(matches!(
/// read(Pin::new(&mut stream), &mut cx, &mut output),
/// Poll::Ready(Ok(0))
/// ));
/// ```
/// Streams with a different item type do not satisfy this bound:
///
/// ```compile_fail
/// use qubit_io::AsyncByteInput;
/// use qubit_io::AsyncInput;
///
/// fn accept(stream: impl AsyncByteInput) {}
///
/// fn reject(stream: impl AsyncInput<Item = char>) {
/// accept(stream);
/// }
/// ```