lab.nexedi.com/kirr/go123@v0.0.0-20240207185015-8299741fa871/xmath/math19.go (about) 1 // Copyright (C) 2017-2019 Nexedi SA and Contributors. 2 // Kirill Smelkov <kirr@nexedi.com> 3 // 4 // This program is free software: you can Use, Study, Modify and Redistribute 5 // it under the terms of the GNU General Public License version 3, or (at your 6 // option) any later version, as published by the Free Software Foundation. 7 // 8 // You can also Link and Combine this program with other software covered by 9 // the terms of any of the Free Software licenses or any of the Open Source 10 // Initiative approved licenses and Convey the resulting work. Corresponding 11 // source of such a combination shall include the source code for all other 12 // software used. 13 // 14 // This program is distributed WITHOUT ANY WARRANTY; without even the implied 15 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 16 // 17 // See COPYING file for full licensing terms. 18 // See https://www.nexedi.com/licensing for rationale and options. 19 20 //go:build go1.9 21 // +build go1.9 22 23 // Package xmath provides addons to std math package. 24 package xmath 25 26 import ( 27 "math/bits" 28 ) 29 30 // CeilPow2 returns minimal y >= x, such that y = 2^i. 31 func CeilPow2(x uint64) uint64 { 32 switch bits.OnesCount64(x) { 33 case 0, 1: 34 return x // either 0 or 2^i already 35 default: 36 return 1 << uint(bits.Len64(x)) 37 } 38 } 39 40 // CeilLog2 returns minimal i: 2^i >= x. 41 func CeilLog2(x uint64) int { 42 switch bits.OnesCount64(x) { 43 case 0: 44 return 0 45 case 1: 46 return bits.Len64(x) - 1 47 default: 48 return bits.Len64(x) 49 } 50 } 51 52 // FloorLog2 returns maximal i: 2^i <= x. 53 // 54 // x=0 gives -> -1. 55 func FloorLog2(x uint64) int { 56 switch bits.OnesCount64(x) { 57 case 0: 58 return -1 59 default: 60 return bits.Len64(x) - 1 61 } 62 } 63 64 65 // XXX if needed: NextPow2 (y > x, such that y = 2^i) is 66 // 1 << bits.Len64(x)