authorgravatar for marc@tiehu.isMarc Tiehuis <marc@tiehu.is> 2018-01-13 13:23:12+13:00
committergravatar for marc@tiehu.isMarc Tiehuis <marc@tiehu.is> 2018-01-13 13:23:12+13:00
log304f6f1d0165f9bdacb7d80479298ca0acff1c27
tree09aa4690e46a3d0ca35aaf940f2fae609f4127b2
parent3268276b58d8b65cb295b738d7c14174005bd84e

Add integer rotation functions


1 files changed, 39 insertions(+), 0 deletions(-)

std/math/index.zig+39
...@@ -267,6 +267,45 @@ test "math.shr" {...@@ -267,6 +267,45 @@ test "math.shr" {
267 assert(shr(u8, 0b11111111, isize(-2)) == 0b11111100);267 assert(shr(u8, 0b11111111, isize(-2)) == 0b11111100);
268}268}
269269
270/// Rotates right. Only unsigned values can be rotated.
271/// Negative shift values results in shift modulo the bit count.
272pub fn rotr(comptime T: type, x: T, r: var) -> T {
273 if (T.is_signed) {
274 @compileError("cannot rotate signed integer");
275 } else {
276 const ar = @mod(r, T.bit_count);
277 return shr(T, x, ar) | shl(T, x, T.bit_count - ar);
278 }
279}
280
281test "math.rotr" {
282 assert(rotr(u8, 0b00000001, usize(0)) == 0b00000001);
283 assert(rotr(u8, 0b00000001, usize(9)) == 0b10000000);
284 assert(rotr(u8, 0b00000001, usize(8)) == 0b00000001);
285 assert(rotr(u8, 0b00000001, usize(4)) == 0b00010000);
286 assert(rotr(u8, 0b00000001, isize(-1)) == 0b00000010);
287}
288
289/// Rotates left. Only unsigned values can be rotated.
290/// Negative shift values results in shift modulo the bit count.
291pub fn rotl(comptime T: type, x: T, r: var) -> T {
292 if (T.is_signed) {
293 @compileError("cannot rotate signed integer");
294 } else {
295 const ar = @mod(r, T.bit_count);
296 return shl(T, x, ar) | shr(T, x, T.bit_count - ar);
297 }
298}
299
300test "math.rotl" {
301 assert(rotl(u8, 0b00000001, usize(0)) == 0b00000001);
302 assert(rotl(u8, 0b00000001, usize(9)) == 0b00000010);
303 assert(rotl(u8, 0b00000001, usize(8)) == 0b00000001);
304 assert(rotl(u8, 0b00000001, usize(4)) == 0b00010000);
305 assert(rotl(u8, 0b00000001, isize(-1)) == 0b10000000);
306}
307
308
270pub fn Log2Int(comptime T: type) -> type {309pub fn Log2Int(comptime T: type) -> type {
271 return @IntType(false, log2(T.bit_count));310 return @IntType(false, log2(T.bit_count));
272}311}