Skip to content

Commit

Permalink
primops: add builtins.rebaseHash
Browse files Browse the repository at this point in the history
  • Loading branch information
ShamrockLee committed Jan 29, 2023
1 parent 189261c commit 3cf1f49
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/libexpr/primops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3631,6 +3631,51 @@ static RegisterPrimOp primop_hashString({
.fun = prim_hashString,
});

static void prim_rebaseHash(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto type = state.forceStringNoCtx(*args[0], pos, "while evaluating the first argument passed to builtins.rebaseHash");
std::optional<HashType> ht = parseHashType(type);
if (!ht)
state.debugThrowLastTrace(Error({
.msg = hintfmt("unknown hash type '%1%'", type),
.errPos = state.positions[pos],
}));

auto base = state.forceStringNoCtx(*args[1], pos, "while evaluating the second argument passed to builtins.rebaseHash");
Base hb;
if (base == "sri") {
hb = SRI;
} else if (base == "base16") {
hb = Base16;
} else if (base == "base32") {
hb = Base32;
} else if (base == "base64") {
hb = Base64;
} else {
state.debugThrowLastTrace(Error({
.msg = hintfmt("unknown hash format '%1%'", base),
.errPos = state.positions[pos],
}));
}

PathSet context; // discarded
auto s = state.forceString(*args[2], context, pos, "while evaluating the third argument passed to builtins.rebaseHash");

v.mkString(Hash::parseAny(s, ht).to_string(hb, hb == SRI));
}

static RegisterPrimOp primop_rebaseHash({
.name = "__rebaseHash",
.args = {"type", "base", "s"},
.doc = R"(
Return a *base* representation of the hash *s*. The hash algorithm
specified by *type* must be one of `"md5"`, `"sha1"`, `"sha256"` or
`"sha512"`. The hash format specified by *base* must be one of
`"base16"`, `"base32"`, `"base64"` or `"sri"`.
)",
.fun = prim_rebaseHash,
});

struct RegexCache
{
// TODO use C++20 transparent comparison when available
Expand Down

0 comments on commit 3cf1f49

Please sign in to comment.