From c2a681eaff09777011e6ea892411f6ac261caea7 Mon Sep 17 00:00:00 2001 From: Florian Klink Date: Sat, 4 Mar 2023 03:24:01 +0100 Subject: feat(tvix/nix-compat): add NixHash::{new, to_nix_hash_string} This provides a way to construct a NixHash struct without parsing strings. Change-Id: I947d96e15e51e72d5b02929cda8c5fc31d81253a Reviewed-on: https://cl.tvl.fyi/c/depot/+/8217 Tested-by: BuildkiteCI Autosubmit: flokli Reviewed-by: tazjin --- tvix/nix-compat/src/nixhash.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tvix/nix-compat/src/nixhash.rs b/tvix/nix-compat/src/nixhash.rs index 100c127692b3..4cb076ed16b0 100644 --- a/tvix/nix-compat/src/nixhash.rs +++ b/tvix/nix-compat/src/nixhash.rs @@ -1,4 +1,4 @@ -use data_encoding::{BASE64, BASE64_NOPAD}; +use data_encoding::{BASE64, BASE64_NOPAD, HEXLOWER}; use std::fmt::Display; use thiserror::Error; @@ -12,6 +12,19 @@ pub struct NixHash { pub algo: HashAlgo, } +impl NixHash { + /// Constructs a new [NixHash] by specifying [HashAlgo] and digest. + pub fn new(algo: HashAlgo, digest: Vec) -> Self { + Self { algo, digest } + } + + /// Formats a [NixHash] in the Nix default hash format, + /// which is the algo, followed by a colon, then the lower hex encoded digest. + pub fn to_nix_hash_string(&self) -> String { + format!("{}:{}", self.algo, HEXLOWER.encode(&self.digest)) + } +} + /// This are the hash algorithms supported by cppnix. #[derive(Clone, Debug, Eq, PartialEq)] pub enum HashAlgo { -- cgit 1.4.1