hash: add a function to look up hash algo structs
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>
brian m. carlson committed
Feb 7, 2026 at 20:04 UTC
9005b5bb72df521670db03eefeafe53c0a81f9a5
3 files changed
+22
hash.c
+7
@@ -241,6 +241,13 @@ const char *empty_tree_oid_hex(const struct git_hash_algo *algop)
241
return oid_to_hex_r(buf, algop->empty_tree);
242
}
243
244
+const struct git_hash_algo *hash_algo_ptr_by_number(uint32_t algo)
245
+{
246
+ if (algo >= GIT_HASH_NALGOS)
247
+ return NULL;
248
+ return &hash_algos[algo];
249
+}
250
+
251
uint32_t hash_algo_by_name(const char *name)
252
{
253
if (!name)
hash.h
+1
@@ -340,6 +340,7 @@ static inline void git_hash_final_oid(struct object_id *oid, struct git_hash_ctx
340
ctx->algop->final_oid_fn(oid, ctx);
341
}
342
343
+const struct git_hash_algo *hash_algo_ptr_by_number(uint32_t algo);
344
/*
345
* Return a GIT_HASH_* constant based on the name. Returns GIT_HASH_UNKNOWN if
346
* the name doesn't match a known algorithm.
src/hash.rs
+14
@@ -12,6 +12,7 @@
12
13
use std::error::Error;
14
use std::fmt::{self, Debug, Display};
15
+use std::os::raw::c_void;
16
17
pub const GIT_MAX_RAWSZ: usize = 32;
18
@@ -177,4 +178,17 @@ impl HashAlgorithm {
178
HashAlgorithm::SHA256 => &Self::SHA256_NULL_OID,
179
}
180
}
181
+
182
+ /// A pointer to the C `struct git_hash_algo` for interoperability with C.
183
+ pub fn hash_algo_ptr(self) -> *const c_void {
184
+ unsafe { c::hash_algo_ptr_by_number(self as u32) }
185
+ }
186
+}
187
+
188
+pub mod c {
189
+ use std::os::raw::c_void;
190
+
191
+ extern "C" {
192
+ pub fn hash_algo_ptr_by_number(n: u32) -> *const c_void;
193
+ }
194
}