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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Buffered reader for LEB128-encoded values.

use core::marker::PhantomData;
use std::collections::TryReserveError;
use std::io::Result;
use std::io::SeekFrom;

use qubit_codec::TranscodeDecodeInput;
use qubit_codec_binary::Leb128Codec;
use qubit_codec_binary::Leb128DecodePolicy;
use qubit_codec_binary::NonStrict;
use qubit_codec_binary::Strict;
use qubit_io::Buffer;
use qubit_io::ByteInput;
use qubit_io::Input;
use qubit_io::Seekable;
use qubit_io::SeekableByteInput;

use super::internal::TranscodeDecodeInputExt;
use crate::util::MIN_CODEC_BUFFER_CAPACITY;
use crate::util::read_utf8_payload;
#[cfg(not(target_pointer_width = "64"))]
use crate::util::usize_from_u64_len;

/// Buffered reader for LEB128 integers.
///
/// Values are decoded directly from the internal input buffer while the codec
/// scans for the LEB128 terminating byte.
///
/// # Buffered state
///
/// This reader may prefetch bytes from the wrapped reader. As a result,
/// [`Self::inner`] can observe an underlying stream position ahead of the
/// logical position exposed by this wrapper.
///
/// # Target-width integers
///
/// `usize` and `isize` methods use the current Rust target's pointer width.
/// Prefer fixed-width integer methods such as `read_u64` or `read_i64` for
/// persistent files and cross-platform protocols.
///
/// # Type Parameters
///
/// - `R`: Underlying byte input.
/// - `P`: LEB128 canonicality policy.
///
/// # Examples
///
/// ```
/// use qubit_codec_binary::NonStrict;
/// use qubit_io_binary::BufferedLeb128Reader;
///
/// let mut reader = BufferedLeb128Reader::<_, NonStrict>::new(
///     std::io::Cursor::new([0xAC, 0x02]),
/// );
/// assert_eq!(reader.read_u32_non_strict()?, 300);
/// # Ok::<(), std::io::Error>(())
/// ```
pub struct BufferedLeb128Reader<R, P>
where
    R: ByteInput,
{
    /// Buffered codec input and wrapped reader.
    input: TranscodeDecodeInput<R>,
    /// Associates the selected decoding policy without storing a value.
    marker: PhantomData<fn() -> P>,
}

impl_input_methods!(BufferedLeb128Reader<R, P> where R: ByteInput);
impl_seekable_methods!(BufferedLeb128Reader<R, P> where R: SeekableByteInput);

impl<R, P> BufferedLeb128Reader<R, P>
where
    R: ByteInput,
    P: Leb128DecodePolicy,
{
    /// Creates a buffered LEB128 reader with the default buffer capacity.
    ///
    /// # Parameters
    ///
    /// - `inner`: Underlying byte input.
    ///
    /// # Returns
    ///
    /// Returns a buffered reader using policy `P`.
    #[must_use]
    #[inline]
    pub fn new(inner: R) -> Self {
        Self {
            input: TranscodeDecodeInput::new(inner),
            marker: PhantomData,
        }
    }

    /// Creates a buffered LEB128 reader with at least `capacity` bytes.
    ///
    /// # Parameters
    ///
    /// - `inner`: Underlying byte input.
    /// - `capacity`: Requested internal buffer capacity in bytes.
    ///
    /// # Returns
    ///
    /// Returns a buffered reader whose capacity also satisfies the largest
    /// supported codec payload.
    #[must_use]
    #[inline]
    pub fn with_capacity(inner: R, capacity: usize) -> Self {
        Self {
            input: TranscodeDecodeInput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
            marker: PhantomData,
        }
    }

    /// Tries to create a buffered LEB128 reader with at least `capacity` bytes.
    ///
    /// # Parameters
    ///
    /// - `inner`: Underlying byte input to wrap.
    /// - `capacity`: Requested internal buffer capacity in bytes. The request
    ///   is raised when necessary to fit the largest supported codec payload.
    ///
    /// # Returns
    ///
    /// Returns a buffered reader on successful allocation. Its capacity
    /// satisfies both the request and the minimum required by the supported
    /// codecs.
    ///
    /// # Errors
    ///
    /// Returns a [`TryReserveError`] if the buffer capacity overflows or its
    /// allocation fails.
    #[inline]
    pub fn try_with_capacity(inner: R, capacity: usize) -> std::result::Result<Self, TryReserveError> {
        Ok(Self {
            input: TranscodeDecodeInput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
            marker: PhantomData,
        })
    }

    /// Returns whether this reader rejects non-canonical encodings.
    ///
    /// # Returns
    ///
    /// Returns `true` when policy `P` requires canonical encodings.
    #[must_use]
    #[inline(always)]
    pub const fn is_strict(&self) -> bool {
        P::STRICT
    }

    /// Returns a shared reference to the underlying reader.
    ///
    /// The underlying reader may already be positioned past unread bytes held
    /// in this wrapper's internal buffer.
    ///
    /// # Returns
    ///
    /// Returns the wrapped reader.
    #[must_use]
    #[inline(always)]
    pub const fn inner(&self) -> &R {
        self.input.inner()
    }

    /// Consumes this wrapper and preserves its unread buffered bytes.
    ///
    /// # Returns
    ///
    /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
    /// slice contains every prefetched byte not yet consumed logically. To
    /// continue the same logical stream, consume that slice before reading
    /// from the returned reader.
    #[inline(always)]
    #[must_use = "the returned inner reader and unread buffer must be handled"]
    pub fn into_parts(self) -> (R, Buffer<u8>) {
        self.input.into_parts()
    }
}

