bits_io/io/
bit_slice_traits.rs1use crate::prelude::*;
2
3impl BitRead for &BitSlice {
4 fn read_bits<O: BitStore>(&mut self, dest: &mut BitSlice<O>) -> std::io::Result<usize> {
5 let n = self.len().min(dest.len());
6 dest[..n].clone_from_bitslice(&self[..n]);
7
8 *self = &self[n..];
9
10 Ok(n)
11 }
12}
13
14impl<S: BitStore> BitWrite for &mut BitSlice<S> {
15 fn write_bits<O: BitStore>(&mut self, source: &BitSlice<O>) -> std::io::Result<usize> {
16 let n = self.len().min(source.len());
17 self[..n].clone_from_bitslice(&source[..n]);
18
19 *self = &mut std::mem::take(self)[n..];
20
21 Ok(n)
22 }
23}
24
25#[cfg(test)]
26mod tests {
27 use super::*;
28
29 #[test]
30 fn test_write_bits_unique_slice() {
31 let mut buf = [0u8; 2];
32 let mut bits = BitSlice::from_slice_mut(&mut buf[..]);
33
34 bits.write_bits(bits![1]).unwrap();
35 bits.write_bits(bits![0, 0, 1]).unwrap();
36 bits.write_bits(bits![0, 0, 0, 0, 1]).unwrap();
37
38 assert_eq!(buf, [0b10010000, 0b10000000]);
39 }
40
41 #[test]
42 fn test_write_bits_shared_slice() {
43 let mut buf = [0u8; 2];
44 let bits = BitSlice::from_slice_mut(&mut buf[..]);
45 let (mut left, mut right) = bits.split_at_mut(8);
46
47 left.write_bits(bits![1]).unwrap();
48 left.write_bits(bits![0, 0, 1]).unwrap();
49
50 right.write_bits(bits![0, 1]).unwrap();
51 right.write_bits(bits![0, 0, 0, 1]).unwrap();
52
53 assert_eq!(buf, [0b10010000, 0b01000100]);
54 }
55
56 #[test]
57 fn test_read_bits() {
58 let mut data = bits![0, 1, 0, 0, 1, 0, 0, 0, 0, 1];
59
60 let read_buf = bits![mut 0; 2];
61 data.read_bits(&mut read_buf[..]).unwrap();
62 assert_eq!(read_buf, bits![0, 1]);
63
64 let read_buf = bits![mut 0; 3];
65 data.read_bits(&mut read_buf[..]).unwrap();
66 assert_eq!(read_buf, bits![0, 0, 1]);
67
68 let read_buf = bits![mut 0; 5];
69 data.read_bits(&mut read_buf[..]).unwrap();
70 assert_eq!(read_buf, bits![0, 0, 0, 0, 1]);
71 }
72}