]> git.ipfire.org Git - thirdparty/git.git/commitdiff
hash: add a function to look up hash algo structs
authorbrian m. carlson <sandals@crustytoothpaste.net>
Mon, 17 Nov 2025 22:16:12 +0000 (22:16 +0000)
committerJunio C Hamano <gitster@pobox.com>
Mon, 17 Nov 2025 22:24:14 +0000 (14:24 -0800)
In C, it's easy for us to look up a hash algorithm structure by its
offset by simply indexing the hash_algos array.  However, in Rust, we
sometimes need a pointer to pass to a C function, but we have our own
hash algorithm abstraction.

To get one from the other, let's provide a simple function that looks up
the C structure from the offset and expose it in Rust.

Signed-off-by: brian m. carlson <sandals@crustytoothpaste.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
hash.c
hash.h
src/hash.rs

diff --git a/hash.c b/hash.c
index 81b4f87027ebd2b01e134a48d98af2e350bf52eb..97fd473607a809efae2144d506c8829950b6e8c4 100644 (file)
--- a/hash.c
+++ b/hash.c
@@ -241,6 +241,13 @@ const char *empty_tree_oid_hex(const struct git_hash_algo *algop)
        return oid_to_hex_r(buf, algop->empty_tree);
 }
 
+const struct git_hash_algo *hash_algo_ptr_by_number(uint32_t algo)
+{
+       if (algo >= GIT_HASH_NALGOS)
+               return NULL;
+       return &hash_algos[algo];
+}
+
 uint32_t hash_algo_by_name(const char *name)
 {
        if (!name)
diff --git a/hash.h b/hash.h
index 99c9c2a0a8624c3c0fadefc5b75c42ed76e753eb..709d7585a51e67b20065c1444d3de93cc78239c0 100644 (file)
--- a/hash.h
+++ b/hash.h
@@ -340,6 +340,7 @@ static inline void git_hash_final_oid(struct object_id *oid, struct git_hash_ctx
        ctx->algop->final_oid_fn(oid, ctx);
 }
 
+const struct git_hash_algo *hash_algo_ptr_by_number(uint32_t algo);
 /*
  * Return a GIT_HASH_* constant based on the name.  Returns GIT_HASH_UNKNOWN if
  * the name doesn't match a known algorithm.
index 0ec0ab0490103d3053cd5b706dc006a05edc2a31..70bb8095e845515edde7084d149ec135f8c6faaa 100644 (file)
@@ -12,6 +12,7 @@
 
 use std::error::Error;
 use std::fmt::{self, Debug, Display};
+use std::os::raw::c_void;
 
 pub const GIT_MAX_RAWSZ: usize = 32;
 
@@ -177,4 +178,17 @@ impl HashAlgorithm {
             HashAlgorithm::SHA256 => &Self::SHA256_NULL_OID,
         }
     }
+
+    /// A pointer to the C `struct git_hash_algo` for interoperability with C.
+    pub fn hash_algo_ptr(self) -> *const c_void {
+        unsafe { c::hash_algo_ptr_by_number(self as u32) }
+    }
+}
+
+pub mod c {
+    use std::os::raw::c_void;
+
+    extern "C" {
+        pub fn hash_algo_ptr_by_number(n: u32) -> *const c_void;
+    }
 }