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
//! Connection preamble encoding and decoding utilities.
//!
//! The optional preamble is exchanged before processing a connection. This
//! module provides helpers to encode and decode preambles using `bincode`.
use ;
use ;
/// Bound preamble reads so a peer cannot grow the initial buffer indefinitely.
const MAX_PREAMBLE_LEN: usize = 1024;
/// Stable error text shared by the preamble read guard and rejection metrics.
pub const PREAMBLE_TOO_LONG_ERROR: &str = "preamble too long";
/// Trait bound for types accepted as connection preambles.
///
/// The bound allows decoding borrowed data for any lifetime without
/// requiring an external decoding context. `Sync` is required because
/// preamble values are shared by reference with asynchronous handlers.
/// Read exactly the requested additional bytes while enforcing the preamble cap.
async
/// Asynchronously read and decode a connection preamble using bincode.
///
/// This helper reads the exact number of bytes required by `T`, as
/// indicated by [`DecodeError::UnexpectedEnd`]. Additional bytes are
/// requested from `reader` until decoding succeeds or fails for some
/// other reason. A preamble that encodes to no bytes, such as the
/// default `()`, decodes without reading anything, so a connection
/// whose client waits for an unsolicited frame still reaches setup.
///
/// Attempts to decode a value of type `T` from the beginning of the
/// byte stream, reading more bytes as needed until decoding succeeds or
/// an error occurs. Any bytes remaining after the decoded value are
/// returned as leftovers.
///
/// Decoding bounds bincode's accounted allocation at `MAX_PREAMBLE_LEN`
/// (1 KiB), rejecting oversized `Vec<u8>` lengths before allocation. The limit
/// follows bincode's resource accounting; type-specific resource bounds need
/// independent validation.
///
/// # Returns
///
/// A tuple containing the decoded value and any leftover bytes.
///
/// # Errors
///
/// Returns a [`DecodeError`] if decoding fails or if an I/O error occurs
/// while reading from `reader`.
///
/// # Examples
///
/// ```
/// use tokio::io::BufReader;
/// use wireframe::preamble::read_preamble;
///
/// #[derive(Debug, PartialEq, bincode::Encode, bincode::BorrowDecode)]
/// struct MyPreamble(u64);
///
/// #[tokio::main]
/// async fn main() {
/// let data = bincode::encode_to_vec(
/// MyPreamble(42),
/// bincode::config::standard()
/// .with_big_endian()
/// .with_fixed_int_encoding(),
/// )
/// .expect("Failed to encode example preamble");
/// let mut reader = BufReader::new(&data[..]);
/// let (preamble, leftover) = read_preamble::<_, MyPreamble>(&mut reader)
/// .await
/// .expect("Failed to decode preamble bytes");
/// assert_eq!(preamble.0, 42);
/// assert!(leftover.is_empty());
/// }
/// ```
pub async
/// Asynchronously encode and write a connection preamble using bincode.
///
/// This helper encodes the preamble using the same configuration as
/// [`read_preamble`] (big-endian, fixed int encoding) and writes the
/// resulting bytes to the provided writer.
///
/// # Errors
///
/// Returns an [`EncodeError`] if encoding fails, or wraps an I/O error
/// if writing to `writer` fails.
///
/// # Examples
///
/// ```
/// use tokio::io::{AsyncReadExt, duplex};
/// use wireframe::preamble::{read_preamble, write_preamble};
///
/// #[derive(Debug, PartialEq, bincode::Encode, bincode::BorrowDecode)]
/// struct MyPreamble(u64);
///
/// #[tokio::main]
/// async fn main() {
/// let (mut client, mut server) = duplex(64);
/// write_preamble(&mut client, &MyPreamble(42))
/// .await
/// .expect("Failed to write preamble");
/// drop(client);
///
/// let (decoded, leftover) = read_preamble::<_, MyPreamble>(&mut server)
/// .await
/// .expect("Failed to read preamble");
/// assert_eq!(decoded.0, 42);
/// assert!(leftover.is_empty());
/// }
/// ```
pub async