From 97f215aef28921f10fe165b10cf973695b10ff27 Mon Sep 17 00:00:00 2001 From: Florian Klink Date: Mon, 2 Jun 2025 12:10:57 +0200 Subject: [PATCH] feat(nix-compat/nixhash): add NixHash::to_sri_string As can be seen in https://github.com/andir/npins/pull/139/files#diff-ec60332b9e2ccfe20e64db6d804f37fe4c652ae58c0679a13e30548cecf1c32fR12, it makes sense to have this as a function for external consumers. This is already also exposed in the Display impl, but it's better to have an explicit function. Change-Id: I1e16d8bd64502802a9642a2f08ddeb5cbbceacae Reviewed-on: https://cl.snix.dev/c/snix/+/30545 Reviewed-by: Ilan Joselevich Tested-by: besadii Autosubmit: Florian Klink --- snix/nix-compat/src/nixhash/mod.rs | 33 ++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/snix/nix-compat/src/nixhash/mod.rs b/snix/nix-compat/src/nixhash/mod.rs index f16753ed4..9cb6f6605 100644 --- a/snix/nix-compat/src/nixhash/mod.rs +++ b/snix/nix-compat/src/nixhash/mod.rs @@ -40,14 +40,12 @@ impl PartialOrd for NixHash { } } +// This provides a Display impl, which happens to be SRI right now. +// If you explicitly care about the format, use [NixHash::to_sri_string] +// or [NixHash::write_sri_str]. impl Display for NixHash { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { - write!( - f, - "{}-{}", - self.algo(), - BASE64.encode(self.digest_as_bytes()) - ) + self.write_sri_str(f) } } @@ -108,6 +106,24 @@ impl NixHash { ) } + /// Writes a [NixHash] in SRI format to a [std::fmt::Write]. + pub fn write_sri_str(&self, w: &mut impl std::fmt::Write) -> Result<(), std::fmt::Error> { + write!( + w, + "{}-{}", + self.algo(), + BASE64.encode(self.digest_as_bytes()) + ) + } + + /// Formats a [NixHash] to an SRI string. + pub fn to_sri_string(&self) -> String { + let mut s = String::new(); + self.write_sri_str(&mut s).unwrap(); + + s + } + /// Returns the digest as a hex string -- without any algorithm prefix. pub fn to_plain_hex_string(&self) -> String { HEXLOWER.encode(self.digest_as_bytes()) @@ -143,9 +159,8 @@ impl Serialize for NixHash { where S: serde::Serializer, { - // encode as SRI - let string = format!("{}-{}", self.algo(), BASE64.encode(self.digest_as_bytes())); - string.serialize(serializer) + let sri = self.to_sri_string(); + sri.serialize(serializer) } }