oxedyne/fe2o3/fe2o3_num/src/int.rs
1.6 KiB, 6 runs
created by r1870400018:633, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | use oxedyne_fe2o3_core::prelude::*; |
| 2 | |
| 3 | use std::string; |
| 4 | |
| 5 | pub trait PrimInt: Sized + string::ToString { |
| 6 | fn is_neg(self) -> bool; |
| 7 | } |
| 8 | |
| 9 | impl PrimInt for u8 { |
| 10 | fn is_neg(self) -> bool { false } |
| 11 | } |
| 12 | |
| 13 | impl PrimInt for i8 { |
| 14 | fn is_neg(self) -> bool { self < 0 } |
| 15 | } |
| 16 | |
| 17 | impl PrimInt for u16 { |
| 18 | fn is_neg(self) -> bool { false } |
| 19 | } |
| 20 | |
| 21 | impl PrimInt for i16 { |
| 22 | fn is_neg(self) -> bool { self < 0 } |
| 23 | } |
| 24 | |
| 25 | impl PrimInt for u32 { |
| 26 | fn is_neg(self) -> bool { false } |
| 27 | } |
| 28 | |
| 29 | impl PrimInt for i32 { |
| 30 | fn is_neg(self) -> bool { self < 0 } |
| 31 | } |
| 32 | |
| 33 | impl PrimInt for u64 { |
| 34 | fn is_neg(self) -> bool { false } |
| 35 | } |
| 36 | |
| 37 | impl PrimInt for i64 { |
| 38 | fn is_neg(self) -> bool { self < 0 } |
| 39 | } |
| 40 | |
| 41 | impl PrimInt for usize { |
| 42 | fn is_neg(self) -> bool { false } |
| 43 | } |
| 44 | |
| 45 | impl PrimInt for isize { |
| 46 | fn is_neg(self) -> bool { self < 0 } |
| 47 | } |
| 48 | |
| 49 | pub trait Signed {} |
| 50 | pub trait Unsigned {} |
| 51 | |
| 52 | /// Fast `usize` ceiling division. |
| 53 | /// Credit: https://stackoverflow.com/questions/2745074/fast-ceiling-of-an-integer-division-in-c-c |
| 54 | pub fn usize_ceil_div(dividend: usize, divisor: usize) -> Outcome<usize> { |
| 55 | if divisor == 0 { |
| 56 | Err(err!( |
| 57 | "Attempt to divide {} by {}, latter cannot be zero", |
| 58 | dividend, divisor; |
| 59 | Numeric, Input, Invalid)) |
| 60 | } else if dividend == 0 { |
| 61 | Ok(0) |
| 62 | } else { |
| 63 | Ok(1 + ((dividend - 1) / divisor)) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | #[cfg(test)] |
| 68 | mod tests { |
| 69 | use super::*; |
| 70 | |
| 71 | #[test] |
| 72 | fn test_ceiling_div_01() { |
| 73 | for x in 1..1000 { |
| 74 | for y in 1..x { |
| 75 | let xf = x as f64; |
| 76 | let yf = y as f64; |
| 77 | let q = (xf/yf).ceil() as usize; |
| 78 | assert_eq!(q, usize_ceil_div(x, y).unwrap()); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |