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 #[inline]
200 fn write_utf8_payload(&mut self, value: &str) -> Result<()> {
201 write_utf8_payload_impl(self, value)
202 }
203
204 #[inline]
205 fn write_utf8_string_uleb_usize(&mut self, value: &str) -> Result<()> {
206 let bytes = value.as_bytes();
207 self.write_uleb_usize(bytes.len())?;
208 write_all(self, bytes)
209 }
210
211 #[inline]
212 fn write_utf8_string_uleb_u64(&mut self, value: &str) -> Result<()> {
213 let bytes = value.as_bytes();
214 self.write_uleb_u64(checked_u64_len(bytes.len())?)?;
215 write_all(self, bytes)
216 }
217
218 #[inline]
219 fn write_string_with_u16_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()> {
220 write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16(len, byte_order))
221 }
222
223 #[inline]
224 fn write_string_with_u16_len_be(&mut self, value: &str) -> Result<()> {
225 write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16_be(len))
226 }
227
228 #[inline]
229 fn write_string_with_u16_len_le(&mut self, value: &str) -> Result<()> {
230 write_utf8_string_with_u16_len(self, value, |writer, len| writer.write_u16_le(len))
231 }
232
233 #[inline]
234 fn write_string_with_u32_len(&mut self, value: &str, byte_order: ByteOrder) -> Result<()> {
235 write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32(len, byte_order))
236 }
237
238 #[inline]
239 fn write_string_with_u32_len_be(&mut self, value: &str) -> Result<()> {
240 write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32_be(len))
241 }
242
243 #[inline]
244 fn write_string_with_u32_len_le(&mut self, value: &str) -> Result<()> {
245 write_utf8_string_with_u32_len(self, value, |writer, len| writer.write_u32_le(len))
246 }
247}