Skip to content

Commit c17aee6

Browse files
committed
fix!: hex-display of any object ID is now faster as oid::hex_to_buf() now returns &mut str.
This helps callers to avoid converting to UTF8 by hand.
1 parent 592e250 commit c17aee6

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

gix-hash/src/oid.rs

+9-12
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,9 @@ pub struct HexDisplay<'a> {
4444
impl std::fmt::Display for HexDisplay<'_> {
4545
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4646
let mut hex = Kind::hex_buf();
47-
let max_len = self.inner.hex_to_buf(hex.as_mut());
48-
let hex = std::str::from_utf8(&hex[..self.hex_len.min(max_len)]).expect("ascii only in hex");
49-
f.write_str(hex)
47+
let hex = self.inner.hex_to_buf(hex.as_mut());
48+
let max_len = hex.len();
49+
f.write_str(&hex[..self.hex_len.min(max_len)])
5050
}
5151
}
5252

@@ -152,22 +152,21 @@ impl oid {
152152

153153
/// Sha1 specific methods
154154
impl oid {
155-
/// Write ourselves to the `out` in hexadecimal notation, returning the amount of written bytes.
155+
/// Write ourselves to the `out` in hexadecimal notation, returning the hex-string ready for display.
156156
///
157157
/// **Panics** if the buffer isn't big enough to hold twice as many bytes as the current binary size.
158158
#[inline]
159159
#[must_use]
160-
pub fn hex_to_buf(&self, buf: &mut [u8]) -> usize {
160+
pub fn hex_to_buf<'a>(&self, buf: &'a mut [u8]) -> &'a mut str {
161161
let num_hex_bytes = self.bytes.len() * 2;
162-
faster_hex::hex_encode(&self.bytes, &mut buf[..num_hex_bytes]).expect("to count correctly");
163-
num_hex_bytes
162+
faster_hex::hex_encode(&self.bytes, &mut buf[..num_hex_bytes]).expect("to count correctly")
164163
}
165164

166165
/// Write ourselves to `out` in hexadecimal notation.
167166
#[inline]
168167
pub fn write_hex_to(&self, out: &mut dyn std::io::Write) -> std::io::Result<()> {
169168
let mut hex = Kind::hex_buf();
170-
let hex_len = self.hex_to_buf(&mut hex);
169+
let hex_len = self.hex_to_buf(&mut hex).len();
171170
out.write_all(&hex[..hex_len])
172171
}
173172

@@ -210,10 +209,8 @@ impl<'a> From<&'a [u8; SIZE_OF_SHA1_DIGEST]> for &'a oid {
210209

211210
impl std::fmt::Display for &oid {
212211
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213-
for b in self.as_bytes() {
214-
write!(f, "{b:02x}")?;
215-
}
216-
Ok(())
212+
let mut buf = Kind::hex_buf();
213+
f.write_str(self.hex_to_buf(&mut buf))
217214
}
218215
}
219216

0 commit comments

Comments
 (0)