qubit-io-binary 0.8.6

Synchronous and asynchronous binary stream I/O adapters for Rust
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Extension methods for reading length-prefixed UTF-8 strings.

use std::io::Result;

use qubit_codec::ByteOrder;
use qubit_io::ByteInput;

use crate::BinaryReadExt;
use crate::Leb128ReadExt;
use crate::util::read_utf8_payload as read_utf8_payload_impl;
use crate::util::read_utf8_payload_into as read_utf8_payload_into_impl;
#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
use crate::util::usize_from_u32_len;
#[cfg(not(target_pointer_width = "64"))]
use crate::util::usize_from_u64_len;

/// Extension methods for reading length-prefixed UTF-8 strings.
///
/// String-producing methods may return allocation failures as I/O errors in
/// addition to input and validation errors described below.
///
/// A length-prefixed read is not transactional. If the decoded length exceeds
/// max_len, the prefix is consumed but the payload is left unread. If UTF-8
/// validation fails, both the prefix and the complete payload are consumed.
/// Do not continue parsing the same record from the current position.
///
/// # Examples
///
/// Read a length-prefixed string and observe that an oversized length consumes
/// its prefix while leaving the payload unread:
///
/// ```
/// use std::io::Cursor;
/// use std::io::ErrorKind;
/// use qubit_io_binary::StringReadExt;
///
/// let mut input = Cursor::new([3, b'a', b'b', b'c']);
/// assert_eq!(input.read_utf8_string_uleb_u64_strict(3)?, "abc");
/// let mut oversized = Cursor::new([3, b'a', b'b', b'c']);
/// assert_eq!(oversized.read_utf8_string_uleb_u64_strict(2).unwrap_err().kind(), ErrorKind::InvalidData);
/// assert_eq!(oversized.position(), 1);
/// # Ok::<(), std::io::Error>(())
/// ```
pub trait StringReadExt: ByteInput {
    /// Reads and validates a UTF-8 payload into reusable byte storage.
    ///
    /// # Parameters
    ///
    /// - `bytes`: Reusable destination buffer. It is cleared before a permitted
    ///   read and contains the received bytes when the read succeeds or when
    ///   UTF-8 validation fails.
    /// - `len`: UTF-8 payload length in bytes.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// If `len` exceeds `max_len`, `bytes` is left unchanged. Once the length
    /// is accepted, its previous contents may be cleared even if allocation or
    /// reading fails. After an I/O error, `bytes` is not a complete payload:
    /// its length does not report how many bytes were received, and it may
    /// contain zero-filled bytes that were never read. Invalid UTF-8 is
    /// reported only after the complete payload has been received, so all
    /// payload bytes remain available in `bytes` for diagnostics.
    ///
    /// # Returns
    ///
    /// Returns after `bytes` contains one valid UTF-8 payload.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for payload reads or allocation failures, or
    /// [`std::io::ErrorKind::InvalidData`] when `len` exceeds `max_len` or
    /// the payload is not valid UTF-8.
    fn read_utf8_payload_into(&mut self, bytes: &mut Vec<u8>, len: usize, max_len: usize) -> Result<()>;

