Any way to make ceil() work in a const context?

Hi,
I would like to calculate the length of a non padded Base64 value:

const LENGTH_SESSION: usize = 128;
const LENGTH_SESSION_B64: usize = (4_f64 * (LENGTH_SESSION as f64 / 3.0_f64) as f64).ceil() as usize;

Now, the ceil() (or round, or floor..) function doesn't compile in a const context.
It's easy enough to manually calculate on a calculator, but is there a technique to let the compiler calculate it anyway at compile time?

Thanks!

You can't force a non-const fn to be called in a const context, if that's what you are asking for.


You shouldn't be doing this via floating-point numbers anyway (you'll get wrong results as soon as the numerator exceeds 2^53/4). The standard way to divide x by N while rounding up is to compute (x + N - 1) / N as an integer (i.e., by truncating).

const LENGTH_SESSION_B64: usize = (4 * LENGTH_SESSION + 2) / 3;
6 Likes

Great, thanks :+1:

Rust can do better than that: (4 * LENGTH_SESSION).div_ceil(3)

1 Like

that's not yet stable

div_ceil is stable since Rust 1.73.

(However, div_floor is not yet stable.)

1 Like

Hmm, I swear I saw the "nightly-only experimental API" annotation on that function.

Anyway, it's good to know the x + N - 1 trick in case you encounter a type that doesn't have a pre-baked method. It's trivial, and it's an idiom any experienced programmer will recognize.

div_ceil has been stabilized for unsigned integers, but not for signed integers. I suspect you did what I did, and searched for it, then clicked on isize not usize in error.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.