about summary refs log tree commit diff
diff options
context:
space:
mode:
-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 {