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::ByteOutput;
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. Length-prefixed methods are not transactional: retrying the whole
27/// method can append a second length prefix. Recover using the enclosing
28/// protocol's framing or transaction boundary instead.
29///
30/// # Examples
31///
32/// ```
33/// use qubit_io_binary::StringWriteExt;
34///
35/// let mut output = Vec::new();
36/// output.write_string_with_u16_len_be("Ada")?;
37/// assert_eq!(output, [0, 3, b'A', b'd', b'a']);
38/// # Ok::<(), std::io::Error>(())
39/// ```
40pub trait StringWriteExt: ByteOutput {
41 /// Writes a UTF-8 payload without a length prefix.
42 ///
43 /// # Parameters
44 ///
45 /// - `value`: String slice to write.
46 ///
47 /// # Returns
48 ///
49 /// Returns after the payload has been written.
50 ///
51 /// # Errors
52 ///
53 /// Returns an I/O error from the underlying writer.
54 fn write_utf8_payload(&mut self, value: &str) -> Result<()>;
55
56 /// Writes a UTF-8 string with an unsigned LEB128 byte-length prefix.
57 ///
58 /// The length prefix is encoded as `usize`, so this format is target-width
59 /// dependent. Prefer `u16` or `u32` length-prefix methods for persistent
60 /// files and cross-platform protocols.
61 ///
62 /// # Parameters
63 ///
64 /// - `value`: String slice to write.
65 ///
66 /// # Returns
67 ///
68 /// Returns after the prefix and payload have been written.
69 ///
70 /// # Errors
71 ///
72 /// Returns an I/O error from the underlying writer.
73 fn write_utf8_string_uleb_usize(&mut self, value: &str) -> Result<()>;
74
75 /// Writes a UTF-8 string with an unsigned LEB128 `u64` byte-length prefix.
76 ///
77 /// Prefer this method over [`Self::write_utf8_string_uleb_usize`] for
78 /// persistent files and cross-platform protocols because the length
79 /// field is independent of the current Rust target's pointer width.
80 ///
81 /// # Parameters
82 ///
83 /// - `value`: String slice to write.
84 ///
85 /// # Returns
86 ///
87 /// Returns after the prefix and payload have been written.
88 ///
89 /// # Errors
90 ///
91 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
92 /// cannot be represented as `u64`, or an I/O error from the underlying
93 /// writer.
94 fn write_utf8_string_uleb_u64(&mut self, value: &str) -> Result<()>;
95
96 /// Writes a UTF-8 string with a runtime-order `u16` byte-length prefix.
97 ///
98 /// # Parameters
99 ///
100 /// - `value`: String slice to write.
101 /// - `byte_order`: Byte order used by the length prefix.
102 ///
103 /// # Returns
104 ///
105 /// Returns after the prefix and payload have been written.
106 ///
107 /// # Errors
108 ///
109 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
110 /// does not fit into `u16`, or an I/O error from the underlying writer.
111 fn write_string_with_u16_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()>;
112
113 /// Writes a UTF-8 string with a big-endian `u16` byte-length prefix.
114 ///
115 /// # Parameters
116 ///
117 /// - `value`: String slice to write.
118 ///
119 /// # Returns
120 ///
121 /// Returns after the prefix and payload have been written.
122 ///
123 /// # Errors
124 ///
125 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
126 /// does not fit into `u16`, or an I/O error from the underlying writer.
127 fn write_string_with_u16_len_be(&mut self, value: &str) -> Result<()>;
128
129 /// Writes a UTF-8 string with a little-endian `u16` byte-length prefix.
130 ///
131 /// # Parameters
132 ///
133 /// - `value`: String slice to write.
134 ///
135 /// # Returns
136 ///
137 /// Returns after the prefix and payload have been written.
138 ///
139 /// # Errors
140 ///
141 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
142 /// does not fit into `u16`, or an I/O error from the underlying writer.
143 fn write_string_with_u16_len_le(&mut self, value: &str) -> Result<()>;
144
145 /// Writes a UTF-8 string with a runtime-order `u32` byte-length prefix.
146 ///
147 /// # Parameters
148 ///
149 /// - `value`: String slice to write.
150 /// - `byte_order`: Byte order used by the length prefix.
151 ///
152 /// # Returns
153 ///
154 /// Returns after the prefix and payload have been written.
155 ///
156 /// # Errors
157 ///
158 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
159 /// does not fit into `u32`, or an I/O error from the underlying writer.
160 fn write_string_with_u32_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()>;
161
162 /// Writes a UTF-8 string with a big-endian `u32` byte-length prefix.
163 ///
164 /// # Parameters
165 ///
166 /// - `value`: String slice to write.
167 ///
168 /// # Returns
169 ///
170 /// Returns after the prefix and payload have been written.
171 ///
172 /// # Errors
173 ///
174 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
175 /// does not fit into `u32`, or an I/O error from the underlying writer.
176 fn write_string_with_u32_len_be(&mut self, value: &str) -> Result<()>;
177
178 /// Writes a UTF-8 string with a little-endian `u32` byte-length prefix.
179 ///
180 /// # Parameters
181 ///
182 /// - `value`: String slice to write.
183 ///
184 /// # Returns
185 ///
186 /// Returns after the prefix and payload have been written.
187 ///
188 /// # Errors
189 ///
190 /// Returns [`std::io::ErrorKind::InvalidInput`] when the UTF-8 byte length
191 /// does not fit into `u32`, or an I/O error from the underlying writer.
192 fn write_string_with_u32_len_le(&mut self, value: &str) -> Result<()>;
193}
194
195impl<T> StringWriteExt for T
196where
197 T: ByteOutput + ?Sized,
198{
199 /// Writes the string's UTF-8 bytes without adding a length prefix.
200 ///
201 /// A write failure may occur after some payload bytes have reached the
202 /// underlying output.
203 ///
204 /// # Parameters
205 ///
206 /// - `value`: UTF-8 string whose bytes are written to the output.
207 ///
208 /// # Returns
209 ///
210 /// Returns after all UTF-8 payload bytes have been written.
211 ///
212 /// # Errors
213 ///
214 /// Returns an I/O error from the underlying output.
215 #[inline]
216 fn write_utf8_payload(&mut self, value: &str) -> Result<()> {
217 write_utf8_payload_impl(self, value)
218 }
219
220 /// Writes the UTF-8 byte length as target-width-dependent unsigned LEB128,
221 /// followed by the string bytes.
222 ///
223 /// A failure can leave a partial prefix or payload in the output.
224 ///
225 /// # Parameters
226 ///
227 /// - `value`: UTF-8 string to write after its target-width-dependent byte
228 /// length.
229 ///
230 /// # Returns
231 ///
232 /// Returns after the length prefix and payload have been written.
233 ///
234 /// # Errors
235 ///
236 /// Returns an I/O error from writing the prefix or payload.
237 #[inline]
238 fn write_utf8_string_uleb_usize(&mut self, value: &str) -> Result<()> {
239 let bytes = value.as_bytes();
240 self.write_uleb_usize(bytes.len())?;
241 write_all(self, bytes)
242 }
243
244 /// Writes the UTF-8 byte length as unsigned LEB128 `u64`, then the string
245 /// bytes.
246 ///
247 /// Returns `InvalidInput` if the byte length does not fit in `u64`; a
248 /// write failure can leave a partial prefix or payload in the output.
249 ///
250 /// # Parameters
251 ///
252 /// - `value`: UTF-8 string to write after its `u64` byte length.
253 ///
254 /// # Returns
255 ///
256 /// Returns after the length prefix and payload have been written.
257 ///
258 /// # Errors
259 ///
260 /// Returns `InvalidInput` if the byte length does not fit in `u64`, or an
261 /// I/O error while writing.
262 #[inline]
263 fn write_utf8_string_uleb_u64(&mut self, value: &str) -> Result<()> {
264 let bytes = value.as_bytes();
265 self.write_uleb_u64(checked_u64_len(bytes.len())?)?;
266 write_all(self, bytes)
267 }
268
269 /// Writes a `u16` UTF-8 byte-length prefix in the requested byte order,
270 /// followed by the string bytes.
271 ///
272 /// Returns `InvalidInput` if the byte length exceeds `u16::MAX`; a write
273 /// failure can leave a partial prefix or payload in the output.
274 ///
275 /// # Parameters
276 ///
277 /// - `value`: UTF-8 string to write after its `u16` byte length.
278 /// - `byte_order`: Byte order used to encode the length prefix.
279 ///
280 /// # Returns
281 ///
282 /// Returns after the length prefix and payload have been written.
283 ///
284 /// # Errors
285 ///
286 /// Returns `InvalidInput` if the byte length exceeds `u16::MAX`, or an
287 /// I/O error while writing.
288 #[inline]
289 fn write_string_with_u16_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()> {
290 write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16(len, byte_order))
291 }
292
293 /// Writes a big-endian `u16` UTF-8 byte-length prefix, then the string
294 /// bytes.
295 ///
296 /// Returns `InvalidInput` if the byte length exceeds `u16::MAX`; a write
297 /// failure can leave a partial prefix or payload in the output.
298 ///
299 /// # Parameters
300 ///
301 /// - `value`: UTF-8 string to write after its big-endian `u16` byte length.
302 ///
303 /// # Returns
304 ///
305 /// Returns after the length prefix and payload have been written.
306 ///
307 /// # Errors
308 ///
309 /// Returns `InvalidInput` if the byte length exceeds `u16::MAX`, or an
310 /// I/O error while writing.
311 #[inline]
312 fn write_string_with_u16_len_be(&mut self, value: &str) -> Result<()> {
313 write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16_be(len))
314 }
315
316 /// Writes a little-endian `u16` UTF-8 byte-length prefix, then the string
317 /// bytes.
318 ///
319 /// Returns `InvalidInput` if the byte length exceeds `u16::MAX`; a write
320 /// failure can leave a partial prefix or payload in the output.
321 ///
322 /// # Parameters
323 ///
324 /// - `value`: UTF-8 string to write after its little-endian `u16` byte
325 /// length.
326 ///
327 /// # Returns
328 ///
329 /// Returns after the length prefix and payload have been written.
330 ///
331 /// # Errors
332 ///
333 /// Returns `InvalidInput` if the byte length exceeds `u16::MAX`, or an
334 /// I/O error while writing.
335 #[inline]
336 fn write_string_with_u16_len_le(&mut self, value: &str) -> Result<()> {
337 write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16_le(len))
338 }
339
340 /// Writes a `u32` UTF-8 byte-length prefix in the requested byte order,
341 /// followed by the string bytes.
342 ///
343 /// Returns `InvalidInput` if the byte length exceeds `u32::MAX`; a write
344 /// failure can leave a partial prefix or payload in the output.
345 ///
346 /// # Parameters
347 ///
348 /// - `value`: UTF-8 string to write after its `u32` byte length.
349 /// - `byte_order`: Byte order used to encode the length prefix.
350 ///
351 /// # Returns
352 ///
353 /// Returns after the length prefix and payload have been written.
354 ///
355 /// # Errors
356 ///
357 /// Returns `InvalidInput` if the byte length exceeds `u32::MAX`, or an
358 /// I/O error while writing.
359 #[inline]
360 fn write_string_with_u32_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()> {
361 write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32(len, byte_order))
362 }
363
364 /// Writes a big-endian `u32` UTF-8 byte-length prefix, then the string
365 /// bytes.
366 ///
367 /// Returns `InvalidInput` if the byte length exceeds `u32::MAX`; a write
368 /// failure can leave a partial prefix or payload in the output.
369 ///
370 /// # Parameters
371 ///
372 /// - `value`: UTF-8 string to write after its big-endian `u32` byte length.
373 ///
374 /// # Returns
375 ///
376 /// Returns after the length prefix and payload have been written.
377 ///
378 /// # Errors
379 ///
380 /// Returns `InvalidInput` if the byte length exceeds `u32::MAX`, or an
381 /// I/O error while writing.
382 #[inline]
383 fn write_string_with_u32_len_be(&mut self, value: &str) -> Result<()> {
384 write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32_be(len))
385 }
386
387 /// Writes a little-endian `u32` UTF-8 byte-length prefix, then the string
388 /// bytes.
389 ///
390 /// Returns `InvalidInput` if the byte length exceeds `u32::MAX`; a write
391 /// failure can leave a partial prefix or payload in the output.
392 ///
393 /// # Parameters
394 ///
395 /// - `value`: UTF-8 string to write after its little-endian `u32` byte
396 /// length.
397 ///
398 /// # Returns
399 ///
400 /// Returns after the length prefix and payload have been written.
401 ///
402 /// # Errors
403 ///
404 /// Returns `InvalidInput` if the byte length exceeds `u32::MAX`, or an
405 /// I/O error while writing.
406 #[inline]
407 fn write_string_with_u32_len_le(&mut self, value: &str) -> Result<()> {
408 write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32_le(len))
409 }
410}