Skip to content

Instantly share code, notes, and snippets.

@ntalbs
Last active June 15, 2023 22:13
Show Gist options
  • Save ntalbs/5c0627a1524c6857a7d6fff4f7bff3e2 to your computer and use it in GitHub Desktop.
Save ntalbs/5c0627a1524c6857a7d6fff4f7bff3e2 to your computer and use it in GitHub Desktop.
Implementation of count_digit() in Rust
use std::ops::DivAssign;
trait Int {
fn ten() -> Self;
fn zero() -> Self;
}
macro_rules! impl_int_for {
( $( $t:ty ) *) => {
$( impl Int for $t {
fn zero() -> Self { 0 }
fn ten() -> Self { 10 }
} )*
};
}
impl_int_for!(u8 u16 u32 u64 u128 i8 i16 i32 i64 i128);
fn count_digit<T>(mut n: T) -> usize
where
T: Int +PartialOrd + DivAssign + Copy,
{
let zero = T::zero();
if n == zero {
return 1;
}
let ten = T::ten();
let mut count: usize = 0;
loop {
if n == zero {
return count;
}
n /= ten;
count += 1;
}
}
fn main() {
println!("digits: {}", count_digit(12345));
}
#[test]
fn test_1() {
for i in 0..10 {
assert_eq!(count_digit(i), 1);
}
for i in -9..0 {
assert_eq!(count_digit(i), 1);
}
}
#[test]
fn test_2() {
for i in 10..100u128 {
assert_eq!(count_digit(i), 2);
}
for i in -99..-10i128 {
assert_eq!(count_digit(i), 2);
}
}
#[test]
fn test_types() {
assert_eq!(count_digit(101i8), 3);
assert_eq!(count_digit(101u8), 3);
assert_eq!(count_digit(12345u16), 5);
assert_eq!(count_digit(12345i16), 5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment