griffin_core/pallas_codec/flat/encode/encoder.rs
1use super::Encode;
2use super::Error;
3use crate::pallas_codec::flat::zigzag::ZigZag;
4
5use alloc::vec::Vec;
6
7use num_bigint::{BigInt, BigUint};
8
9pub struct Encoder {
10 pub buffer: Vec<u8>,
11 // Int
12 used_bits: i64,
13 // Int
14 current_byte: u8,
15}
16
17impl Default for Encoder {
18 fn default() -> Self {
19 Self::new()
20 }
21}
22
23impl Encoder {
24 pub fn new() -> Encoder {
25 Encoder {
26 buffer: Vec::new(),
27 used_bits: 0,
28 current_byte: 0,
29 }
30 }
31
32 /// Encode any type that implements [`Encode`].
33 pub fn encode<T: Encode>(&mut self, x: T) -> Result<&mut Self, Error> {
34 x.encode(self)?;
35
36 Ok(self)
37 }
38
39 /// Encode 1 unsigned byte.
40 /// Uses the next 8 bits in the buffer, can be byte aligned or byte
41 /// unaligned
42 pub fn u8(&mut self, x: u8) -> Result<&mut Self, Error> {
43 if self.used_bits == 0 {
44 self.current_byte = x;
45 self.next_word();
46 } else {
47 self.byte_unaligned(x);
48 }
49
50 Ok(self)
51 }
52
53 /// Encode a `bool` value. This is byte alignment agnostic.
54 /// Uses the next unused bit in the current byte to encode this information.
55 /// One for true and Zero for false
56 pub fn bool(&mut self, x: bool) -> &mut Self {
57 if x {
58 self.one();
59 } else {
60 self.zero();
61 }
62
63 self
64 }
65
66 /// Encode a byte array.
67 /// Uses filler to byte align the buffer, then writes byte array length up
68 /// to 255. Following that it writes the next 255 bytes from the array.
69 /// We repeat writing length up to 255 and the next 255 bytes until we reach
70 /// the end of the byte array. After reaching the end of the byte array
71 /// we write a 0 byte. Only write 0 byte if the byte array is empty.
72 pub fn bytes(&mut self, x: &[u8]) -> Result<&mut Self, Error> {
73 // use filler to write current buffer so bits used gets reset
74 self.filler();
75
76 self.byte_array(x)
77 }
78
79 /// Encode a byte array in a byte aligned buffer. Throws exception if any
80 /// bits for the current byte were used. Writes byte array length up to
81 /// 255 Following that it writes the next 255 bytes from the array.
82 /// We repeat writing length up to 255 and the next 255 bytes until we reach
83 /// the end of the byte array. After reaching the end of the buffer we
84 /// write a 0 byte. Only write 0 if the byte array is empty.
85 pub fn byte_array(&mut self, arr: &[u8]) -> Result<&mut Self, Error> {
86 if self.used_bits != 0 {
87 return Err(Error::BufferNotByteAligned);
88 }
89
90 self.write_blk(arr);
91
92 Ok(self)
93 }
94
95 /// Encode an isize integer.
96 ///
97 /// This is byte alignment agnostic.
98 /// First we use zigzag once to double the number and encode the negative
99 /// sign as the least significant bit. Next we encode the 7 least
100 /// significant bits of the unsigned integer. If the number is greater than
101 /// 127 we encode a leading 1 followed by repeating the encoding above for
102 /// the next 7 bits and so on.
103 pub fn integer(&mut self, i: isize) -> &mut Self {
104 self.word(i.zigzag());
105 self
106 }
107
108 /// Encode an arbitrarily sized integer.
109 ///
110 /// This is byte alignment agnostic.
111 /// First we use zigzag once to double the number and encode the negative
112 /// sign as the least significant bit. Next we encode the 7 least
113 /// significant bits of the unsigned integer. If the number is greater than
114 /// 127 we encode a leading 1 followed by repeating the encoding above for
115 /// the next 7 bits and so on.
116 pub fn big_integer(&mut self, i: BigInt) -> &mut Self {
117 self.big_word(i.zigzag());
118 self
119 }
120
121 /// Encode a char of 32 bits.
122 /// This is byte alignment agnostic.
123 /// We encode the 7 least significant bits of the unsigned byte. If the char
124 /// value is greater than 127 we encode a leading 1 followed by
125 /// repeating the above for the next 7 bits and so on.
126 pub fn char(&mut self, c: char) -> &mut Self {
127 self.word(c as usize);
128
129 self
130 }
131
132 // TODO: Do we need this?
133 pub fn string(&mut self, s: &str) -> &mut Self {
134 for i in s.chars() {
135 self.one();
136 self.char(i);
137 }
138
139 self.zero();
140
141 self
142 }
143
144 /// Encode a string.
145 /// Convert to byte array and then use byte array encoding.
146 /// Uses filler to byte align the buffer, then writes byte array length up
147 /// to 255. Following that it writes the next 255 bytes from the array.
148 /// After reaching the end of the buffer we write a 0 byte. Only write 0
149 /// byte if the byte array is empty.
150 pub fn utf8(&mut self, s: &str) -> Result<&mut Self, Error> {
151 self.bytes(s.as_bytes())
152 }
153
154 /// Encode a unsigned integer of any size.
155 /// This is byte alignment agnostic.
156 /// We encode the 7 least significant bits of the unsigned byte. If the char
157 /// value is greater than 127 we encode a leading 1 followed by
158 /// repeating the above for the next 7 bits and so on.
159 pub fn word(&mut self, c: usize) -> &mut Self {
160 let mut d = c;
161 loop {
162 let mut w = (d & 127) as u8;
163 d >>= 7;
164
165 if d != 0 {
166 w |= 128;
167 }
168 self.bits(8, w);
169
170 if d == 0 {
171 break;
172 }
173 }
174
175 self
176 }
177
178 /// Encode a unsigned integer of 128 bits size.
179 /// This is byte alignment agnostic.
180 /// We encode the 7 least significant bits of the unsigned byte. If the char
181 /// value is greater than 127 we encode a leading 1 followed by
182 /// repeating the above for the next 7 bits and so on.
183 pub fn big_word(&mut self, c: BigUint) -> &mut Self {
184 let mut d = c;
185 let zero = (0_u8).into();
186 loop {
187 let m: usize = 127;
188 let mut w = (d.clone() & <usize as Into<BigUint>>::into(m))
189 .to_bytes_be()
190 .pop()
191 .unwrap();
192
193 d >>= 7;
194
195 if d != zero {
196 w |= 128;
197 }
198 self.bits(8, w);
199
200 if d == zero {
201 break;
202 }
203 }
204
205 self
206 }
207
208 /// Encode a list of bytes with a function
209 /// This is byte alignment agnostic.
210 /// If there are bytes in a list then write 1 bit followed by the functions
211 /// encoding. After the last item write a 0 bit. If the list is empty
212 /// only encode a 0 bit.
213 pub fn encode_list_with<T>(
214 &mut self,
215 list: &[T],
216 encoder_func: for<'r> fn(&T, &'r mut Encoder) -> Result<(), Error>,
217 ) -> Result<&mut Self, Error> {
218 for item in list {
219 self.one();
220 encoder_func(item, self)?;
221 }
222
223 self.zero();
224
225 Ok(self)
226 }
227
228 /// Encodes up to 8 bits of information and is byte alignment agnostic.
229 /// Uses unused bits in the current byte to write out the passed in byte
230 /// value. Overflows to the most significant digits of the next byte if
231 /// number of bits to use is greater than unused bits. Expects that
232 /// number of bits to use is greater than or equal to required bits by the
233 /// value. The param num_bits is i64 to match unused_bits type.
234 pub fn bits(&mut self, num_bits: i64, val: u8) -> &mut Self {
235 match (num_bits, val) {
236 (1, 0) => self.zero(),
237 (1, 1) => self.one(),
238 (2, 0) => {
239 self.zero();
240 self.zero();
241 }
242 (2, 1) => {
243 self.zero();
244 self.one();
245 }
246 (2, 2) => {
247 self.one();
248 self.zero();
249 }
250 (2, 3) => {
251 self.one();
252 self.one();
253 }
254 (_, _) => {
255 self.used_bits += num_bits;
256 let unused_bits = 8 - self.used_bits;
257 match unused_bits {
258 0 => {
259 self.current_byte |= val;
260 self.next_word();
261 }
262 x if x > 0 => {
263 self.current_byte |= val << x;
264 }
265 x => {
266 let used = -x;
267 self.current_byte |= val >> used;
268 self.next_word();
269 self.current_byte = val << (8 - used);
270 self.used_bits = used;
271 }
272 }
273 }
274 }
275
276 self
277 }
278
279 /// A filler amount of end 0's followed by a 1 at the end of a byte.
280 /// Used to byte align the buffer by padding out the rest of the byte.
281 pub(crate) fn filler(&mut self) -> &mut Self {
282 self.current_byte |= 1;
283 self.next_word();
284
285 self
286 }
287
288 /// Write a 0 bit into the current byte.
289 /// Write out to buffer if last used bit in the current byte.
290 fn zero(&mut self) {
291 if self.used_bits == 7 {
292 self.next_word();
293 } else {
294 self.used_bits += 1;
295 }
296 }
297
298 /// Write a 1 bit into the current byte.
299 /// Write out to buffer if last used bit in the current byte.
300 fn one(&mut self) {
301 if self.used_bits == 7 {
302 self.current_byte |= 1;
303 self.next_word();
304 } else {
305 self.current_byte |= 128 >> self.used_bits;
306 self.used_bits += 1;
307 }
308 }
309 /// Write out byte regardless of current buffer alignment.
310 /// Write most significant bits in remaining unused bits for the current
311 /// byte, then write out the remaining bits at the beginning of the next
312 /// byte.
313 fn byte_unaligned(&mut self, x: u8) {
314 let x_shift = self.current_byte | (x >> self.used_bits);
315 self.buffer.push(x_shift);
316
317 self.current_byte = x << (8 - self.used_bits);
318 }
319
320 /// Write the current byte out to the buffer and begin next byte to write
321 /// out. Add current byte to the buffer and set current byte and used
322 /// bits to 0.
323 fn next_word(&mut self) {
324 self.buffer.push(self.current_byte);
325
326 self.current_byte = 0;
327 self.used_bits = 0;
328 }
329
330 /// Writes byte array length up to 255
331 /// Following that it writes the next 255 bytes from the array.
332 /// After reaching the end of the buffer we write a 0 byte. Only write 0 if
333 /// the byte array is empty. This is byte alignment agnostic.
334 fn write_blk(&mut self, arr: &[u8]) {
335 let chunks = arr.chunks(255);
336
337 for chunk in chunks {
338 self.buffer.push(chunk.len() as u8);
339 self.buffer.extend(chunk);
340 }
341 self.buffer.push(0_u8);
342 }
343}