euv_docs/codec/impl.rs
1use super::*;
2
3/// Human-readable diagnostic formatting for `DocsCodecError`.
4impl fmt::Display for DocsCodecError {
5 /// Formats a descriptive error string for build logs and boot diagnostics.
6 ///
7 /// # Arguments
8 ///
9 /// - `&Self` - Error variant reference.
10 /// - `&mut fmt::Formatter<'_>` - Output formatter.
11 ///
12 /// # Returns
13 ///
14 /// - `fmt::Result` - Formatting result.
15 fn fmt(&self, factor_val: &mut fmt::Formatter<'_>) -> fmt::Result {
16 match self {
17 Self::BadMagic => write!(factor_val, "{CODEC_ERR_BAD_MAGIC}"),
18 Self::UnsupportedVersion(version) => {
19 write!(factor_val, "{CODEC_ERR_VERSION}: {version}")
20 }
21 Self::Truncated => write!(factor_val, "{CODEC_ERR_TRUNCATED}"),
22 Self::InvalidCodeLengths => write!(factor_val, "{CODEC_ERR_CODE_LENGTHS}"),
23 Self::InvalidSymbol => write!(factor_val, "{CODEC_ERR_SYMBOL}"),
24 Self::InvalidDistance => write!(factor_val, "{CODEC_ERR_DISTANCE}"),
25 Self::LengthMismatch => write!(factor_val, "{CODEC_ERR_LENGTH}"),
26 Self::PageCountMismatch => write!(factor_val, "{CODEC_ERR_PAGE_COUNT}"),
27 Self::InvalidPayload(reason) => write!(factor_val, "{CODEC_ERR_PAYLOAD}: {reason}"),
28 }
29 }
30}
31
32/// Bit-level streaming helpers for `CodecBitWriter`.
33impl CodecBitWriter {
34 /// Creates an empty bit writer preallocated for approximately `capacity` output bytes.
35 ///
36 /// # Arguments
37 ///
38 /// - `usize` - Estimated output byte capacity.
39 ///
40 /// # Returns
41 ///
42 /// - `Self` - Initialized bit writer.
43 pub(crate) fn with_capacity(capacity: usize) -> Self {
44 Self {
45 bytes: Vec::with_capacity(capacity),
46 bit_buf: 0,
47 bit_count: 0,
48 }
49 }
50
51 /// Appends the lowest `count` bits of `bits` in LSB-first order.
52 ///
53 /// # Arguments
54 ///
55 /// - `&Self` - Mutable bit writer reference.
56 /// - `u64` - Bit payload (only lowest `count` bits are used).
57 /// - `u32` - Number of bits to append (`0..=32`).
58 pub(crate) fn write_bits(&mut self, bits: u64, count: u32) {
59 if count == 0 {
60 return;
61 }
62 let next_buf: u64 = self.get_bit_buf() | (bits << self.get_bit_count());
63 let mut next_count: u32 = self.get_bit_count() + count;
64 let mut cur_buf: u64 = next_buf;
65 while next_count >= 8 {
66 self.get_mut_bytes().push((cur_buf & 0xFF) as u8);
67 cur_buf >>= 8;
68 next_count -= 8;
69 }
70 self.set_bit_buf(cur_buf);
71 self.set_bit_count(next_count);
72 }
73
74 /// Flushes any trailing partial byte padded with zero bits and returns the encoded byte vector.
75 ///
76 /// # Arguments
77 ///
78 /// - `Self` - Consumed bit writer.
79 ///
80 /// # Returns
81 ///
82 /// - `Vec<u8>` - Complete encoded byte stream.
83 pub(crate) fn finish(mut self) -> Vec<u8> {
84 if self.get_bit_count() > 0 {
85 let tail: u8 = (self.get_bit_buf() & 0xFF) as u8;
86 self.get_mut_bytes().push(tail);
87 self.set_bit_buf(0);
88 self.set_bit_count(0);
89 }
90 take(self.get_mut_bytes())
91 }
92}
93
94/// Bit-level streaming helpers for `CodecBitReader`.
95impl<'a> CodecBitReader<'a> {
96 /// Creates a new bit reader positioned at byte offset `0` of `data`.
97 ///
98 /// # Arguments
99 ///
100 /// - `&'a [u8]` - Compressed byte slice positioned after the stream header.
101 ///
102 /// # Returns
103 ///
104 /// - `Self` - Initialized bit reader.
105 pub(crate) fn from_slice(data: &'a [u8]) -> Self {
106 Self {
107 data,
108 cursor: 0,
109 bit_buf: 0,
110 bit_count: 0,
111 }
112 }
113
114 /// Refills the bit buffer from `data` until at least `CODEC_REFILL_THRESHOLD` bits are buffered or input ends.
115 ///
116 /// # Arguments
117 ///
118 /// - `&Self` - Mutable bit reader reference.
119 pub(crate) fn refill(&mut self) {
120 let slice: &[u8] = self.get_data();
121 let mut pos: usize = self.get_cursor();
122 let mut buf: u64 = self.get_bit_buf();
123 let mut count: u32 = self.get_bit_count();
124 while count <= CODEC_REFILL_THRESHOLD && pos < slice.len() {
125 buf |= (slice[pos] as u64) << count;
126 pos += 1;
127 count += 8;
128 }
129 self.set_cursor(pos);
130 self.set_bit_buf(buf);
131 self.set_bit_count(count);
132 }
133
134 /// Reads exactly `count` bits in LSB-first order, failing with `DocsCodecError::Truncated` if unavailable.
135 ///
136 /// # Arguments
137 ///
138 /// - `&Self` - Mutable bit reader reference.
139 /// - `u32` - Number of bits to read (`0..=32`).
140 ///
141 /// # Returns
142 ///
143 /// - `Result<u32, DocsCodecError>` - Extracted bit value or truncation error.
144 pub(crate) fn read_bits(&mut self, count: u32) -> Result<u32, DocsCodecError> {
145 if count == 0 {
146 return Ok(0);
147 }
148 if self.get_bit_count() < count {
149 self.refill();
150 if self.get_bit_count() < count {
151 return Err(DocsCodecError::Truncated);
152 }
153 }
154 let mask: u64 = (1u64 << count) - 1;
155 let value: u32 = (self.get_bit_buf() & mask) as u32;
156 self.set_bit_buf(self.get_bit_buf() >> count);
157 self.set_bit_count(self.get_bit_count() - count);
158 Ok(value)
159 }
160
161 /// Consumes `count` already-peeked bits from the buffer.
162 ///
163 /// # Arguments
164 ///
165 /// - `&Self` - Mutable bit reader reference.
166 /// - `u32` - Number of bits to drop.
167 pub(crate) fn consume(&mut self, count: u32) {
168 self.set_bit_buf(self.get_bit_buf() >> count);
169 self.set_bit_count(self.get_bit_count() - count);
170 }
171}