#logarithm #integer #function #optimized #inline #10 #type

no-std ilog

Base 10 and 2 logarithm functions for integer types

7 releases (2 stable)

1.0.1 Mar 7, 2023
0.1.4 Dec 14, 2022

#517 in Algorithms

Download history 132/week @ 2023-12-12 110/week @ 2023-12-19 41/week @ 2023-12-26 189/week @ 2024-01-02 174/week @ 2024-01-09 94/week @ 2024-01-16 91/week @ 2024-01-23 53/week @ 2024-01-30 110/week @ 2024-02-06 66/week @ 2024-02-13 98/week @ 2024-02-20 118/week @ 2024-02-27 125/week @ 2024-03-05 96/week @ 2024-03-12 119/week @ 2024-03-19 117/week @ 2024-03-26

475 downloads per month
Used in 5 crates

MIT license

18KB
199 lines

ilog

crate documentation build status crate

Base 10 and 2 logarithm functions for integer types

The IntLog trait defines the following methods:

fn log10(self) -> usize
fn log2(self) -> usize
fn checked_log10(self) -> Option<usize>
fn checked_log2(self) -> Option<usize>

The log2 and log10 methods are optimized for the integer width and are [inline] since the code remains small enough. They typically use constant tables that are only stored once, even if the methods using them are inlined multiple times.

The checked versions of the methods, checked_log2 and checked_log10, return None if the logarithm is undefined for the parameter value, whereas the unchecked methods mentioned above simply panic or return a wrong value.

Examples

use ilog::IntLog;

let hundred: u32 = 100;
assert_eq!(hundred.log10(), 2);
assert_eq!(u32::log10(99), 1);

let value: u64 = 256;
assert_eq!(value.log2(), 8);
assert_eq!(u64::log2(255), 7);

assert_eq!(u32::checked_log2(63), Some(5));
assert_eq!(0_u32.checked_log2(), None);

Compatibility

The ilog crate is tested for rustc 1.65 and greater, on Windows 64-bit and Linux 64/32-bit platforms.

It doesn't require the std library, and supports 16-, 32- and 64-bit architectures.

Rust versions 1.64 and earlier

Note that in versions 1.64 and earlier, log, log2 and log10 were nightly experimental core::num methods, which were then renamed respectively to ilog, ilog2 and ilog10 in version 1.65 (and are still experimental). This was unknown to the author when the crate was first published.

Should you need to use this crate with earlier versions of rustc, the warnings can be masked with this file directive:

    #![allow(unstable_name_collisions)]

or with this directive in front of the function using the methods:

    #[allow(unstable_name_collisions)]

Releases

RELEASES.md keeps a log of all the releases.

License

Licensed under MIT license.

No runtime deps