about summary refs log tree commit diff
path: root/tvix/eval/src/builtins/mod.rs
diff options
context:
space:
mode:
authorPadraic-O-Mhuiris <patrick.morris.310@gmail.com>2024-02-21T16·49+0000
committerPádraic Ó Mhuiris <patrick.morris.310@gmail.com>2024-02-23T16·04+0000
commit5c3065b43a61a5fa019cbbb157984fc5eb81d439 (patch)
tree897a44fdb7da446413276861c13d2a2365ea5f4b /tvix/eval/src/builtins/mod.rs
parentffb134398dedcae6cd13cdf49b2cd57d43793bda (diff)
feat(tvix/eval): implement `builtins.hashString` r/7597
Implements md5, sha1, sha256 and sha512 using the related crates from
the RustCrypto hashes project (https://github.com/RustCrypto/hashes)

Change-Id: I00730dea44ec9ef85309edc27addab0ae88814b8
Reviewed-on: https://cl.tvl.fyi/c/depot/+/11005
Tested-by: BuildkiteCI
Reviewed-by: aspen <root@gws.fyi>
Diffstat (limited to 'tvix/eval/src/builtins/mod.rs')
-rw-r--r--tvix/eval/src/builtins/mod.rs32
1 files changed, 23 insertions, 9 deletions
diff --git a/tvix/eval/src/builtins/mod.rs b/tvix/eval/src/builtins/mod.rs
index 131f2b7bb201..119c0bda2dc3 100644
--- a/tvix/eval/src/builtins/mod.rs
+++ b/tvix/eval/src/builtins/mod.rs
@@ -5,9 +5,14 @@
 
 use bstr::{ByteSlice, ByteVec};
 use builtin_macros::builtins;
+use data_encoding::HEXLOWER;
 use genawaiter::rc::Gen;
 use imbl::OrdMap;
+use md5::Md5;
 use regex::Regex;
+use sha1::Sha1;
+use sha2::digest::Output;
+use sha2::{Digest, Sha256, Sha512};
 use std::cmp::{self, Ordering};
 use std::collections::VecDeque;
 use std::collections::{BTreeMap, HashSet};
@@ -686,15 +691,24 @@ mod pure_builtins {
 
     #[builtin("hashString")]
     #[allow(non_snake_case)]
-    async fn builtin_hashString(
-        co: GenCo,
-        _algo: Value,
-        _string: Value,
-    ) -> Result<Value, ErrorKind> {
-        // FIXME: propagate contexts here.
-        Ok(Value::from(CatchableErrorKind::UnimplementedFeature(
-            "hashString".into(),
-        )))
+    async fn builtin_hashString(co: GenCo, algo: Value, s: Value) -> Result<Value, ErrorKind> {
+        fn hash<D: Digest>(b: &[u8]) -> Output<D> {
+            let mut hasher = D::new();
+            hasher.update(b);
+            hasher.finalize()
+        }
+
+        let s = s.to_str()?;
+
+        let encoded_hash = match algo.to_str()?.as_bytes() {
+            b"md5" => HEXLOWER.encode(hash::<Md5>(&s).as_bstr()),
+            b"sha1" => HEXLOWER.encode(hash::<Sha1>(&s).as_bstr()),
+            b"sha256" => HEXLOWER.encode(hash::<Sha256>(&s).as_bstr()),
+            b"sha512" => HEXLOWER.encode(hash::<Sha512>(&s).as_bstr()),
+            _ => return Err(ErrorKind::UnknownHashType(s.into())),
+        };
+
+        Ok(Value::from(encoded_hash))
     }
 
     #[builtin("head")]