macro_rules! impl_read_value {
    ($policy:ty, $method:ident, $ty:ty, $doc:literal) => {
        #[doc = $doc]
        #[doc = ""]
        #[doc = "# Returns"]
        #[doc = ""]
        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
        #[doc = ""]
        #[doc = "# Errors"]
        #[doc = ""]
        #[doc = "Returns an input error or an invalid-data error when the \
                 payload is malformed or violates the selected policy."]
        #[inline(always)]
        pub fn $method(&mut self) -> Result<$ty> {
            type Codec = Leb128Codec<$ty, $policy>;

            self.input.read_decoded::<Codec>()
        }
    };
}

macro_rules! impl_for_policy {
    (
        $policy:ty,
        $read_usize:ident,
        $read_u64:ident,
        $read_utf8_string_usize:ident,
        $read_utf8_string_u64:ident,
        {
            $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
        }
        $(,)?
    ) => {
        impl<R> BufferedLeb128Reader<R, $policy>
        where
            R: ByteInput,
        {
            $(
                impl_read_value!($policy, $method, $ty, $doc);
            )*

            /// Reads a UTF-8 string prefixed by an unsigned LEB128 byte length.
            ///
            /// The length prefix is decoded as usize, so this format is
            /// target-width dependent. Prefer a fixed-width length prefix for
            /// persistent files and cross-platform protocols.
            ///
            /// # Parameters
            ///
            /// - max_len: Maximum accepted UTF-8 payload length in bytes.
            ///
            /// # Returns
            ///
            /// Returns the decoded UTF-8 string.
            ///
            /// # Errors
            ///
            /// Returns an input or allocation error, or an invalid-data error
            /// for a malformed or excessive length or invalid UTF-8.
            ///
            /// # Stream position
            ///
            /// If the decoded length exceeds `max_len`, the length prefix has been
            /// consumed logically, but the payload has not. If UTF-8 validation
            /// fails, the prefix and complete payload have been consumed logically.
            /// The underlying input may already have prefetched payload bytes;
            /// its position is not the logical consumption position. These operations
            /// do not roll back; recover only at an outer framing boundary or a
            /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
            /// for the shared length-prefixed read contract.
            #[inline]
            pub fn $read_utf8_string_usize(
                &mut self,
                max_len: usize,
            ) -> Result<String> {
                let len = self.$read_usize()?;
                read_utf8_payload(&mut self.input, len, max_len)
            }

            /// Reads a UTF-8 string prefixed by an unsigned LEB128 u64 byte
            /// length.
            ///
            /// Prefer this method over the usize variant 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
            ///
            /// Returns the decoded UTF-8 string.
            ///
            /// # Errors
            ///
            /// Returns an input, conversion, or allocation error, or an
            /// invalid-data error for a malformed or excessive length or
            /// invalid UTF-8.
            ///
            /// # Stream position
            ///
            /// If the decoded length exceeds `max_len`, the length prefix has been
            /// consumed logically, but the payload has not. If UTF-8 validation
            /// fails, the prefix and complete payload have been consumed logically.
            /// The underlying input may already have prefetched payload bytes;
            /// its position is not the logical consumption position. These operations
            /// do not roll back; recover only at an outer framing boundary or a
            /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
            /// for the shared length-prefixed read contract.
            #[inline]
            pub fn $read_utf8_string_u64(
                &mut self,
                max_len: usize,
            ) -> Result<String> {
                let len = self.$read_u64()?;
                #[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(&mut self.input, len, max_len)
            }
        }
    };
}

