]>
code.octet-stream.net Git - m17rt/blob - m17core/src/bits.rs
3 pub(crate) struct BitsBase
<T
>(T
)
11 pub(crate) fn get_bit(&self, idx
: usize) -> u8 {
12 self.0.as_ref()[idx
/ 8] >> (7 - (idx
% 8)) & 0x01
15 pub(crate) fn iter(&self) -> BitsIterator
<T
> {
16 BitsIterator
{ bits
: self, idx
: 0 }
20 pub(crate) struct BitsIterator
<'a
, T
>
24 bits
: &'a BitsBase
<T
>,
28 impl<T
> Iterator
for BitsIterator
<'_
, T
>
34 fn next(&mut self) -> Option
<Self::Item
> {
35 if self.idx
>= self.bits
.0.as_ref().len() * 8 {
38 let bit
= self.bits
.get_bit(self.idx
);
44 pub(crate) struct Bits
<'a
>(BitsBase
<&'a
[u8]>);
47 pub(crate) fn new(data
: &'a
[u8]) -> Self {
52 impl<'a
> Deref
for Bits
<'a
> {
53 type Target
= BitsBase
<&'a
[u8]>;
55 fn deref(&self) -> &Self::Target
{
60 pub(crate) struct BitsMut
<'a
>(BitsBase
<&'a
mut [u8]>);
62 impl<'a
> Deref
for BitsMut
<'a
> {
63 type Target
= BitsBase
<&'a
mut [u8]>;
65 fn deref(&self) -> &Self::Target
{
70 impl<'a
> BitsMut
<'a
> {
71 pub(crate) fn new(data
: &'a
mut [u8]) -> Self {
75 pub(crate) fn set_bit(&mut self, idx
: usize, value
: u8) {
76 let slice
= &mut self.0 .0;
77 let existing
= slice
[idx
/ 8];
79 slice
[idx
/ 8] = existing
& !(1 << (7 - (idx
% 8)));
81 slice
[idx
/ 8] = existing
| (1 << (7 - (idx
% 8)));
92 let data
: [u8; 2] = [0b00001111, 0b10101010];
93 let bits
= Bits
::new(&data
);
94 assert_eq
!(bits
.get_bit(0), 0);
95 assert_eq
!(bits
.get_bit(1), 0);
96 assert_eq
!(bits
.get_bit(4), 1);
97 assert_eq
!(bits
.get_bit(8), 1);
98 assert_eq
!(bits
.get_bit(9), 0);
102 fn bits_modifying() {
103 let mut data
: [u8; 2] = [0b00001111, 0b10101010];
104 let mut bits
= BitsMut
::new(&mut data
);
106 assert_eq
!(bits
.get_bit(0), 0);
108 assert_eq
!(bits
.get_bit(0), 1);
110 assert_eq
!(bits
.get_bit(4), 1);
112 assert_eq
!(bits
.get_bit(4), 0);
114 assert_eq
!(bits
.get_bit(9), 0);
116 assert_eq
!(bits
.get_bit(9), 1);
118 assert_eq
!(data
, [0b10000111, 0b11101010]);
123 let data
: [u8; 2] = [0b00110111, 0b10101010];
124 let bits
= Bits
::new(&data
);
125 let mut it
= bits
.iter
();
126 assert_eq
!(it
.next(), Some(0));
127 assert_eq
!(it
.next(), Some(0));
128 assert_eq
!(it
.next(), Some(1));
129 assert_eq
!(it
.next(), Some(1));
130 assert_eq
!(it
.next(), Some(0));
131 assert_eq
!(it
.next(), Some(1));
135 assert_eq
!(it
.next(), Some(1));
136 assert_eq
!(it
.next(), Some(0));
137 assert_eq
!(it
.next(), None
);