Skip to content

Commit 4eed1b3

Browse files
committed
Add bit shifting built-ins
1 parent bbfe39e commit 4eed1b3

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
synopsis: Add bit shifting built-ins
3+
issues: [13000]
4+
---
5+
6+
Added left and right bit shifting built-ins.

src/libexpr-tests/primops.cc

+10
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,16 @@ namespace nix {
513513
ASSERT_THAT(v, IsIntEq(1));
514514
}
515515

516+
TEST_F(PrimOpTest, bitShiftLeft) {
517+
auto v = eval("builtins.bitShiftLeft 3 2");
518+
ASSERT_THAT(v, IsIntEq(12));
519+
}
520+
521+
TEST_F(PrimOpTest, bitShiftRight) {
522+
auto v = eval("builtins.bitShiftRight 17 3");
523+
ASSERT_THAT(v, IsIntEq(2));
524+
}
525+
516526
TEST_F(PrimOpTest, lessThanFalse) {
517527
auto v = eval("builtins.lessThan 3 1");
518528
ASSERT_THAT(v, IsFalse());

src/libexpr/primops.cc

+34
Original file line numberDiff line numberDiff line change
@@ -4007,6 +4007,40 @@ static RegisterPrimOp primop_bitXor({
40074007
.fun = prim_bitXor,
40084008
});
40094009

4010+
static void prim_bitShiftLeft(EvalState & state, const PosIdx pos, Value * * args, Value & v)
4011+
{
4012+
auto i1 = state.forceInt(*args[0], pos, "while evaluating the first argument passed to builtins.bitShiftLeft");
4013+
auto i2 = state.forceInt(*args[1], pos, "while evaluating the second argument passed to builtins.bitShiftLeft");
4014+
4015+
v.mkInt(i1.value << i2.value);
4016+
}
4017+
4018+
static RegisterPrimOp primop_bitShiftLeft({
4019+
.name = "__bitShiftLeft",
4020+
.args = {"e1", "e2"},
4021+
.doc = R"(
4022+
Return the integer *e1* shifted left by *e2*.
4023+
)",
4024+
.fun = prim_bitShiftLeft,
4025+
});
4026+
4027+
static void prim_bitShiftRight(EvalState & state, const PosIdx pos, Value * * args, Value & v)
4028+
{
4029+
auto i1 = state.forceInt(*args[0], pos, "while evaluating the first argument passed to builtins.bitShiftRight");
4030+
auto i2 = state.forceInt(*args[1], pos, "while evaluating the second argument passed to builtins.bitShiftRight");
4031+
4032+
v.mkInt(i1.value >> i2.value);
4033+
}
4034+
4035+
static RegisterPrimOp primop_bitShiftRight({
4036+
.name = "__bitShiftRight",
4037+
.args = {"e1", "e2"},
4038+
.doc = R"(
4039+
Return the integer *e1* shifted right by *e2*.
4040+
)",
4041+
.fun = prim_bitShiftRight,
4042+
});
4043+
40104044
static void prim_lessThan(EvalState & state, const PosIdx pos, Value * * args, Value & v)
40114045
{
40124046
state.forceValue(*args[0], pos);

0 commit comments

Comments
 (0)