about summary refs log tree commit diff
path: root/tvix
diff options
context:
space:
mode:
authorFlorian Klink <flokli@flokli.de>2023-03-04T02·24+0100
committertazjin <tazjin@tvl.su>2023-03-04T12·26+0000
commitc2a681eaff09777011e6ea892411f6ac261caea7 (patch)
tree84e5cebcd6dc8fbc842e691a0035223573ebaef9 /tvix
parent67c9e2c770257efc24dabd8590b5f6618fe27bcb (diff)
feat(tvix/nix-compat): add NixHash::{new, to_nix_hash_string} r/5881
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 <flokli@flokli.de>
Reviewed-by: tazjin <tazjin@tvl.su>
Diffstat (limited to 'tvix')
-rw-r--r--tvix/nix-compat/src/nixhash.rs15
1 files changed, 14 insertions, 1 deletions
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<u8>) -> 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 {