Skip to main content

qubit_io_binary/ext/
string_write_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//! Extension methods for writing length-prefixed UTF-8 strings.
9
10use std::io::Result;
11
12use qubit_codec::ByteOrder;
13use qubit_io::Output;
14
15use crate::BinaryWriteExt;
16use crate::Leb128WriteExt;
17use crate::util::checked_u64_len;
18use crate::util::write_all;
19use crate::util::write_utf8_payload as write_utf8_payload_impl;
20use crate::util::write_utf8_string_with_u16_len;
21use crate::util::write_utf8_string_with_u32_len;
22
23/// Extension methods for writing length-prefixed UTF-8 strings.
24///
25/// A failed write can leave the prefix or payload bytes already written to the
26/// output.
27///
28/// # Examples
29///
30/// ```
31/// use qubit_io_binary::StringWriteExt;
32///
33/// let mut output = Vec::new();
34/// output.write_string_with_u16_len_be("Ada")?;
35/// assert_eq!(output, [0, 3, b'A', b'd', b'a']);
36/// # Ok::<(), std::io::Error>(())
37/// ```
38pub trait StringWriteExt: Output<Item = u8> {
39    /// Writes a UTF-8 payload without a length prefix.
40    ///
41    /// # Parameters
42    ///
43    /// - `value`: String slice to write.
44    ///
45    /// # Returns
46    ///
47    /// Returns after the payload has been written.
48    ///
49    /// # Errors
50    ///
51    /// Returns an I/O error from the underlying writer.
52    fn write_utf8_payload(&mut self, value: &str) -> Result<()>;
53
54    /// Writes a UTF-8 string with an unsigned LEB128 byte-length prefix.
55    ///
56    /// The length prefix is encoded as `usize`, so this format is target-width
57    /// dependent. Prefer `u16` or `u32` length-prefix methods for persistent
58    /// files and cross-platform protocols.
59    ///
60    /// # Parameters
61    ///
62    /// - `value`: String slice to write.
63    ///
64    /// # Returns
65    ///
66    /// Returns after the prefix and payload have been written.
67    ///
68    /// # Errors
69    ///
70    /// Returns an I/O error from the underlying writer.
71    fn write_utf8_string_uleb_usize(&mut self, value: &str) -> Result<()>;
72
73    /// Writes a UTF-8 string with an unsigned LEB128 `u64` byte-length prefix.
74    ///
75    /// Prefer this method over [`Self::write_utf8_string_uleb_usize`] for
76    /// persistent files and cross-platform protocols because the length
77    /// field is independent of the current Rust target's pointer width.
78    ///
79    /// # Parameters
80    ///
81    /// - `value`: String slice to write.
82    ///
83    /// # Returns
84    ///
85    /// Returns after the prefix and payload have been written.
86    ///
87    /// # Errors
88    ///
89    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
90    /// cannot be represented as `u64`, or an I/O error from the underlying
91    /// writer.
92    fn write_utf8_string_uleb_u64(&mut self, value: &str) -> Result<()>;
93
94    /// Writes a UTF-8 string with a runtime-order `u16` byte-length prefix.
95    ///
96    /// # Parameters
97    ///
98    /// - `value`: String slice to write.
99    /// - `byte_order`: Byte order used by the length prefix.
100    ///
101    /// # Returns
102    ///
103    /// Returns after the prefix and payload have been written.
104    ///
105    /// # Errors
106    ///
107    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
108    /// does not fit into `u16`, or an I/O error from the underlying writer.
109    fn write_string_with_u16_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()>;
110
111    /// Writes a UTF-8 string with a big-endian `u16` byte-length prefix.
112    ///
113    /// # Parameters
114    ///
115    /// - `value`: String slice to write.
116    ///
117    /// # Returns
118    ///
119    /// Returns after the prefix and payload have been written.
120    ///
121    /// # Errors
122    ///
123    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
124    /// does not fit into `u16`, or an I/O error from the underlying writer.
125    fn write_string_with_u16_len_be(&mut self, value: &str) -> Result<()>;
126
127    /// Writes a UTF-8 string with a little-endian `u16` byte-length prefix.
128    ///
129    /// # Parameters
130    ///
131    /// - `value`: String slice to write.
132    ///
133    /// # Returns
134    ///
135    /// Returns after the prefix and payload have been written.
136    ///
137    /// # Errors
138    ///
139    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
140    /// does not fit into `u16`, or an I/O error from the underlying writer.
141    fn write_string_with_u16_len_le(&mut self, value: &str) -> Result<()>;
142
143    /// Writes a UTF-8 string with a runtime-order `u32` byte-length prefix.
144    ///
145    /// # Parameters
146    ///
147    /// - `value`: String slice to write.
148    /// - `byte_order`: Byte order used by the length prefix.
149    ///
150    /// # Returns
151    ///
152    /// Returns after the prefix and payload have been written.
153    ///
154    /// # Errors
155    ///
156    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
157    /// does not fit into `u32`, or an I/O error from the underlying writer.
158    fn write_string_with_u32_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()>;
159
160    /// Writes a UTF-8 string with a big-endian `u32` byte-length prefix.
161    ///
162    /// # Parameters
163    ///
164    /// - `value`: String slice to write.
165    ///
166    /// # Returns
167    ///
168    /// Returns after the prefix and payload have been written.
169    ///
170    /// # Errors
171    ///
172    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
173    /// does not fit into `u32`, or an I/O error from the underlying writer.
174    fn write_string_with_u32_len_be(&mut self, value: &str) -> Result<()>;
175
176    /// Writes a UTF-8 string with a little-endian `u32` byte-length prefix.
177    ///
178    /// # Parameters
179    ///
180    /// - `value`: String slice to write.
181    ///
182    /// # Returns
183    ///
184    /// Returns after the prefix and payload have been written.
185    ///
186    /// # Errors
187    ///
188    /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
189    /// does not fit into `u32`, or an I/O error from the underlying writer.
190    fn write_string_with_u32_len_le(&mut self, value: &str) -> Result<()>;
191}
192
193impl<T> StringWriteExt for T
194where
195    T: Output<Item = u8> + ?Sized,
196{
197    #[inline]
198    fn write_utf8_payload(&mut self, value: &str) -> Result<()> {
199        write_utf8_payload_impl(self, value)
200    }
201
202    #[inline]
203    fn write_utf8_string_uleb_usize(&mut self, value: &str) -> Result<()> {
204        let bytes = value.as_bytes();
205        self.write_uleb_usize(bytes.len())?;
206        write_all(self, bytes)
207    }
208
209    #[inline]
210    fn write_utf8_string_uleb_u64(&mut self, value: &str) -> Result<()> {
211        let bytes = value.as_bytes();
212        self.write_uleb_u64(checked_u64_len(bytes.len())?)?;
213        write_all(self, bytes)
214    }
215
216    #[inline]
217    fn write_string_with_u16_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()> {
218        write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16(len, byte_order))
219    }
220
221    #[inline]
222    fn write_string_with_u16_len_be(&mut self, value: &str) -> Result<()> {
223        write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16_be(len))
224    }
225
226    #[inline]
227    fn write_string_with_u16_len_le(&mut self, value: &str) -> Result<()> {
228        write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16_le(len))
229    }
230
231    #[inline]
232    fn write_string_with_u32_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()> {
233        write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32(len, byte_order))
234    }
235
236    #[inline]
237    fn write_string_with_u32_len_be(&mut self, value: &str) -> Result<()> {
238        write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32_be(len))
239    }
240
241    #[inline]
242    fn write_string_with_u32_len_le(&mut self, value: &str) -> Result<()> {
243        write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32_le(len))
244    }
245}