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:
parent
5b41ae66eb
commit
97f215aef2
1 changed files with 24 additions and 9 deletions
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue