Skip to content

Commit 8df0405

Browse files
committed
Add encode_to API
In https://github.com/ostreedev/ostree-rs-ext/ we are performing hex encoding in loops and recursively, and it could be helpful for performance to support re-using a buffer instead of allocating a new `String` on the heap. Currently we are using `encode_to_slice`, but then we need to use e.g. `std::str::from_utf8` which unnecessarily performs UTF-8 validation and is also hence fallible even though it doesn't need to be.
1 parent aa8f300 commit 8df0405

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,27 @@ pub fn encode<T: AsRef<[u8]>>(data: T) -> String {
260260
data.encode_hex()
261261
}
262262

263+
/// Encodes `data` as hex string using lowercase characters, appending to target string.
264+
///
265+
/// This is otherwise the same as [`encode`]. One reason to use this function
266+
/// is that if you are performing multiple encodings on distinct data in
267+
/// a loop, this will allow reusing the allocation of a string.
268+
///
269+
/// Alternatively, this is also more efficient to use when you have an
270+
/// existing string and just want to append to it.
271+
///
272+
/// # Example
273+
///
274+
/// ```
275+
/// let mut s = "The hex encoding is: ".to_string();
276+
/// hex::encode_to("Hello world!", &mut s);
277+
/// assert_eq!(s, "The hex encoding is: 48656c6c6f20776f726c6421");
278+
/// ```
279+
#[cfg(feature = "alloc")]
280+
pub fn encode_to<T: AsRef<[u8]>>(data: T, s: &mut String) {
281+
s.extend(BytesToHexChars::new(data.as_ref(), HEX_CHARS_LOWER))
282+
}
283+
263284
/// Encodes `data` as hex string using uppercase characters.
264285
///
265286
/// Apart from the characters' casing, this works exactly like `encode()`.
@@ -276,6 +297,22 @@ pub fn encode_upper<T: AsRef<[u8]>>(data: T) -> String {
276297
data.encode_hex_upper()
277298
}
278299

300+
/// Encodes `data` as hex string using uppercase characters, appending to target string.
301+
///
302+
/// This is the same as [`encode_to`], but uses uppercase characters.
303+
///
304+
/// # Example
305+
///
306+
/// ```
307+
/// let mut s = "The hex encoding is: ".to_string();
308+
/// hex::encode_upper_to("Hello world!", &mut s);
309+
/// assert_eq!(s, "The hex encoding is: 48656C6C6F20776F726C6421");
310+
/// ```
311+
#[cfg(feature = "alloc")]
312+
pub fn encode_upper_to<T: AsRef<[u8]>>(data: T, s: &mut String) {
313+
s.extend(BytesToHexChars::new(data.as_ref(), HEX_CHARS_UPPER))
314+
}
315+
279316
/// Decodes a hex string into raw bytes.
280317
///
281318
/// Both, upper and lower case characters are valid in the input string and can

0 commit comments

Comments
 (0)