[math (rust)] Make the functions generic

This commit is contained in:
Ming-Hung Tsai 2021-05-24 12:45:26 +08:00
parent 1198a3f713
commit e336b3a63f
1 changed files with 43 additions and 3 deletions

View File

@ -1,7 +1,47 @@
pub fn div_up(v: usize, divisor: usize) -> usize {
v / divisor + (v % divisor != 0) as usize
use std::cmp::PartialEq;
use std::ops::{Add, Div, Rem};
//-----------------------------------------
pub trait Integer:
Sized + Copy + Add<Output = Self> + Div<Output = Self> + Rem<Output = Self> + PartialEq
{
fn zero() -> Self;
fn one() -> Self;
}
pub fn div_down(v: usize, divisor: usize) -> usize {
pub fn div_up<T: Integer>(v: T, divisor: T) -> T {
if v % divisor != Integer::zero() {
v / divisor + Integer::one()
} else {
v / divisor
}
}
pub fn div_down<T: Integer>(v: T, divisor: T) -> T {
v / divisor
}
//-----------------------------------------
impl Integer for usize {
fn zero() -> Self {
0
}
fn one() -> Self {
1
}
}
impl Integer for u64 {
fn zero() -> Self {
0
}
fn one() -> Self {
1
}
}
//-----------------------------------------