impl_for_policy!(
    NonStrict,
    read_usize_non_strict,
    read_u64_non_strict,
    read_utf8_string_usize_non_strict,
    read_utf8_string_u64_non_strict,
    {
        (read_u8_non_strict, u8, "Reads an unsigned LEB128 u8."),
        (read_u16_non_strict, u16, "Reads an unsigned LEB128 u16."),
        (read_u32_non_strict, u32, "Reads an unsigned LEB128 u32."),
        (read_u64_non_strict, u64, "Reads an unsigned LEB128 u64."),
        (read_u128_non_strict, u128, "Reads an unsigned LEB128 u128."),
        (read_usize_non_strict, usize, "Reads an unsigned LEB128 usize."),
        (read_i8_non_strict, i8, "Reads a signed LEB128 i8."),
        (read_i16_non_strict, i16, "Reads a signed LEB128 i16."),
        (read_i32_non_strict, i32, "Reads a signed LEB128 i32."),
        (read_i64_non_strict, i64, "Reads a signed LEB128 i64."),
        (read_i128_non_strict, i128, "Reads a signed LEB128 i128."),
        (read_isize_non_strict, isize, "Reads a signed LEB128 isize."),
    },
);
impl_for_policy!(
    Strict,
    read_usize,
    read_u64,
    read_utf8_string_usize,
    read_utf8_string_u64,
    {
        (read_u8, u8, "Reads an unsigned LEB128 u8."),
        (read_u16, u16, "Reads an unsigned LEB128 u16."),
        (read_u32, u32, "Reads an unsigned LEB128 u32."),
        (read_u64, u64, "Reads an unsigned LEB128 u64."),
        (read_u128, u128, "Reads an unsigned LEB128 u128."),
        (read_usize, usize, "Reads an unsigned LEB128 usize."),
        (read_i8, i8, "Reads a signed LEB128 i8."),
        (read_i16, i16, "Reads a signed LEB128 i16."),
        (read_i32, i32, "Reads a signed LEB128 i32."),
        (read_i64, i64, "Reads a signed LEB128 i64."),
        (read_i128, i128, "Reads a signed LEB128 i128."),
        (read_isize, isize, "Reads a signed LEB128 isize."),
    },
);
impl<R, P> Input for BufferedLeb128Reader<R, P>
where
    R: ByteInput,
{
    /// Byte type yielded by the buffered input adapter.
    type Item = u8;

    /// Reports that this adapter buffers input.
    ///
    /// # Returns
    ///
    /// Always returns `true`.
    #[inline(always)]
    fn is_buffered(&self) -> bool {
        true
    }

    /// Reads up to `count` bytes into an indexed output range.
    ///
    /// # Parameters
    ///
    /// - `output`: Destination slice.
    /// - `index`: First destination index.
    /// - `count`: Maximum number of bytes to read.
    ///
    /// # Returns
    ///
    /// Returns the number of bytes read.
    ///
    /// # Errors
    ///
    /// Returns an error reported while reading the buffered input.
    ///
    /// # Safety
    ///
    /// `index..index + count` must be a valid range within `output`.
    #[inline(always)]
    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
        // SAFETY: The caller upholds the indexed destination range contract.
        unsafe { self.input.read_unchecked(output, index, count) }
    }
}

impl<R, P> Seekable for BufferedLeb128Reader<R, P>
where
    R: SeekableByteInput,
{
    /// Unit type used for seeking in the byte stream.
    type Unit = u8;

    /// Seeks relative to this reader's logical position. Relative seeks within
    /// the buffered window preserve unread bytes; successful seeks outside the
    /// window discard the old buffer. The returned position is logical.
    ///
    /// # Parameters
    ///
    /// - `position`: Target seek position.
    ///
    /// # Returns
    ///
    /// Returns the new logical stream position in bytes.
    ///
    /// # Errors
    ///
    /// Returns the seek error reported by the wrapped reader and preserves
    /// buffered bytes when seeking fails, including when an in-window seek
    /// cannot query the wrapped position.
    #[inline(always)]
    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
        self.input.seek(position)
    }
}