hash: make git_hash_discard() idempotent

You must always either finalize or discard a hash context to release any
resources, but you must call only one such function. This creates extra
work for some callers, since their cleanup code paths need to know
whether they got there via their happy path (and the finalization
happened) or due to an error (in which case they need to discard).

Let's add an "active" flag that turns a redundant discard into a noop.
That lets you safely do this:

    git_hash_init(&ctx, algo);
    ...
    if (some_error)
            goto out;
    ...
    git_hash_final(result, &ctx);

  out:
    git_hash_discard(&ctx);

This should avoid future errors, and will also let us simplify a few
existing callers (in future patches).

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Jeff King
2026-07-07 23:52:57 -04:00
committed by Junio C Hamano
parent 90a55e3a51
commit 2c51615d3f
2 changed files with 7 additions and 0 deletions

6
hash.c
View File

@@ -285,6 +285,7 @@ void git_hash_free(struct git_hash_ctx *ctx)
void git_hash_init(struct git_hash_ctx *ctx, const struct git_hash_algo *algop)
{
algop->init_fn(ctx);
ctx->active = true;
}
void git_hash_clone(struct git_hash_ctx *dst, const struct git_hash_ctx *src)
@@ -300,16 +301,21 @@ void git_hash_update(struct git_hash_ctx *ctx, const void *in, size_t len)
void git_hash_final(unsigned char *hash, struct git_hash_ctx *ctx)
{
ctx->algop->final_fn(hash, ctx);
ctx->active = false;
}
void git_hash_final_oid(struct object_id *oid, struct git_hash_ctx *ctx)
{
ctx->algop->final_oid_fn(oid, ctx);
ctx->active = false;
}
void git_hash_discard(struct git_hash_ctx *ctx)
{
if (!ctx->active)
return;
ctx->algop->discard_fn(ctx);
ctx->active = false;
}
uint32_t hash_algo_by_name(const char *name)

1
hash.h
View File

@@ -281,6 +281,7 @@ struct git_hash_ctx {
git_SHA_CTX_unsafe sha1_unsafe;
git_SHA256_CTX sha256;
} state;
bool active;
};
typedef void (*git_hash_init_fn)(struct git_hash_ctx *ctx);