Skip to content

Commit d562d0e

Browse files
wanda-phiwhitequark
authored andcommitted
utils: backport ceil_log2 and exact_log2.
1 parent 8450104 commit d562d0e

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

amaranth/utils.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,28 @@
1-
__all__ = ["log2_int", "bits_for"]
1+
import operator
22

3+
__all__ = ["ceil_log2", "exact_log2", "log2_int", "bits_for"]
4+
5+
6+
def ceil_log2(n):
7+
"""Returns the integer log2 of the smallest power-of-2 greater than or equal to `n`.
8+
9+
Raises a `ValueError` for negative inputs."""
10+
n = operator.index(n)
11+
if n < 0:
12+
raise ValueError("{n} is negative")
13+
if n == 0:
14+
return 0
15+
return (n - 1).bit_length()
16+
17+
18+
def exact_log2(n):
19+
"""Returns the integer log2 of `n`, which must be an exact power of two.
20+
21+
Raises a `ValueError` if `n` is not a power of two."""
22+
n = operator.index(n)
23+
if n <= 0 or (n & (n - 1)):
24+
raise ValueError("{n} is not a power of 2")
25+
return (n - 1).bit_length()
326

427
def log2_int(n, need_pow2=True):
528
if n == 0:

0 commit comments

Comments
 (0)