count-digits
CountDigits is a no-std trait with functions to determine the lengths of integers in various number bases.
It is implemented for all primitive integer types and all non-zero integer types.
Examples
use CountDigits;
// Base 2
assert_eq!;
assert_eq!;
// Base 8
assert_eq!;
assert_eq!;
// Base 10
assert_eq!;
assert_eq!;
// Base 16
assert_eq!;
assert_eq!;
Functions That Return u32
Named functions for which the radix is a power of two return u32 for compatibility with Rust's bitwise functions and constants.
assert_eq!;
assert_eq!;
assert_eq!;
Functions That Return usize
Functions that are not inherently meaningful in a bitwise context return usize for compatibility with Rust's formatting functions and macros.
let numbers = ;
let max_digits = numbers
.iter
.map
.max
.unwrap;
for n in numbers
When formatting binary, octal, or hexadecimal numbers, the count_digits_radix(2 | 8 | 16) and checked_count_digits_radix(2 | 8 | 16) functions can be used in place of count_bits(), count_octal_digits(), and count_hex_digits() to retrieve the desired count directly as a usize.
let numbers = ;
let max_bits = numbers
.iter
.map
.max
.unwrap;
for n in numbers
Invalid Radix Values
Values passed to count_digits_radix() and checked_count_digits_radix() must be greater than or equal to 2.
- count_digits_radix() will panic if given an invalid radix.
for n in 0..100
- checked_count_digits_radix() will return None if given an invalid radix.
for n in 0..100
Negative Numbers
Since negative numbers represented in base 10 are displayed with a negative sign, the base-10 digit count of a positive number will be equal to the base-10 digit count of the number's negated value, assuming no wrapping occurs.
Note that the negative sign itself is not included in the count because the negative sign is not a digit.
assert_eq!;
The digit counts of negative numbers represented in other bases reflect the twos-complement representation, and the digit count of a positive number will not be the same as the count of its negated value.
for radix in 2..=16
This is consistent with Rust's display format.
// Base 2
assert_eq!;
assert_eq!;
// Base 8
assert_eq!;
assert_eq!;
// Base 10
assert_eq!;
assert_eq!;
// Base 16
assert_eq!;
assert_eq!;
Benchmarks
License: MIT