pub struct Bits<V: IntoBits> { /* private fields */ }
Expand description

该结构体可以通过 0x10u32.bits(0x01) 来构造

use bits::BitsOps;
use bits::IntoBits;
assert_eq!(0u8.bits(0).set(), 0x01);
assert_eq!(0u8.bits(1).set(), 0x02);
assert_eq!(0u8.bits(4..=7).set(), 0xf0);
assert_eq!(0xffu8.bits(4..=7).clr(), 0x0f);
assert_eq!(0xffu8.bits(3).revert(), 0xf7);
assert_eq!(0xffu8.bits(4..=7).revert(), 0x0f);
assert_eq!(0u8.bits(4..=7).write(0x10), 0x0);
// 只会写入 value 的相应的 bit 位。低 4 bit 并不会被修改。
assert_eq!(0u8.bits(4..=7).write(0x12), 0x20);
assert_eq!(0x12u8.bits(4..=7).read(), 0x1);
assert_eq!(0xf0u8.bits(4..=7).is_set(), true);
assert_eq!(0x70u8.bits(4..=7).is_set(), false);
assert_eq!(0x70u8.bits(4..=7).is_clr(), false);
assert_eq!(0x70u8.bits(0..=3).is_clr(), true);

单独构造该结构体主要是为了将 bit range 和要写入的值分开,这两者的类型可能会一样,在无 IDE 类型提示的情况下导致调用顺序颠倒: 0u8.bits_write(5, 1) 无法区分哪一个是 range,哪一个是要写入的值。

当然也可以通过 0u8.bits_set(5); 来避免,但 bits_write 的存在依旧会暴露风险。

综上选择单独构造 Bits 结构体。

关于溢出

只尽可能的使输出的值符合预期: 0u8.bits(0..=10).set() == 0xff 0xffu8.bits(3..2).clr() == 0xff 当然这两个代码片段在非 release 编译下会导致溢出 panic(rust 自带的溢出检查)。

Trait Implementations

运行效率和标准库(编译器内部提供的)不相上下。

运行效率和标准库(编译器内部提供的)不相上下。

运行效率和标准库(编译器内部提供的)不相上下。

运行效率和标准库(编译器内部提供的)不相上下。

运行效率和标准库(编译器内部提供的)不相上下。

运行效率和标准库(编译器内部提供的)不相上下。

The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.