1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#![no_std]
#![feature(test)]
#[cfg(target_arch = "x86_64")]
extern crate test;

mod bits_index;
mod bits_iter;
mod bits_ops;

pub mod field;

use core::ops::RangeInclusive;

pub use bits_index::*;
pub use bits_iter::*;
pub use bits_ops::*;

/// 将整型转为 Bits,实际操作由 BitsOps 来实现。
pub trait IntoBits
where
    Self: Sized + Copy,
{
    type Output: BitsOps<Self>;
    fn bits<T: BitIndex>(self, range: T) -> Self::Output;
}

macro_rules! impl_intobits {
    ($($Type:ty) *) => {
        $(impl IntoBits for $Type {
            type Output = Bits<Self>;

            fn bits<T: BitIndex>(self, range:T) -> Bits<Self>{
                let upper = match  <T as BitIndex>::upper(&range) {
                    core::ops::Bound::Unbounded => <$Type>::BITS - 1,
                    core::ops::Bound::Included(v) => *v,
                    core::ops::Bound::Excluded(v) => *v - 1,
                };
                let low = match  <T as BitIndex>::low(&range) {
                    core::ops::Bound::Unbounded => 0,
                    core::ops::Bound::Included(v) => *v,
                    core::ops::Bound::Excluded(v) => *v,
                };

                Bits {
                    value: self,
                    range: low ..= upper
                }
            }
        })*
    };
}

impl_intobits!(u8 u16 u32 u64 u128 usize);

/// 该结构体可以通过 `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 自带的溢出检查)。
pub struct Bits<V: IntoBits> {
    range: RangeInclusive<u32>,
    value: V,
}

impl<V: IntoBits> IntoIterator for Bits<V> {
    type Item = Bit<V>;

    type IntoIter = bits_iter::BitsIter<V>;

    fn into_iter(self) -> Self::IntoIter {
        Self::IntoIter {
            low: *self.range.start(),
            upper: *self.range.end(),
            value: self.value,
        }
    }
}

pub struct Bit<V: IntoBits> {
    value: V,
}
impl<V: IntoBits> Bit<V> {
    #[inline]
    pub fn is_set(&self) -> bool {
        self.value.bits(0).is_set()
    }
    #[inline]
    pub fn is_clr(&self) -> bool {
        !self.is_set()
    }
}

#[cfg(all(test, target_arch = "x86_64"))]
mod tests {
    use test::Bencher;

    use crate::{BitsOps, IntoBits};

    #[test]
    fn bits_ops_test() {
        assert_eq!(0xffu8.bits(..).clr(), 0);
        assert_eq!(0xffu8.bits(..1).clr(), 0xff - 0b1);
        assert_eq!(0xffu8.bits(1..).clr(), 1);
        assert_eq!(0xffu8.bits(1..2).clr(), 0xff - 0b10);
        assert_eq!(0xffu8.bits(1..=2).clr(), 0xff - 0b110);
        assert_eq!(0xffu8.bits(..).msb(), true);
        assert_eq!(0x70u8.bits(4..=5).msb(), true);
        assert_eq!(0x7fu8.bits(..).msb(), false);
        assert_eq!(0x70u8.bits(4..=7).lsb(), true);
    }

    #[test]
    #[should_panic(expected = "overflow")]
    fn bits_ops_test_end_overflow() {
        {
            0xffu8.bits(0..=8).clr()
        };
    }
    #[test]
    #[should_panic(expected = "overflow")]
    fn bits_ops_test_start_overflow() {
        {
            0xffu8.bits(2..=1).clr()
        };
    }
    #[no_mangle]
    fn bits_iterator(data: u64, out: &mut [u8; 64]) {
        for (idx, bit) in data.bits(0..=63).into_iter().enumerate() {
            out[idx] = bit.is_set() as u8;
        }
    }
    #[no_mangle]
    fn plain_loop(data: u64, out: &mut [u8; 64]) {
        let mut mask = 0x1u64;
        let mut idx = 0usize;
        while idx < 64 {
            if data & mask != 0 {
                out[idx] = 1;
            } else {
                out[idx] = 0;
            }
            mask <<= 1;
            idx += 1;
        }
    }

    #[test]
    fn bits_iterator_test() {
        let mut out_iterator = [0u8; 64];
        let mut out_loop = [0u8; 64];
        (0..=0xffff).for_each(|x| {
            bits_iterator(x, &mut out_iterator);
            plain_loop(x, &mut out_loop);
            assert_eq!(out_iterator, out_loop);
        })
    }
    #[test]
    // TODO 需要随机测试
    fn count_ones_test() {
        (0..=0x7f).for_each(|x: u8| assert_eq!(x.bits(..).count_ones(), x.count_ones()));
        (0x5a5a..=0xffff).for_each(|x: u16| assert_eq!(x.bits(..).count_ones(), x.count_ones()));
        (0x5a5a5a5a..=0x5a5aff5a)
            .for_each(|x: u32| assert_eq!(x.bits(..).count_ones(), x.count_ones()));
        (0x5a5a_5a5a_5a5a_5a5a..=0x5a5a_55aa_ffff_5a5a)
            .for_each(|x: u64| assert_eq!(x.bits(..).count_ones(), x.count_ones()));
    }

    #[bench]
    fn bench_plain_loop_code(b: &mut Bencher) {
        let n = test::black_box(0xffff);
        let mut out = test::black_box([0u8; 64]);
        b.iter(|| (0..=n).for_each(|x| plain_loop(x, &mut out)))
    }

    #[bench]
    fn bench_bits_iterator_code(b: &mut Bencher) {
        let n = test::black_box(0xffff);
        let mut out = test::black_box([0u8; 64]);
        b.iter(|| (0..=n).for_each(|x| bits_iterator(x, &mut out)))
    }
    #[no_mangle]
    fn count_ones_bits(data: u64) -> u32 {
        data.bits(..).count_ones()
    }
    #[no_mangle]
    fn count_ones_interal(data: u64) -> u32 {
        data.count_ones()
    }
    #[bench]
    fn bench_count_ones_bits(b: &mut Bencher) {
        let n = test::black_box(0xffff);
        let mut result = test::black_box(0);
        b.iter(|| {
            (0..=n).for_each(|x: u16| {
                result += x.bits(0..=15).count_ones();
            })
        });
    }
    #[bench]
    fn bench_count_ones_internal(b: &mut Bencher) {
        let n = test::black_box(0xffff);
        let mut result = test::black_box(0);
        b.iter(|| {
            (0..=n).for_each(|x: u16| {
                result += x.count_ones();
            })
        })
    }
}

// 👌 请注意对比和修改测试跑分结果
//
// test tests::bench_bits_iterator_code  ... bench:      15,323 ns/iter (+/- 172)
// test tests::bench_count_ones_bits     ... bench:      26,211 ns/iter (+/- 326)
// test tests::bench_count_ones_internal ... bench:      28,036 ns/iter (+/- 494)
// test tests::bench_plain_loop_code     ... bench:   1,514,810 ns/iter (+/- 13,509)