faster-hex icon indicating copy to clipboard operation
faster-hex copied to clipboard

Add `hex_encode_into` function

Open Enduriel opened this issue 5 months ago • 3 comments

This would have the signature

pub fn hex_encode_into(src: &[u8], dst: &mut String)

I find myself passing around a string a that I write into a lot, and having to do

unsafe {
	let dst = dst.as_mut_vec();
	let dst_len = dst.len()
	dst.resize(dst_len + src.len() * 2, 0);
	faster_hex::hex_encode(src, &mut dst[dst_len..]).unwrap_unchecked();
}

is somewhat annoying. Is this something you'd be interested in adding/accept a PR for?

Enduriel avatar Jul 23 '25 16:07 Enduriel

The low-level interface of faster-hex is designed for scenarios where buffer reuse is possible, maintaining flexibility to avoid allocation.

If we add a high-level interface, I feel that passing a string is quite unnecessary.

Would directly using hex_string like this meet your needs?

let hex_string = hex_string("Hello world!");

zhangsoledad avatar Jul 28 '25 03:07 zhangsoledad

Hi @Enduriel ,How about append hex_encode's result to a mutable String like this:

    let src: &[u8] = todo!();
    let encode: String = faster_hex::hex_string(src);

    let mut dst: String = todo!();
    dst.push_str(&encode);

eval-exec avatar Jul 28 '25 09:07 eval-exec

I'm in a situation where I need to append a hex string to an existing String, one in which I may or may not have already allocated sufficient capacity in the String for the new hex characters. I'm trying to extend this string without an additionally unnecessary allocation and ideally without any additional copies.

There are of course ways to do this with unnecessary allocations, but these shouldn't be necessary.

ETA: in an ideal world. We would even remove that resize filling the buffer with 0s, because that's also unnecessary (and while it might get optimized out, I've seen that kind of buffer initialization not get optimized out by the compiler for some reason)

Enduriel avatar Jul 28 '25 10:07 Enduriel