Function rotl [src]

Rotates left. Only unsigned values can be rotated. Negative shift values result in shift modulo the bit count.

Prototype

pub fn rotl(comptime T: type, x: T, r: anytype) T

Parameters

T: typex: T

Example

test rotl { try testing.expect(rotl(u0, 0b0, @as(usize, 3)) == 0b0); try testing.expect(rotl(u5, 0b00001, @as(usize, 0)) == 0b00001); try testing.expect(rotl(u6, 0b000001, @as(usize, 7)) == 0b000010); try testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001); try testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010); try testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001); try testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000); try testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000); try testing.expect(rotl(u12, 0o7777, 1) == 0o7777); try testing.expect(rotl(@Vector(1, u32), @Vector(1, u32){1 << 31}, @as(usize, 1))[0] == 1); try testing.expect(rotl(@Vector(1, u32), @Vector(1, u32){1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30); }

Source

pub fn rotl(comptime T: type, x: T, r: anytype) T { if (@typeInfo(T) == .vector) { const C = @typeInfo(T).vector.child; if (C == u0) return 0; if (@typeInfo(C).int.signedness == .signed) { @compileError("cannot rotate signed integers"); } const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits)); return (x << @splat(ar)) | (x >> @splat(1 +% ~ar)); } else if (@typeInfo(T).int.signedness == .signed) { @compileError("cannot rotate signed integer"); } else { if (T == u0) return 0; if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) { const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits)); return x << ar | x >> 1 +% ~ar; } else { const ar = @mod(r, @typeInfo(T).int.bits); return shl(T, x, ar) | shr(T, x, @typeInfo(T).int.bits - ar); } } }