Skip to content

Commit cd56f0b

Browse files
committed
std.math.shl, std.math.shr: support comptime_int and signed integers
1 parent 10bf696 commit cd56f0b

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

lib/std/math.zig

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,7 @@ pub fn shl(comptime T: type, a: T, shift_amt: anytype) T {
602602
if (abs_shift_amt >= @typeInfo(C).int.bits) return @splat(0);
603603
break :blk @as(@Vector(len, Log2Int(C)), @splat(@as(Log2Int(C), @intCast(abs_shift_amt))));
604604
} else {
605-
if (abs_shift_amt >= @typeInfo(T).int.bits) return 0;
605+
if (T != comptime_int and abs_shift_amt >= @typeInfo(T).int.bits) return 0;
606606
break :blk @as(Log2Int(T), @intCast(abs_shift_amt));
607607
}
608608
};
@@ -642,7 +642,7 @@ pub fn shr(comptime T: type, a: T, shift_amt: anytype) T {
642642
if (abs_shift_amt >= @typeInfo(C).int.bits) return @splat(0);
643643
break :blk @as(@Vector(len, Log2Int(C)), @splat(@as(Log2Int(C), @intCast(abs_shift_amt))));
644644
} else {
645-
if (abs_shift_amt >= @typeInfo(T).int.bits) return 0;
645+
if (T != comptime_int and abs_shift_amt >= @typeInfo(T).int.bits) return if (a < 0) -1 else 0;
646646
break :blk @as(Log2Int(T), @intCast(abs_shift_amt));
647647
}
648648
};
@@ -658,6 +658,8 @@ pub fn shr(comptime T: type, a: T, shift_amt: anytype) T {
658658

659659
test shr {
660660
try testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111);
661+
try testing.expect(shr(i8, -1, @as(usize, 3)) == -1);
662+
try testing.expect(shr(i8, -1, @as(usize, 9)) == -1);
661663
try testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0);
662664
try testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0);
663665
try testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100);

0 commit comments

Comments
 (0)