Skip to main content

qubit_io_binary/ext/
async_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// =============================================================================
8//! Asynchronous length-prefixed UTF-8 reads.
9
10use core::future::Future;
11use std::io::Result;
12
13use qubit_codec::ByteOrder;
14use qubit_io::AsyncInput;
15
16use crate::AsyncBinaryReadExt;
17use crate::AsyncLeb128ReadExt;
18use crate::util::read_utf8_payload_async;
19use crate::util::read_utf8_payload_into_async;
20#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
21use crate::util::usize_from_u32_len;
22#[cfg(not(target_pointer_width = "64"))]
23use crate::util::usize_from_u64_len;
24
25/// Future-based length-prefixed UTF-8 reads.
26///
27/// # Cancellation safety
28///
29/// These reads are not cancellation safe. Dropping a pending future leaves
30/// bytes already consumed from the prefix or payload consumed.
31///
32/// A length above max_len consumes its prefix but leaves the payload unread;
33/// invalid UTF-8 is reported after the complete payload has been consumed.
34/// Neither failure rolls back the input.
35///
36/// # Examples
37///
38/// Define a generic async helper that reads a bounded, length-prefixed label:
39///
40/// ```
41/// use qubit_io::AsyncInput;
42/// use qubit_io_binary::AsyncStringReadExt;
43///
44/// async fn read_label<I>(input: &mut I) -> std::io::Result<String>
45/// where
46///     I: AsyncInput<Item = u8> + Unpin,
47/// {
48///     input.read_utf8_string_uleb_u64_strict_async(64).await
49/// }
50/// ```
51pub trait AsyncStringReadExt: AsyncInput<Item = u8> {
52    /// Asynchronously reads and validates a UTF-8 payload into reusable byte
53    /// storage.
54    ///
55    /// # Parameters
56    ///
57    /// - `bytes`: Reusable destination buffer. It is cleared before a permitted
58    ///   read and contains the received bytes when the read succeeds or when
59    ///   UTF-8 validation fails.
60    /// - `len`: Encoded payload length in bytes.
61    /// - `max_len`: Maximum accepted payload length in bytes.
62    ///
63    /// If `len` exceeds `max_len`, `bytes` is left unchanged. Once the length
64    /// is accepted, its previous contents may be cleared even if allocation or
65    /// reading fails. After an I/O error or after a polled future is cancelled,
66    /// `bytes` is not a complete payload: its length does not report how many
67    /// bytes were received, and it may contain zero-filled bytes that were
68    /// never read.
69    /// Invalid UTF-8 is reported only after the complete payload has been
70    /// received, so all payload bytes remain available in `bytes` for
71    /// diagnostics.
72    ///
73    /// # Returns
74    ///
75    /// Returns a future that completes after `bytes` contains one valid UTF-8
76    /// payload.
77    ///
78    /// # Errors
79    ///
80    /// Returns an input or allocation error, or an invalid-data error when
81    /// `len` exceeds `max_len` or the payload is not valid UTF-8.
82    ///
83    /// # Cancellation safety
84    ///
85    /// This operation is not cancellation safe. Dropping a future before it is
86    /// polled performs no read. Dropping it after polling does not roll back
87    /// bytes consumed from the input or modifications made to `bytes`.
88    #[inline]
89    fn read_utf8_payload_into_async<'a>(
90        &'a mut self,
91        bytes: &'a mut Vec<u8>,
92        len: usize,
93        max_len: usize,
94    ) -> impl Future<Output = Result<()>> + 'a
95    where
96        Self: Unpin,
97    {
98        async move { read_utf8_payload_into_async(self, bytes, len, max_len).await }
99    }
100
101    /// Asynchronously reads an already length-delimited UTF-8 payload.
102    ///
103    /// # Parameters
104    ///
105    /// - `len`: Encoded payload length in bytes.
106    /// - `max_len`: Maximum accepted payload length in bytes.
107    ///
108    /// # Returns
109    ///
110    /// Returns the decoded string.
111    ///
112    /// # Errors
113    ///
114    /// Returns an input or allocation error, or an invalid-data error when
115    /// `len` exceeds `max_len` or the payload is not valid UTF-8.
116    ///
117    /// # Cancellation safety
118    ///
119    /// This operation is not cancellation safe; dropping the future retains
120    /// any bytes already consumed from the input.
121    #[inline]
122    fn read_utf8_payload_async(&mut self, len: usize, max_len: usize) -> impl Future<Output = Result<String>> + '_
123    where
124        Self: Unpin,
125    {
126        async move { read_utf8_payload_async(self, len, max_len).await }
127    }
128
129    /// Asynchronously reads a target-width LEB128-length UTF-8 string.
130    ///
131    /// # Parameters
132    ///
133    /// - `max_len`: Maximum accepted payload length in bytes.
134    ///
135    /// # Returns
136    ///
137    /// Returns the decoded string.
138    ///
139    /// # Errors
140    ///
141    /// Returns an input or allocation error, or an invalid-data error for a
142    /// malformed length, an excessive length, or invalid UTF-8.
143    ///
144    /// # Cancellation safety
145    ///
146    /// This operation is not cancellation safe; dropping the future retains
147    /// any prefix or payload bytes already consumed.
148    #[inline]
149    fn read_utf8_string_uleb_usize_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
150    where
151        Self: Unpin,
152    {
153        async move {
154            let len = self.read_uleb_usize_non_strict_async().await?;
155            read_utf8_payload_async(self, len, max_len).await
156        }
157    }
158
159    /// Asynchronously reads a canonical target-width LEB128-length string.
160    ///
161    /// # Parameters
162    ///
163    /// - `max_len`: Maximum accepted payload length in bytes.
164    ///
165    /// # Returns
166    ///
167    /// Returns the decoded string.
168    ///
169    /// # Errors
170    ///
171    /// Returns an input or allocation error, or an invalid-data error for a
172    /// non-canonical length, an excessive length, or invalid UTF-8.
173    ///
174    /// # Cancellation safety
175    ///
176    /// This operation is not cancellation safe; dropping the future retains
177    /// any prefix or payload bytes already consumed.
178    #[inline]
179    fn read_utf8_string_uleb_usize_strict_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
180    where
181        Self: Unpin,
182    {
183        async move {
184            let len = self.read_uleb_usize_strict_async().await?;
185            read_utf8_payload_async(self, len, max_len).await
186        }
187    }
188
189    /// Asynchronously reads a `u64` LEB128-length UTF-8 string.
190    ///
191    /// # Parameters
192    ///
193    /// - `max_len`: Maximum accepted payload length in bytes.
194    ///
195    /// # Returns
196    ///
197    /// Returns the decoded string.
198    ///
199    /// # Errors
200    ///
201    /// Returns an input, conversion, or allocation error, or an invalid-data
202    /// error for a malformed or excessive length or invalid UTF-8.
203    ///
204    /// # Cancellation safety
205    ///
206    /// This operation is not cancellation safe; dropping the future retains
207    /// any prefix or payload bytes already consumed.
208    #[inline]
209    fn read_utf8_string_uleb_u64_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
210    where
211        Self: Unpin,
212    {
213        async move {
214            let len = self.read_uleb_u64_non_strict_async().await?;
215            #[cfg(target_pointer_width = "64")]
216            let len = len as usize;
217            #[cfg(not(target_pointer_width = "64"))]
218            let len = usize_from_u64_len(len)?;
219            read_utf8_payload_async(self, len, max_len).await
220        }
221    }
222
223    /// Asynchronously reads a canonical `u64` LEB128-length UTF-8 string.
224    ///
225    /// # Parameters
226    ///
227    /// - `max_len`: Maximum accepted payload length in bytes.
228    ///
229    /// # Returns
230    ///
231    /// Returns the decoded string.
232    ///
233    /// # Errors
234    ///
235    /// Returns an input, conversion, or allocation error, or an invalid-data
236    /// error for a non-canonical or excessive length or invalid UTF-8.
237    ///
238    /// # Cancellation safety
239    ///
240    /// This operation is not cancellation safe; dropping the future retains
241    /// any prefix or payload bytes already consumed.
242    #[inline]
243    fn read_utf8_string_uleb_u64_strict_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
244    where
245        Self: Unpin,
246    {
247        async move {
248            let len = self.read_uleb_u64_strict_async().await?;
249            #[cfg(target_pointer_width = "64")]
250            let len = len as usize;
251            #[cfg(not(target_pointer_width = "64"))]
252            let len = usize_from_u64_len(len)?;
253            read_utf8_payload_async(self, len, max_len).await
254        }
255    }
256
257    /// Asynchronously reads a runtime-order `u16`-length UTF-8 string.
258    ///
259    /// # Parameters
260    ///
261    /// - `byte_order`: Byte order used to decode the length.
262    /// - `max_len`: Maximum accepted payload length in bytes.
263    ///
264    /// # Returns
265    ///
266    /// Returns the decoded string.
267    ///
268    /// # Errors
269    ///
270    /// Returns an input or allocation error, or an invalid-data error for an
271    /// excessive length or invalid UTF-8.
272    ///
273    /// # Cancellation safety
274    ///
275    /// This operation is not cancellation safe; dropping the future retains
276    /// any prefix or payload bytes already consumed.
277    #[inline]
278    fn read_string_with_u16_len_async(
279        &mut self,
280        byte_order: ByteOrder,
281        max_len: usize,
282    ) -> impl Future<Output = Result<String>> + '_
283    where
284        Self: Unpin,
285    {
286        async move {
287            let len = usize::from(self.read_u16_async(byte_order).await?);
288            read_utf8_payload_async(self, len, max_len).await
289        }
290    }
291
292    /// Asynchronously reads a big-endian `u16`-length UTF-8 string.
293    ///
294    /// # Parameters
295    ///
296    /// - `max_len`: Maximum accepted payload length in bytes.
297    ///
298    /// # Returns
299    ///
300    /// Returns the decoded string.
301    ///
302    /// # Errors
303    ///
304    /// Returns an input or allocation error, or an invalid-data error for an
305    /// excessive length or invalid UTF-8.
306    ///
307    /// # Cancellation safety
308    ///
309    /// This operation is not cancellation safe; dropping the future retains
310    /// any prefix or payload bytes already consumed.
311    #[inline]
312    fn read_string_with_u16_len_be_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
313    where
314        Self: Unpin,
315    {
316        async move {
317            let len = usize::from(self.read_u16_be_async().await?);
318            read_utf8_payload_async(self, len, max_len).await
319        }
320    }
321
322    /// Asynchronously reads a little-endian `u16`-length UTF-8 string.
323    ///
324    /// # Parameters
325    ///
326    /// - `max_len`: Maximum accepted payload length in bytes.
327    ///
328    /// # Returns
329    ///
330    /// Returns the decoded string.
331    ///
332    /// # Errors
333    ///
334    /// Returns an input or allocation error, or an invalid-data error for an
335    /// excessive length or invalid UTF-8.
336    ///
337    /// # Cancellation safety
338    ///
339    /// This operation is not cancellation safe; dropping the future retains
340    /// any prefix or payload bytes already consumed.
341    #[inline]
342    fn read_string_with_u16_len_le_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
343    where
344        Self: Unpin,
345    {
346        async move {
347            let len = usize::from(self.read_u16_le_async().await?);
348            read_utf8_payload_async(self, len, max_len).await
349        }
350    }
351
352    /// Asynchronously reads a runtime-order `u32`-length UTF-8 string.
353    ///
354    /// # Parameters
355    ///
356    /// - `byte_order`: Byte order used to decode the length.
357    /// - `max_len`: Maximum accepted payload length in bytes.
358    ///
359    /// # Returns
360    ///
361    /// Returns the decoded string.
362    ///
363    /// # Errors
364    ///
365    /// Returns an input, conversion, or allocation error, or an invalid-data
366    /// error for an excessive length or invalid UTF-8.
367    ///
368    /// # Cancellation safety
369    ///
370    /// This operation is not cancellation safe; dropping the future retains
371    /// any prefix or payload bytes already consumed.
372    #[inline]
373    fn read_string_with_u32_len_async(
374        &mut self,
375        byte_order: ByteOrder,
376        max_len: usize,
377    ) -> impl Future<Output = Result<String>> + '_
378    where
379        Self: Unpin,
380    {
381        async move {
382            let len = self.read_u32_async(byte_order).await?;
383            #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
384            let len = len as usize;
385            #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
386            let len = usize_from_u32_len(len)?;
387            read_utf8_payload_async(self, len, max_len).await
388        }
389    }
390
391    /// Asynchronously reads a big-endian `u32`-length UTF-8 string.
392    ///
393    /// # Parameters
394    ///
395    /// - `max_len`: Maximum accepted payload length in bytes.
396    ///
397    /// # Returns
398    ///
399    /// Returns the decoded string.
400    ///
401    /// # Errors
402    ///
403    /// Returns an input, conversion, or allocation error, or an invalid-data
404    /// error for an excessive length or invalid UTF-8.
405    ///
406    /// # Cancellation safety
407    ///
408    /// This operation is not cancellation safe; dropping the future retains
409    /// any prefix or payload bytes already consumed.
410    #[inline]
411    fn read_string_with_u32_len_be_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
412    where
413        Self: Unpin,
414    {
415        async move {
416            let len = self.read_u32_be_async().await?;
417            #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
418            let len = len as usize;
419            #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
420            let len = usize_from_u32_len(len)?;
421            read_utf8_payload_async(self, len, max_len).await
422        }
423    }
424
425    /// Asynchronously reads a little-endian `u32`-length UTF-8 string.
426    ///
427    /// # Parameters
428    ///
429    /// - `max_len`: Maximum accepted payload length in bytes.
430    ///
431    /// # Returns
432    ///
433    /// Returns the decoded string.
434    ///
435    /// # Errors
436    ///
437    /// Returns an input, conversion, or allocation error, or an invalid-data
438    /// error for an excessive length or invalid UTF-8.
439    ///
440    /// # Cancellation safety
441    ///
442    /// This operation is not cancellation safe; dropping the future retains
443    /// any prefix or payload bytes already consumed.
444    #[inline]
445    fn read_string_with_u32_len_le_async(&mut self, max_len: usize) -> impl Future<Output = Result<String>> + '_
446    where
447        Self: Unpin,
448    {
449        async move {
450            let len = self.read_u32_le_async().await?;
451            #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
452            let len = len as usize;
453            #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
454            let len = usize_from_u32_len(len)?;
455            read_utf8_payload_async(self, len, max_len).await
456        }
457    }
458}
459
460impl<R> AsyncStringReadExt for R where R: AsyncInput<Item = u8> + ?Sized {}