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 <personal@ilanjoselevich.com>
Tested-by: besadii
Autosubmit: Florian Klink <flokli@flokli.de>
This commit is contained in:
Florian Klink 2025-06-02 12:10:57 +02:00 committed by clbot
parent 5b41ae66eb
commit 97f215aef2

View file

@ -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 { impl Display for NixHash {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
write!( self.write_sri_str(f)
f,
"{}-{}",
self.algo(),
BASE64.encode(self.digest_as_bytes())
)
} }
} }
@ -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. /// Returns the digest as a hex string -- without any algorithm prefix.
pub fn to_plain_hex_string(&self) -> String { pub fn to_plain_hex_string(&self) -> String {
HEXLOWER.encode(self.digest_as_bytes()) HEXLOWER.encode(self.digest_as_bytes())
@ -143,9 +159,8 @@ impl Serialize for NixHash {
where where
S: serde::Serializer, S: serde::Serializer,
{ {
// encode as SRI let sri = self.to_sri_string();
let string = format!("{}-{}", self.algo(), BASE64.encode(self.digest_as_bytes())); sri.serialize(serializer)
string.serialize(serializer)
} }
} }