Skip to content

Commit 3e2a29c

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 a49ea4b commit 3e2a29c

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

hash.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,11 @@ 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_offset(uint32_t algo)
245+
{
246+
return &hash_algos[algo];
247+
}
248+
244249
uint32_t hash_algo_by_name(const char *name)
245250
{
246251
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_offset(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: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
// You should have received a copy of the GNU General Public License along
1111
// with this program; if not, see <https://www.gnu.org/licenses/>.
1212

13+
use std::os::raw::c_void;
14+
1315
pub const GIT_MAX_RAWSZ: usize = 32;
1416

1517
/// A binary object ID.
@@ -160,4 +162,17 @@ impl HashAlgorithm {
160162
HashAlgorithm::SHA256 => &Self::SHA256_NULL_OID,
161163
}
162164
}
165+
166+
/// A pointer to the C `struct git_hash_algo` for interoperability with C.
167+
pub fn hash_algo_ptr(self) -> *const c_void {
168+
unsafe { c::hash_algo_ptr_by_offset(self as u32) }
169+
}
170+
}
171+
172+
pub mod c {
173+
use std::os::raw::c_void;
174+
175+
extern "C" {
176+
pub fn hash_algo_ptr_by_offset(n: u32) -> *const c_void;
177+
}
163178
}

0 commit comments

Comments
 (0)