    /// Reads a UTF-8 payload with an already decoded byte length.
    ///
    /// # Parameters
    ///
    /// - `len`: UTF-8 payload length in bytes.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when `len` exceeds `max_len`, or
    /// [`std::io::ErrorKind::InvalidData`] when the payload is not valid
    /// UTF-8.
    fn read_utf8_payload(&mut self, len: usize, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with an unsigned LEB128 byte-length prefix.
    ///
    /// The length prefix is decoded as `usize`, so this format is target-width
    /// dependent. Prefer `u16` or `u32` length-prefix methods for persistent
    /// files and cross-platform protocols.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_utf8_string_uleb_usize(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a canonical unsigned LEB128 byte-length
    /// prefix.
    ///
    /// The length prefix is decoded as `usize`, so this format is target-width
    /// dependent. Prefer `u16` or `u32` length-prefix methods for persistent
    /// files and cross-platform protocols.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the length prefix is
    /// malformed or non-canonical, [`std::io::ErrorKind::InvalidData`] when
    /// the encoded length exceeds `max_len`, or
    /// [`std::io::ErrorKind::InvalidData`] when the payload is not valid
    /// UTF-8.
    fn read_utf8_string_uleb_usize_strict(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with an unsigned LEB128 `u64` byte-length prefix.
    ///
    /// Prefer this method over [`Self::read_utf8_string_uleb_usize`] for
    /// persistent files and cross-platform protocols because the length
    /// field is independent of the current Rust target's pointer width.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded `u64` length
    /// does not fit the local `usize`, when the encoded length exceeds
    /// `max_len`, or when the payload is not valid UTF-8.
    fn read_utf8_string_uleb_u64(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a canonical unsigned LEB128 `u64` byte-length
    /// prefix.
    ///
    /// Prefer this method over [`Self::read_utf8_string_uleb_usize_strict`] for
    /// persistent files and cross-platform protocols because the length field
    /// is independent of the current Rust target's pointer width.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the length prefix is
    /// malformed or non-canonical, when the encoded `u64` length does not
    /// fit the local `usize`, when the encoded length exceeds `max_len`, or
    /// when the payload is not valid UTF-8.
    fn read_utf8_string_uleb_u64_strict(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a runtime-order `u16` byte-length prefix.
    ///
    /// # Parameters
    ///
    /// - `byte_order`: Byte order used by the length prefix.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_string_with_u16_len(&mut self, byte_order: ByteOrder, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a big-endian `u16` byte-length prefix.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_string_with_u16_len_be(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a little-endian `u16` byte-length prefix.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_string_with_u16_len_le(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a runtime-order `u32` byte-length prefix.
    ///
    /// # Parameters
    ///
    /// - `byte_order`: Byte order used by the length prefix.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_string_with_u32_len(&mut self, byte_order: ByteOrder, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a big-endian `u32` byte-length prefix.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_string_with_u32_len_be(&mut self, max_len: usize) -> Result<String>;

    /// Reads a UTF-8 string with a little-endian `u32` byte-length prefix.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    ///
    /// # Returns
    ///
    /// The decoded string.
    ///
    /// # Errors
    ///
    /// Returns an I/O error for length or payload reads,
    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
    /// is not valid UTF-8.
    fn read_string_with_u32_len_le(&mut self, max_len: usize) -> Result<String>;
}

impl<T> StringReadExt for T
where
    T: ByteInput + ?Sized,
{
    /// Reads a validated UTF-8 payload into the caller's reusable byte buffer.
    ///
    /// The buffer contents and error behavior follow the contract documented
    /// on [`StringReadExt::read_utf8_payload_into`].
    ///
    /// # Parameters
    ///
    /// - `bytes`: Reusable destination buffer for the received payload.
    /// - `len`: UTF-8 payload length in bytes.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_utf8_payload_into(&mut self, bytes: &mut Vec<u8>, len: usize, max_len: usize) -> Result<()> {
        read_utf8_payload_into_impl(self, bytes, len, max_len)
    }

    /// Reads and validates a UTF-8 payload whose byte length is already known.
    ///
    /// Length limits and input-consumption behavior follow the contract
    /// documented on [`StringReadExt::read_utf8_payload`].
    ///
    /// # Parameters
    ///
    /// - `len`: UTF-8 payload length in bytes.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_utf8_payload(&mut self, len: usize, max_len: usize) -> Result<String> {
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Decodes a non-strict `usize` ULEB128 length and reads that UTF-8
    /// payload.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_utf8_string_uleb_usize(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_uleb_usize_non_strict()?;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Decodes a canonical `usize` ULEB128 length and reads that UTF-8 payload.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_utf8_string_uleb_usize_strict(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_uleb_usize_strict()?;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Decodes a non-strict `u64` ULEB128 length and reads that UTF-8 payload.
    ///
    /// Returns an invalid-data error if the length cannot fit in `usize`.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_utf8_string_uleb_u64(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_uleb_u64_non_strict()?;
        #[cfg(target_pointer_width = "64")]
        let len = len as usize;
        #[cfg(not(target_pointer_width = "64"))]
        let len = usize_from_u64_len(len)?;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Decodes a canonical `u64` ULEB128 length and reads that UTF-8 payload.
    ///
    /// Returns an invalid-data error for a malformed prefix or a length that
    /// cannot fit in `usize`.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_utf8_string_uleb_u64_strict(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_uleb_u64_strict()?;
        #[cfg(target_pointer_width = "64")]
        let len = len as usize;
        #[cfg(not(target_pointer_width = "64"))]
        let len = usize_from_u64_len(len)?;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Reads a UTF-8 payload preceded by a `u16` length in the selected byte
    /// order.
    ///
    /// # Parameters
    ///
    /// - `byte_order`: Byte order used by the length prefix.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_string_with_u16_len(&mut self, byte_order: ByteOrder, max_len: usize) -> Result<String> {
        let len = usize::from(self.read_u16(byte_order)?);
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Reads a UTF-8 payload preceded by a big-endian `u16` length.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_string_with_u16_len_be(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_u16_be()? as usize;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Reads a UTF-8 payload preceded by a little-endian `u16` length.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_string_with_u16_len_le(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_u16_le()? as usize;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Reads a UTF-8 payload preceded by a `u32` length in the selected byte
    /// order.
    ///
    /// # Parameters
    ///
    /// - `byte_order`: Byte order used by the length prefix.
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_string_with_u32_len(&mut self, byte_order: ByteOrder, max_len: usize) -> Result<String> {
        let len = self.read_u32(byte_order)?;
        #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
        let len = len as usize;
        #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
        let len = usize_from_u32_len(len)?;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Reads a UTF-8 payload preceded by a big-endian `u32` length.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_string_with_u32_len_be(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_u32_be()?;
        #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
        let len = len as usize;
        #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
        let len = usize_from_u32_len(len)?;
        read_utf8_payload_impl(self, len, max_len)
    }

    /// Reads a UTF-8 payload preceded by a little-endian `u32` length.
    ///
    /// # Parameters
    ///
    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
    #[inline]
    fn read_string_with_u32_len_le(&mut self, max_len: usize) -> Result<String> {
        let len = self.read_u32_le()?;
        #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
        let len = len as usize;
        #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
        let len = usize_from_u32_len(len)?;
        read_utf8_payload_impl(self, len, max_len)
    }
}