Assessment reports>Barretenberg Bigfield>Discussion>Handling of too large ranges in uint256_t::slice

Handling of too large ranges in uint256_t::slice

The function uint256_t::slice is implemented as follows:

/**
 * Viewing `this` uint256_t as a bit string, and counting bits from 0, slices a substring.
 * @returns the uint256_t equal to the substring of bits from (and including) the `start`-th bit, to (but excluding) the
 * `end`-th bit of `this`.
 */
constexpr uint256_t uint256_t::slice(const uint64_t start, const uint64_t end) const
{
    const uint64_t range = end - start;
    const uint256_t mask = (range == 256) ? -uint256_t(1) : (uint256_t(1) << range) - 1;
    return ((*this) >> start) & mask;
}

Note that this function works correctly even when end is bigger than 256 (essentially, the 256-bit value is extended by zeros for more significant bits). However, the implementation will not handle ranges bigger than 256 correctly. To prevent incorrect usage, we recommend to assert that range <= 256, or alternatively document that the caller must ensure this.

Zellic © 2025Back to top ↑