Skip to content

Commit fea0fc2

Browse files
committed
Truncate secret hash
The `hex-conservative` crate does not truncate hashes when printed with the `fmt` precision format parameter, this is as expected since a hash is a 32 byte integer (I think) and for integral types precision is ignorded. Add a private struct to handle truncating, and truncate the hash to an 8 byte identifier.
1 parent 789f384 commit fea0fc2

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/secret.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,29 @@ macro_rules! impl_display_secret {
4646
engine.input(&self.secret_bytes());
4747
let hash = sha256::Hash::from_engine(engine);
4848

49-
f.debug_tuple(stringify!($thing)).field(&format_args!("#{:016x}", hash)).finish()
49+
// hex-conservative does not support truncation and this is the correct behaviour if
50+
// a hash is considered integral type. So we truncate manually.
51+
//
52+
// > Precision
53+
// > ...
54+
// > For integral types, this is ignored.
55+
//
56+
// ref: https://doc.rust-lang.org/std/fmt/
57+
58+
struct Id(&[u8]);
59+
60+
impl ::core::fmt::Display for Id {
61+
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
62+
for byte in self.0.iter() {
63+
write!(f, "{:02x}", byte)?;
64+
}
65+
Ok(())
66+
}
67+
}
68+
69+
let id = Id(&hash[0..8]);
70+
71+
f.debug_tuple(stringify!($thing)).field(&format_args!("#{}", id)).finish()
5072
}
5173
}
5274

0 commit comments

Comments
 (0)