#power #numbers #integer #power-of-two

binexp

A struct that represents power of two numbers

2 releases

0.1.1 Jul 24, 2023
0.1.0 Jul 18, 2023

#2855 in Rust patterns

MIT license

11KB
200 lines

binexp

CI crates

binexp provides a PowerOfTwo struct that you can create from any valid power of two integer.
You can use PowerOfTwo as a safe way to represent powers of two in your code.

Examples

use std::convert::TryFrom;
use binexp::PowerOfTwo;

assert!(PowerOfTwo::try_from(1).is_ok());
assert!(PowerOfTwo::try_from(2).is_ok());
assert!(PowerOfTwo::try_from(3).is_err());

let four = PowerOfTwo::try_from(4).unwrap();
assert_eq!(four.to_string(), "2^2 (4)");

let eight: PowerOfTwo = 8i8.try_into().unwrap();
assert_eq!(eight.to_string(), "2^3 (8)");

License

This project is licensed under the MIT license.


lib.rs:

A library for working with power of two numbers. Using the PowerOfTwo struct can be useful for validation purposes, when you want to make sure that a number is a power of two. PowerOfTwo implements TryFrom for all integer types, so you can convert any integer into a PowerOfTwo instance.


Examples

use std::convert::TryFrom;
use binexp::PowerOfTwo;

assert!(PowerOfTwo::try_from(1).is_ok());
assert!(PowerOfTwo::try_from(2).is_ok());
assert!(PowerOfTwo::try_from(3).is_err());

let four = PowerOfTwo::try_from(4).unwrap();
assert_eq!(four.to_string(), "2^2 (4)");

let eigth: PowerOfTwo = 8i8.try_into().unwrap();
assert_eq!(eigth.to_string(), "2^3 (8)");

Dependencies

~245–700KB
~16K SLoC