3个不稳定版本
0.1.1 | 2023年8月5日 |
---|---|
0.1.0 | 2023年5月12日 |
0.0.0 | 2023年5月7日 |
#1161 in 数据结构
用于 mvbitfield
38KB
573 代码行
bitint
Rust的位整数库。 bitint
类似于原始整数类型,但它们的逻辑宽度以位为单位。
这个crate提供了 UBitint
特性和从 U1
到 U128
的128种类型,实现了它。每种类型封装了可以包含它的最小原始无符号整数类型。与原始类型宽度不同的类型施加了一个有效性约束——值表示在最低有效位中,而高位始终为清零。
演示
// Recommended, but not required.
use bitint::prelude::*;
// Use the bitint! macro to write a bitint literal. Underscores are permitted
// anywhere in a Rust literal and are encouraged for readability.
let seven = bitint!(7_U12);
// Use the #[bitint_literals] attribute macro to write bitint literals anywhere
// inside an item. Here the item is a function, but it can also be useful on an
// impl block or inline module.
# demo();
#[bitint_literals]
fn demo() {
let five = 5_U12;
// Arithmetic ops accept Self or the primitive type and panic or wrap just
// like primitive arithmetic ops.
assert_eq!(five + five, 10_U12);
assert_eq!(five - 1_U12, 4_U12);
assert_eq!(five * 2_U12, 10_U12);
assert_eq!(five / 3_U12, 1_U12);
assert_eq!(five % 3_U12, 2_U12);
// If built with overflow-checks = true, this would panic.
// If built with overflow-checks = false, this would wrap.
// five + U12::MAX
// Checked arithmetic ops.
assert_eq!(five.checked_add(10_U12), Some(15_U12));
assert_eq!(five.checked_add(4095_U12), None);
// Wrapping arithmetic ops.
assert_eq!(five.wrapping_add(10_U12), 15_U12);
assert_eq!(five.wrapping_add(4095_U12), 4_U12);
// Zero-(extra)-cost unchecked arithmetic ops.
#[cfg(feature = "unchecked_math")]
{
// SAFETY: 15 is in range for U12.
assert_eq!(unsafe { five.unchecked_add(10_U12) }, 15_U12);
// This would violate the safety condition and cause undefined behavior.
// unsafe { five.unchecked_add(4095_U12) }
}
// Zero-cost conversion to a primitive type.
assert_eq!(five.to_primitive(), 5);
// Checked constructor.
assert_eq!(U12::new(5), Some(five));
assert_eq!(U12::new(4096), None);
// Masking constructor.
assert_eq!(U12::new_masked(5), five);
assert_eq!(U12::new_masked(13 * 4096 + 5), five);
// Zero-cost unsafe constructor.
// SAFETY: 5 is in range for U12.
assert_eq!(unsafe { U12::new_unchecked(5) }, five);
// This would violate the safety condition and cause undefined behavior.
// unsafe { U12::new_unchecked(65536) }
// Zero-cost safe constructor, only for bitints that are the same width as a
// primitive type.
assert_eq!(U16::from_primitive(1234), 1234_U16);
// String conversions.
assert_eq!(format!("{five}"), "5");
assert_eq!(five.to_string(), "5");
assert_eq!("5".parse::<U12>().unwrap(), 5_U12);
};
crate功能
- unchecked_math - 启用无符号
bitint
类型的unchecked_*
方法。需要nightly Rust编译器。
依赖项
~0.6–1.1MB
~24K SLoC