github.com/primecitizens/pcz/std@v0.2.1/core/bits/rotate.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2023 The Prime Citizens 3 // 4 // Copyright 2017 The Go Authors. All rights reserved. 5 // Use of this source code is governed by a BSD-style 6 // license that can be found in the LICENSE file. 7 8 package bits 9 10 import ( 11 "github.com/primecitizens/pcz/std/core/arch" 12 ) 13 14 // RotateLeft returns the value of x rotated left by (k mod UintSize) bits. 15 // To rotate x right by k bits, call RotateLeft(x, -k). 16 // 17 // This function's execution time does not depend on the inputs. 18 func RotateLeft(x uint, k int) uint { 19 if arch.UintBits == 32 { 20 return uint(RotateLeft32(uint32(x), k)) 21 } 22 return uint(RotateLeft64(uint64(x), k)) 23 } 24 25 // RotateLeft8 returns the value of x rotated left by (k mod 8) bits. 26 // To rotate x right by k bits, call RotateLeft8(x, -k). 27 // 28 // This function's execution time does not depend on the inputs. 29 func RotateLeft8(x uint8, k int) uint8 { 30 const n = 8 31 s := uint(k) & (n - 1) 32 return x<<s | x>>(n-s) 33 } 34 35 // RotateLeft16 returns the value of x rotated left by (k mod 16) bits. 36 // To rotate x right by k bits, call RotateLeft16(x, -k). 37 // 38 // This function's execution time does not depend on the inputs. 39 func RotateLeft16(x uint16, k int) uint16 { 40 const n = 16 41 s := uint(k) & (n - 1) 42 return x<<s | x>>(n-s) 43 } 44 45 // RotateLeft32 returns the value of x rotated left by (k mod 32) bits. 46 // To rotate x right by k bits, call RotateLeft32(x, -k). 47 // 48 // This function's execution time does not depend on the inputs. 49 func RotateLeft32(x uint32, k int) uint32 { 50 const n = 32 51 s := uint(k) & (n - 1) 52 return x<<s | x>>(n-s) 53 } 54 55 // RotateLeft64 returns the value of x rotated left by (k mod 64) bits. 56 // To rotate x right by k bits, call RotateLeft64(x, -k). 57 // 58 // This function's execution time does not depend on the inputs. 59 func RotateLeft64(x uint64, k int) uint64 { 60 const n = 64 61 s := uint(k) & (n - 1) 62 return x<<s | x>>(n-s) 63 }