csum-file: introduce checksum_valid()

Introduce a new function which checks the validity of a file's trailing
checksum. This is similar to hashfd_check(), but different since it is
intended to be used by callers who aren't writing the same data (like
`git index-pack --verify`), but who instead want to validate the
integrity of data that they are reading.

Rewrite the first of two callers which could benefit from this new
function in pack-check.c. Subsequent callers will be added in the
following patches.

Helped-by: Jeff King <peff@peff.net>
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Taylor Blau <me@ttaylorr.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Taylor Blau
2021-06-23 14:39:07 -04:00
committed by Junio C Hamano
parent ebf3c04b26
commit f9221e2cf5
3 changed files with 20 additions and 10 deletions

View File

@ -187,3 +187,19 @@ uint32_t crc32_end(struct hashfile *f)
f->do_crc = 0;
return f->crc32;
}
int hashfile_checksum_valid(const unsigned char *data, size_t total_len)
{
unsigned char got[GIT_MAX_RAWSZ];
git_hash_ctx ctx;
size_t data_len = total_len - the_hash_algo->rawsz;
if (total_len < the_hash_algo->rawsz)
return 0; /* say "too short"? */
the_hash_algo->init_fn(&ctx);
the_hash_algo->update_fn(&ctx, data, data_len);
the_hash_algo->final_fn(got, &ctx);
return hasheq(got, data + data_len);
}