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