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
|
use std::ops::BitAnd;
pub trait Sortable
{
type Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord;
}
impl<Item> Sortable for [Item]
{
type Item = Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord,
{
self.sort_by_key(func);
}
}
impl<Item, const LENGTH: usize> Sortable for [Item; LENGTH]
{
type Item = Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord,
{
self.sort_by_key(func);
}
}
impl<Item> Sortable for Vec<Item>
{
type Item = Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord,
{
self.sort_by_key(func);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BitMask<Value>
{
mask: Value,
}
impl BitMask<u64>
{
#[must_use]
pub const fn new(mask: u64) -> Self
{
Self { mask }
}
pub const fn value(self) -> u64
{
self.mask
}
/// Prepares a bitfield value in the range of bits specified by this `BitMask`.
#[must_use]
pub const fn field_prep(self, field_value: u64) -> u64
{
((field_value) << self.mask.trailing_zeros()) & (self.mask)
}
}
impl BitAnd<u64> for BitMask<u64>
{
type Output = u64;
fn bitand(self, rhs: u64) -> Self::Output
{
self.mask & rhs
}
}
pub trait NumberExt: Sized
{
/// Returns a range of bits (field) specified by the provided [`BitMask`].
fn field_get(self, field_mask: BitMask<Self>) -> Self;
}
impl NumberExt for u64
{
fn field_get(self, field_mask: BitMask<Self>) -> Self
{
(field_mask & self) >> field_mask.value().trailing_zeros()
}
}
macro_rules! gen_mask_64 {
($low: literal..=$high: literal) => {
const {
if $high <= $low {
panic!("High bit index cannot be less than or equal to low bit index");
}
(((!0u64) - (1u64 << ($low)) + 1)
& (!0u64 >> (u64::BITS as u64 - 1 - ($high))))
}
};
}
pub(crate) use gen_mask_64;
#[cfg(test)]
mod tests
{
use super::BitMask;
use crate::util::NumberExt;
#[test]
fn field_get_works()
{
assert_eq!(0b11011u64.field_get(BitMask::new(0b11100)), 0b00110);
}
#[test]
fn bitmask_field_prep_works()
{
assert_eq!(BitMask::new(0b11000).field_prep(3), 0b11000);
}
}
|