|
| 1 | +- Start Date: 2023-08-07 |
| 2 | +- RFC PR: [amaranth-lang/rfcs#17](https://github.com/amaranth-lang/rfcs/pull/17) |
| 3 | +- Amaranth Issue: None |
| 4 | + |
| 5 | +# Remove `log2_int` |
| 6 | + |
| 7 | +## Summary |
| 8 | +[summary]: #summary |
| 9 | + |
| 10 | +Remove the `log2_int(n, need_pow2=True)` function. |
| 11 | + |
| 12 | +## Motivation |
| 13 | +[motivation]: #motivation |
| 14 | + |
| 15 | +`log2_int` is a helper function that was copied from Migen in the early days of Amaranth. |
| 16 | + |
| 17 | +It behaves like so: |
| 18 | + |
| 19 | +* `n` must be an integer, and a power-of-2 unless `need_pow2` is `False`; |
| 20 | +* if `n == 0`, it returns `0`; |
| 21 | +* if `n != 0`, it returns `(n - 1).bit_length()`. |
| 22 | + |
| 23 | +Its differences with the `math.log2` function are summarized in the following table: |
| 24 | + |
| 25 | +| `n` | `math.log2(n)` | `log2_int(n)` | `log2_int(n, need_pow2=False)` | |
| 26 | +| ----- | ---------------- | ---------------- | ------------------------------ | |
| 27 | +| `4` | `2.0` | `2` | `2` | |
| 28 | +| `3` | `1.58496250...` | `ValueError` | `2` | |
| 29 | +| `0.5` | `-1.0` | `AttributeError` | `AttributeError` | |
| 30 | +| `0` | `ValueError` | `0` | `0` | |
| 31 | +| `-1` | `ValueError` | `ValueError` | `2` | |
| 32 | + |
| 33 | + |
| 34 | +In practice, developers seem to use `log2_int` as a variant of `math.log2` whose result is rounded-up to an integer, in order to know how many bits are needed to represent a number. |
| 35 | + |
| 36 | +However, the fact that it transparently accepts `0` and rejects non-integer values such as `0.5` makes it inadequate for use cases outside bit manipulation. |
| 37 | + |
| 38 | +## Explanation |
| 39 | +[explanation]: #explanation |
| 40 | + |
| 41 | +The `log2_int` function is deprecated and removed in favor of `math.log2`. |
| 42 | + |
| 43 | +The following suggestions are made to help migration: |
| 44 | + |
| 45 | +* `int(log2(n))` can be used instead of `log2_int(n)`; |
| 46 | +* `ceil(log2(n))` can be used instead of `log2_int(n, need_pow2=False)`; |
| 47 | +* if `n == 0` or `n < 0` are valid, the caller must handle them explicitly. |
| 48 | + |
| 49 | +## Drawbacks |
| 50 | +[drawbacks]: #drawbacks |
| 51 | + |
| 52 | +This is a breaking change. |
| 53 | + |
| 54 | +## Rationale and alternatives |
| 55 | +[rationale-and-alternatives]: #rationale-and-alternatives |
| 56 | + |
| 57 | +We could keep `log2_int`. The author believes that the suggested replacements are more effective at communicating intent. |
| 58 | + |
| 59 | +## Prior art |
| 60 | +[prior-art]: #prior-art |
| 61 | + |
| 62 | +None. |
| 63 | + |
| 64 | +## Unresolved questions |
| 65 | +[unresolved-questions]: #unresolved-questions |
| 66 | + |
| 67 | +None. |
| 68 | + |
| 69 | +## Future possibilities |
| 70 | +[future-possibilities]: #future-possibilities |
| 71 | + |
| 72 | +None. |
0 commit comments