1use crate::mask::mask128;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct Extent {
10 start: u64,
11 width: u32,
12}
13
14impl Extent {
15 #[must_use]
21 pub const fn new(start: u64, width: u32) -> Self {
22 assert!(width >= 1, "extent width must be at least 1");
23 Self { start, width }
24 }
25
26 #[must_use]
28 pub const fn start(&self) -> u64 {
29 self.start
30 }
31
32 #[must_use]
34 pub const fn width(&self) -> u32 {
35 self.width
36 }
37
38 #[must_use]
40 pub const fn end(&self) -> u64 {
41 self.start + self.width as u64
42 }
43
44 #[inline]
45 const fn mask_wide(&self) -> u128 {
46 mask128(self.width)
47 }
48
49 #[inline]
51 #[must_use]
52 pub const fn extract_wide(&self, bits: u128) -> u128 {
53 debug_assert!(self.end() <= 128, "the field lies outside a u128 container");
54 (bits >> self.start) & self.mask_wide()
55 }
56
57 #[inline]
61 #[must_use]
62 pub const fn insert_wide(&self, bits: u128, value: u128) -> u128 {
63 let mask = self.mask_wide();
64 (bits & !(mask << self.start)) | ((value & mask) << self.start)
65 }
66
67 #[inline]
69 #[must_use]
70 pub const fn extract(&self, bits: u128) -> u64 {
71 self.extract_wide(bits) as u64
72 }
73
74 #[inline]
76 #[must_use]
77 pub const fn insert(&self, bits: u128, value: u64) -> u128 {
78 self.insert_wide(bits, value as u128)
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85
86 #[test]
87 fn extract_and_insert_are_inverse() {
88 let field = Extent::new(19, 19);
89 let word = field.insert(0, 0x5_A5A5);
90 assert_eq!(field.extract(word), 0x5_A5A5);
91 assert_eq!(word & !((crate::mask::mask64(field.width()) as u128) << 19), 0);
92 }
93
94 #[test]
95 fn insert_masks_oversized_values() {
96 let field = Extent::new(4, 4);
97 assert_eq!(field.insert(0, 0xFF), 0xF0);
98 }
99
100 #[test]
101 fn a_full_width_64_bit_field_works() {
102 let field = Extent::new(6, 64);
103 let word = field.insert(0, u64::MAX);
104 assert_eq!(field.extract(word), u64::MAX);
105 }
106
107 #[test]
108 fn adjacent_fields_do_not_interfere() {
109 let a = Extent::new(0, 13);
110 let b = Extent::new(13, 7);
111 let mut word = 0u128;
112 word = a.insert(word, 0x1FFF);
113 word = b.insert(word, 0);
114 assert_eq!(a.extract(word), 0x1FFF);
115 assert_eq!(b.extract(word), 0);
116 }
117}