Small Rust library for calculating greatest common divisor crates.io/crates/gcd
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Get rid of external dependencies (#10)

authored by

pacak and committed by
GitHub
da9073a6 ab61dfd0

+23 -15
-1
Cargo.toml
··· 10 10 categories = ["algorithms"] 11 11 12 12 [dependencies] 13 - paste = "1" 14 13 15 14 [dev-dependencies] 16 15 criterion = "0.3"
+23 -14
src/lib.rs
··· 29 29 } 30 30 31 31 macro_rules! gcd_impl { 32 - ($($T:ty),*) => {$( 32 + ($(($T:ty) $binary:ident $euclid:ident),*) => {$( 33 33 34 - paste::paste! { 35 - #[doc = "Const binary GCD implementation for `" $T "`."] 36 - pub const fn [<binary_ $T>](mut u: $T, mut v: $T) -> $T 34 + 35 + #[doc = concat!("Const binary GCD implementation for `", stringify!($T), "`.")] 36 + pub const fn $binary(mut u: $T, mut v: $T) -> $T 37 37 { 38 38 if u == 0 { return v; } 39 39 if v == 0 { return u; } ··· 46 46 loop { 47 47 v >>= v.trailing_zeros(); 48 48 49 + #[allow(clippy::manual_swap)] 49 50 if u > v { 50 51 // mem::swap(&mut u, &mut v); 51 52 let temp = u; ··· 61 62 u << shift 62 63 } 63 64 64 - #[doc = "Const euclid GCD implementation for `" $T "`."] 65 - pub const fn [<euclid_ $T>]( a: $T, b: $T) -> $T 65 + #[doc = concat!("Const euclid GCD implementation for `", stringify!($T), "`.")] 66 + pub const fn $euclid( a: $T, b: $T) -> $T 66 67 { 67 68 // variable names based off euclidean division equation: a = b · q + r 68 69 let (mut a, mut b) = if a > b { ··· 71 72 (b, a) 72 73 }; 73 74 75 + #[allow(clippy::manual_swap)] 74 76 while b != 0 { 75 77 // mem::swap(&mut a, &mut b); 76 78 let temp = a; ··· 82 84 83 85 a 84 86 } 85 - } 87 + 86 88 87 89 88 90 impl Gcd for $T { ··· 91 93 } 92 94 93 95 fn gcd_binary(self, v: $T) -> $T { 94 - paste::paste! { 95 - [<binary_ $T>](self, v) 96 - } 96 + 97 + $binary(self, v) 98 + 97 99 } 98 100 99 101 fn gcd_euclid(self, other: $T) -> $T { 100 - paste::paste! { 101 - [<euclid_ $T>](self, other) 102 - } 102 + 103 + $euclid(self, other) 104 + 103 105 } 104 106 } 105 107 )*}; 106 108 } 107 109 108 - gcd_impl! { u8, u16, u32, u64, u128, usize } 110 + gcd_impl! { 111 + (u8) binary_u8 euclid_u8, 112 + (u16) binary_u16 euclid_u16, 113 + (u32) binary_u32 euclid_u32, 114 + (u64) binary_u64 euclid_u64, 115 + (u128) binary_u128 euclid_u128, 116 + (usize) binary_usize euclid_usize 117 + } 109 118 110 119 #[cfg(test)] 111 120 mod test {