paholg / typenum

Compile time numbers in Rust.
https://crates.io/crates/typenum
Other
518 stars 46 forks source link

Add a type-level equivalent for `div_ceil`? #215

Open newpavlov opened 1 week ago

newpavlov commented 1 week ago

This can be emulated by calculating (N + M - 1) / M, but it results in bloated where blocks which obscure the original intention.

kgullion commented 1 week ago
use core::ops::{Add, Div, Sub};
use typenum::op;

pub type DivCeil<X, Y> = <X as DivCeiling<Y>>::Output;
pub trait DivCeiling<Denom> {
    type Output;
}
impl<X: Integer, Y: Integer + NonZero> DivCeiling<Y> for X
where
    X: Add<Y, Output: Sub<U1, Output: Div<Y>>>,
{
    type Output = op!((X + Y - U1) / Y);
}

now you should be able to use just DivCeiling as your bounds:

trait Example<Y> {
    type Output;
}
impl<X: DivCeiling<Y>, Y> Example<Y> for X {
    type Output = DivCeil<X, Y>;
}