Skip to content

Commit eae08d8

Browse files
bk2204gitster
authored andcommitted
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>
1 parent 76ee085 commit eae08d8

3 files changed

Lines changed: 22 additions & 0 deletions

File tree

hash.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,13 @@ const char *empty_tree_oid_hex(const struct git_hash_algo *algop)
241241
return oid_to_hex_r(buf, algop->empty_tree);
242242
}
243243

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+
244251
uint32_t hash_algo_by_name(const char *name)
245252
{
246253
if (!name)

hash.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ static inline void git_hash_final_oid(struct object_id *oid, struct git_hash_ctx
340340
ctx->algop->final_oid_fn(oid, ctx);
341341
}
342342

343+
const struct git_hash_algo *hash_algo_ptr_by_number(uint32_t algo);
343344
/*
344345
* Return a GIT_HASH_* constant based on the name. Returns GIT_HASH_UNKNOWN if
345346
* the name doesn't match a known algorithm.

src/hash.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
use std::error::Error;
1414
use std::fmt::{self, Debug, Display};
15+
use std::os::raw::c_void;
1516

1617
pub const GIT_MAX_RAWSZ: usize = 32;
1718

@@ -177,4 +178,17 @@ impl HashAlgorithm {
177178
HashAlgorithm::SHA256 => &Self::SHA256_NULL_OID,
178179
}
179180
}
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+
}
180194
}

0 commit comments

Comments
 (0)