Skip to main content

qubit_io_binary/ext/
string_read_ext.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8use std::io::Result;
9
10use crate::util::read_utf8_payload as read_utf8_payload_impl;
11#[cfg(not(any(
12    target_pointer_width = "32",
13    target_pointer_width = "64"
14)))]
15use crate::util::usize_from_u32_len;
16#[cfg(not(target_pointer_width = "64"))]
17use crate::util::usize_from_u64_len;
18use crate::{
19    BinaryReadExt,
20    Leb128ReadExt,
21};
22use qubit_codec::ByteOrder;
23use qubit_io::Input;
24
25/// Extension methods for reading length-prefixed UTF-8 strings.
26pub trait StringReadExt: Input<Item = u8> {
27    /// Reads a UTF-8 payload with an already decoded byte length.
28    ///
29    /// # Parameters
30    ///
31    /// - `len`: UTF-8 payload length in bytes.
32    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
33    ///
34    /// # Returns
35    ///
36    /// The decoded string.
37    ///
38    /// # Errors
39    ///
40    /// Returns an I/O error for payload reads,
41    /// [`std::io::ErrorKind::InvalidData`] when `len` exceeds `max_len`, or
42    /// [`std::io::ErrorKind::InvalidData`] when the payload is not valid
43    /// UTF-8.
44    fn read_utf8_payload(
45        &mut self,
46        len: usize,
47        max_len: usize,
48    ) -> Result<String>;
49
50    /// Reads a UTF-8 string with an unsigned LEB128 byte-length prefix.
51    ///
52    /// The length prefix is decoded as `usize`, so this format is target-width
53    /// dependent. Prefer `u16` or `u32` length-prefix methods for persistent
54    /// files and cross-platform protocols.
55    ///
56    /// # Parameters
57    ///
58    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
59    ///
60    /// # Returns
61    ///
62    /// The decoded string.
63    ///
64    /// # Errors
65    ///
66    /// Returns an I/O error for length or payload reads,
67    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
68    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
69    /// is not valid UTF-8.
70    fn read_utf8_string_uleb_usize(&mut self, max_len: usize)
71    -> Result<String>;
72
73    /// Reads a UTF-8 string with a canonical unsigned LEB128 byte-length
74    /// prefix.
75    ///
76    /// The length prefix is decoded as `usize`, so this format is target-width
77    /// dependent. Prefer `u16` or `u32` length-prefix methods for persistent
78    /// files and cross-platform protocols.
79    ///
80    /// # Parameters
81    ///
82    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
83    ///
84    /// # Returns
85    ///
86    /// The decoded string.
87    ///
88    /// # Errors
89    ///
90    /// Returns an I/O error for length or payload reads,
91    /// [`std::io::ErrorKind::InvalidData`] when the length prefix is
92    /// malformed or non-canonical, [`std::io::ErrorKind::InvalidData`] when
93    /// the encoded length exceeds `max_len`, or
94    /// [`std::io::ErrorKind::InvalidData`] when the payload is not valid
95    /// UTF-8.
96    fn read_utf8_string_uleb_usize_strict(
97        &mut self,
98        max_len: usize,
99    ) -> Result<String>;
100
101    /// Reads a UTF-8 string with an unsigned LEB128 `u64` byte-length prefix.
102    ///
103    /// Prefer this method over [`Self::read_utf8_string_uleb_usize`] for
104    /// persistent files and cross-platform protocols because the length
105    /// field is independent of the current Rust target's pointer width.
106    ///
107    /// # Parameters
108    ///
109    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
110    ///
111    /// # Returns
112    ///
113    /// The decoded string.
114    ///
115    /// # Errors
116    ///
117    /// Returns an I/O error for length or payload reads,
118    /// [`std::io::ErrorKind::InvalidData`] when the encoded `u64` length
119    /// does not fit the local `usize`, when the encoded length exceeds
120    /// `max_len`, or when the payload is not valid UTF-8.
121    fn read_utf8_string_uleb_u64(&mut self, max_len: usize) -> Result<String>;
122
123    /// Reads a UTF-8 string with a canonical unsigned LEB128 `u64` byte-length
124    /// prefix.
125    ///
126    /// Prefer this method over [`Self::read_utf8_string_uleb_usize_strict`] for
127    /// persistent files and cross-platform protocols because the length field
128    /// is independent of the current Rust target's pointer width.
129    ///
130    /// # Parameters
131    ///
132    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
133    ///
134    /// # Returns
135    ///
136    /// The decoded string.
137    ///
138    /// # Errors
139    ///
140    /// Returns an I/O error for length or payload reads,
141    /// [`std::io::ErrorKind::InvalidData`] when the length prefix is
142    /// malformed or non-canonical, when the encoded `u64` length does not
143    /// fit the local `usize`, when the encoded length exceeds `max_len`, or
144    /// when the payload is not valid UTF-8.
145    fn read_utf8_string_uleb_u64_strict(
146        &mut self,
147        max_len: usize,
148    ) -> Result<String>;
149
150    /// Reads a UTF-8 string with a runtime-order `u16` byte-length prefix.
151    ///
152    /// # Parameters
153    ///
154    /// - `byte_order`: Byte order used by the length prefix.
155    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
156    ///
157    /// # Returns
158    ///
159    /// The decoded string.
160    ///
161    /// # Errors
162    ///
163    /// Returns an I/O error for length or payload reads,
164    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
165    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
166    /// is not valid UTF-8.
167    fn read_string_with_u16_len(
168        &mut self,
169        byte_order: ByteOrder,
170        max_len: usize,
171    ) -> Result<String>;
172
173    /// Reads a UTF-8 string with a big-endian `u16` byte-length prefix.
174    ///
175    /// # Parameters
176    ///
177    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
178    ///
179    /// # Returns
180    ///
181    /// The decoded string.
182    ///
183    /// # Errors
184    ///
185    /// Returns an I/O error for length or payload reads,
186    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
187    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
188    /// is not valid UTF-8.
189    fn read_string_with_u16_len_be(&mut self, max_len: usize)
190    -> Result<String>;
191
192    /// Reads a UTF-8 string with a little-endian `u16` byte-length prefix.
193    ///
194    /// # Parameters
195    ///
196    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
197    ///
198    /// # Returns
199    ///
200    /// The decoded string.
201    ///
202    /// # Errors
203    ///
204    /// Returns an I/O error for length or payload reads,
205    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
206    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
207    /// is not valid UTF-8.
208    fn read_string_with_u16_len_le(&mut self, max_len: usize)
209    -> Result<String>;
210
211    /// Reads a UTF-8 string with a runtime-order `u32` byte-length prefix.
212    ///
213    /// # Parameters
214    ///
215    /// - `byte_order`: Byte order used by the length prefix.
216    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
217    ///
218    /// # Returns
219    ///
220    /// The decoded string.
221    ///
222    /// # Errors
223    ///
224    /// Returns an I/O error for length or payload reads,
225    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
226    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
227    /// is not valid UTF-8.
228    fn read_string_with_u32_len(
229        &mut self,
230        byte_order: ByteOrder,
231        max_len: usize,
232    ) -> Result<String>;
233
234    /// Reads a UTF-8 string with a big-endian `u32` byte-length prefix.
235    ///
236    /// # Parameters
237    ///
238    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
239    ///
240    /// # Returns
241    ///
242    /// The decoded string.
243    ///
244    /// # Errors
245    ///
246    /// Returns an I/O error for length or payload reads,
247    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
248    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
249    /// is not valid UTF-8.
250    fn read_string_with_u32_len_be(&mut self, max_len: usize)
251    -> Result<String>;
252
253    /// Reads a UTF-8 string with a little-endian `u32` byte-length prefix.
254    ///
255    /// # Parameters
256    ///
257    /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
258    ///
259    /// # Returns
260    ///
261    /// The decoded string.
262    ///
263    /// # Errors
264    ///
265    /// Returns an I/O error for length or payload reads,
266    /// [`std::io::ErrorKind::InvalidData`] when the encoded length exceeds
267    /// `max_len`, or [`std::io::ErrorKind::InvalidData`] when the payload
268    /// is not valid UTF-8.
269    fn read_string_with_u32_len_le(&mut self, max_len: usize)
270    -> Result<String>;
271}
272
273impl<T> StringReadExt for T
274where
275    T: Input<Item = u8> + ?Sized,
276{
277    #[inline]
278    fn read_utf8_payload(
279        &mut self,
280        len: usize,
281        max_len: usize,
282    ) -> Result<String> {
283        read_utf8_payload_impl(self, len, max_len)
284    }
285
286    #[inline]
287    fn read_utf8_string_uleb_usize(
288        &mut self,
289        max_len: usize,
290    ) -> Result<String> {
291        let len = self.read_uleb_usize_non_strict()?;
292        read_utf8_payload_impl(self, len, max_len)
293    }
294
295    #[inline]
296    fn read_utf8_string_uleb_usize_strict(
297        &mut self,
298        max_len: usize,
299    ) -> Result<String> {
300        let len = self.read_uleb_usize_strict()?;
301        read_utf8_payload_impl(self, len, max_len)
302    }
303
304    #[inline]
305    fn read_utf8_string_uleb_u64(&mut self, max_len: usize) -> Result<String> {
306        let len = self.read_uleb_u64_non_strict()?;
307        #[cfg(target_pointer_width = "64")]
308        let len = len as usize;
309        #[cfg(not(target_pointer_width = "64"))]
310        let len = usize_from_u64_len(len)?;
311        read_utf8_payload_impl(self, len, max_len)
312    }
313
314    #[inline]
315    fn read_utf8_string_uleb_u64_strict(
316        &mut self,
317        max_len: usize,
318    ) -> Result<String> {
319        let len = self.read_uleb_u64_strict()?;
320        #[cfg(target_pointer_width = "64")]
321        let len = len as usize;
322        #[cfg(not(target_pointer_width = "64"))]
323        let len = usize_from_u64_len(len)?;
324        read_utf8_payload_impl(self, len, max_len)
325    }
326
327    #[inline]
328    fn read_string_with_u16_len(
329        &mut self,
330        byte_order: ByteOrder,
331        max_len: usize,
332    ) -> Result<String> {
333        let len = usize::from(self.read_u16(byte_order)?);
334        read_utf8_payload_impl(self, len, max_len)
335    }
336
337    #[inline]
338    fn read_string_with_u16_len_be(
339        &mut self,
340        max_len: usize,
341    ) -> Result<String> {
342        let len = self.read_u16_be()? as usize;
343        read_utf8_payload_impl(self, len, max_len)
344    }
345
346    #[inline]
347    fn read_string_with_u16_len_le(
348        &mut self,
349        max_len: usize,
350    ) -> Result<String> {
351        let len = self.read_u16_le()? as usize;
352        read_utf8_payload_impl(self, len, max_len)
353    }
354
355    #[inline]
356    fn read_string_with_u32_len(
357        &mut self,
358        byte_order: ByteOrder,
359        max_len: usize,
360    ) -> Result<String> {
361        let len = self.read_u32(byte_order)?;
362        #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
363        let len = len as usize;
364        #[cfg(not(any(
365            target_pointer_width = "32",
366            target_pointer_width = "64"
367        )))]
368        let len = usize_from_u32_len(len)?;
369        read_utf8_payload_impl(self, len, max_len)
370    }
371
372    #[inline]
373    fn read_string_with_u32_len_be(
374        &mut self,
375        max_len: usize,
376    ) -> Result<String> {
377        let len = self.read_u32_be()?;
378        #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
379        let len = len as usize;
380        #[cfg(not(any(
381            target_pointer_width = "32",
382            target_pointer_width = "64"
383        )))]
384        let len = usize_from_u32_len(len)?;
385        read_utf8_payload_impl(self, len, max_len)
386    }
387
388    #[inline]
389    fn read_string_with_u32_len_le(
390        &mut self,
391        max_len: usize,
392    ) -> Result<String> {
393        let len = self.read_u32_le()?;
394        #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
395        let len = len as usize;
396        #[cfg(not(any(
397            target_pointer_width = "32",
398            target_pointer_width = "64"
399        )))]
400        let len = usize_from_u32_len(len)?;
401        read_utf8_payload_impl(self, len, max_len)
402    }
403}