xrpl/core/binarycodec/binary_wrappers.rs
1use super::definitions::*;
2use super::types::TryFromParser;
3use crate::core::binarycodec::exceptions::XRPLBinaryCodecException;
4use crate::core::binarycodec::utils::*;
5use crate::core::exceptions::XRPLCoreException;
6use crate::core::exceptions::XRPLCoreResult;
7use crate::utils::ToBytes;
8use alloc::borrow::ToOwned;
9use alloc::vec;
10use alloc::vec::Vec;
11use core::convert::TryFrom;
12use core::convert::TryInto;
13
14/// Serializes JSON to XRPL binary format.
15pub type BinarySerializer = Vec<u8>;
16
17/// Deserializes from hex-encoded XRPL binary format to
18/// serde JSON fields and values.
19///
20/// # Examples
21///
22/// ## Basic usage
23///
24/// ```
25/// use xrpl::core::binarycodec::BinaryParser;
26/// use xrpl::core::Parser;
27/// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
28///
29/// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
30/// let binary_parser: BinaryParser = BinaryParser::from(test_bytes);
31///
32/// assert_eq!(binary_parser, test_bytes[..]);
33/// ```
34#[derive(Debug, Clone)]
35pub struct BinaryParser(Vec<u8>);
36
37/// Helper function for length-prefixed fields including
38/// Blob types and some AccountID types. Calculates the
39/// prefix of variable length bytes.
40///
41/// The length of the prefix is 1-3 bytes depending on the
42/// length of the contents:
43/// Content length <= 192 bytes: prefix is 1 byte
44/// 192 bytes < Content length <= 12480 bytes: prefix is 2 bytes
45/// 12480 bytes < Content length <= 918744 bytes: prefix is 3 bytes
46///
47/// See Length Prefixing:
48/// `<https://xrpl.org/serialization.html#length-prefixing>`
49fn _encode_variable_length_prefix(length: &usize) -> XRPLCoreResult<Vec<u8>> {
50 if length <= &MAX_SINGLE_BYTE_LENGTH {
51 Ok([*length as u8].to_vec())
52 } else if length < &MAX_DOUBLE_BYTE_LENGTH {
53 let mut bytes = vec![];
54 let b_length = *length - (MAX_SINGLE_BYTE_LENGTH + 1);
55 let val_a: u8 = ((b_length >> 8) + (MAX_SINGLE_BYTE_LENGTH + 1))
56 .try_into()
57 .map_err(XRPLBinaryCodecException::TryFromIntError)?;
58 let val_b: u8 = (b_length & 0xFF)
59 .try_into()
60 .map_err(XRPLBinaryCodecException::TryFromIntError)?;
61
62 bytes.extend_from_slice(&[val_a]);
63 bytes.extend_from_slice(&[val_b]);
64
65 Ok(bytes)
66 } else if length <= &MAX_LENGTH_VALUE {
67 let mut bytes = vec![];
68 let b_length = *length - MAX_DOUBLE_BYTE_LENGTH;
69 let val_a: u8 = ((MAX_SECOND_BYTE_VALUE + 1) + (b_length >> 16))
70 .try_into()
71 .map_err(XRPLBinaryCodecException::TryFromIntError)?;
72 let val_b: u8 = ((b_length >> 8) & 0xFF)
73 .try_into()
74 .map_err(XRPLBinaryCodecException::TryFromIntError)?;
75 let val_c: u8 = (b_length & 0xFF)
76 .try_into()
77 .map_err(XRPLBinaryCodecException::TryFromIntError)?;
78
79 bytes.extend_from_slice(&[val_a]);
80 bytes.extend_from_slice(&[val_b]);
81 bytes.extend_from_slice(&[val_c]);
82
83 Ok(bytes)
84 } else {
85 Err(XRPLBinaryCodecException::InvalidVariableLengthTooLarge {
86 max: MAX_LENGTH_VALUE,
87 }
88 .into())
89 }
90}
91
92pub trait Parser {
93 /// Peek the first byte of the BinaryParser.
94 ///
95 /// # Examples
96 ///
97 /// ## Basic usage
98 ///
99 /// ```
100 /// use xrpl::core::binarycodec::BinaryParser;
101 /// use xrpl::core::Parser;
102 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
103 ///
104 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
105 /// let binary_parser: BinaryParser = BinaryParser::from(test_bytes);
106 /// let first_byte: Option<[u8; 1]> = binary_parser.peek();
107 ///
108 /// assert_eq!(Some([test_bytes[0]; 1]), first_byte);
109 /// ```
110 fn peek(&self) -> Option<[u8; 1]>;
111
112 /// Consume the first n bytes of the BinaryParser.
113 ///
114 /// # Examples
115 ///
116 /// ## Basic usage
117 ///
118 /// ```
119 /// use xrpl::core::binarycodec::BinaryParser;
120 /// use xrpl::core::Parser;
121 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
122 /// use xrpl::core::exceptions::XRPLCoreException;
123 ///
124 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
125 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
126 ///
127 /// match binary_parser.skip_bytes(4) {
128 /// Ok(parser) => assert_eq!(*parser, test_bytes[4..]),
129 /// Err(e) => match e {
130 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
131 /// max: _,
132 /// found: _,
133 /// }) => assert!(false),
134 /// _ => assert!(false)
135 /// }
136 /// }
137 /// ```
138 fn skip_bytes(&mut self, n: usize) -> XRPLCoreResult<&Self>;
139
140 /// Consume and return the first n bytes of the BinaryParser.
141 ///
142 /// # Examples
143 ///
144 /// ## Basic usage
145 ///
146 /// ```
147 /// use xrpl::core::binarycodec::BinaryParser;
148 /// use xrpl::core::Parser;
149 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
150 /// use xrpl::core::exceptions::XRPLCoreException;
151 ///
152 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
153 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
154 ///
155 /// match binary_parser.read(5) {
156 /// Ok(data) => assert_eq!(test_bytes[..5], data),
157 /// Err(e) => match e {
158 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
159 /// max: _,
160 /// found: _,
161 /// }) => assert!(false),
162 /// _ => assert!(false)
163 /// }
164 /// }
165 /// ```
166 fn read(&mut self, n: usize) -> XRPLCoreResult<Vec<u8>>;
167
168 /// Read 1 byte from parser and return as unsigned int.
169 ///
170 /// # Examples
171 ///
172 /// ## Basic usage
173 ///
174 /// ```
175 /// use xrpl::core::binarycodec::BinaryParser;
176 /// use xrpl::core::Parser;
177 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
178 /// use xrpl::core::exceptions::XRPLCoreException;
179 ///
180 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
181 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
182 ///
183 /// match binary_parser.read_uint8() {
184 /// Ok(data) => assert_eq!(0, data),
185 /// Err(e) => match e {
186 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
187 /// max: _,
188 /// found: _,
189 /// }) => assert!(false),
190 /// _ => assert!(false)
191 /// }
192 /// }
193 /// ```
194 fn read_uint8(&mut self) -> XRPLCoreResult<u8>;
195
196 /// Read 2 bytes from parser and return as unsigned int.
197 ///
198 /// # Examples
199 ///
200 /// ## Basic usage
201 ///
202 /// ```
203 /// use xrpl::core::binarycodec::BinaryParser;
204 /// use xrpl::core::Parser;
205 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
206 /// use xrpl::core::exceptions::XRPLCoreException;
207 ///
208 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
209 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
210 ///
211 /// match binary_parser.read_uint16() {
212 /// Ok(data) => assert_eq!(17, data),
213 /// Err(e) => match e {
214 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
215 /// max: _,
216 /// found: _,
217 /// }) => assert!(false),
218 /// _ => assert!(false)
219 /// }
220 /// }
221 /// ```
222 fn read_uint16(&mut self) -> XRPLCoreResult<u16>;
223
224 /// Read 4 bytes from parser and return as unsigned int.
225 ///
226 /// # Examples
227 ///
228 /// ## Basic usage
229 ///
230 /// ```
231 /// use xrpl::core::binarycodec::BinaryParser;
232 /// use xrpl::core::Parser;
233 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
234 /// use xrpl::core::exceptions::XRPLCoreException;
235 ///
236 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
237 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
238 ///
239 /// match binary_parser.read_uint32() {
240 /// Ok(data) => assert_eq!(1122867, data),
241 /// Err(e) => match e {
242 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
243 /// max: _,
244 /// found: _,
245 /// }) => assert!(false),
246 /// _ => assert!(false)
247 /// }
248 /// }
249 /// ```
250 fn read_uint32(&mut self) -> XRPLCoreResult<u32>;
251
252 /// Returns whether the binary parser has finished
253 /// parsing (e.g. there is nothing left in the buffer
254 /// that needs to be processed).
255 ///
256 /// # Examples
257 ///
258 /// ## Basic usage
259 ///
260 /// ```
261 /// use xrpl::core::binarycodec::BinaryParser;
262 /// use xrpl::core::Parser;
263 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
264 /// use xrpl::core::exceptions::XRPLCoreException;
265 /// extern crate alloc;
266 /// use alloc::vec;
267 ///
268 /// let empty: &[u8] = &[];
269 /// let mut buffer: Vec<u8> = vec![];
270 /// let test_bytes: &[u8] = &[0, 17, 34, 51, 68, 85, 102];
271 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
272 ///
273 /// while !binary_parser.is_end(None) {
274 /// match binary_parser.read(1) {
275 /// Ok(data) => buffer.extend_from_slice(&data),
276 /// Err(e) => match e {
277 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
278 /// max: _,
279 /// found: _,
280 /// }) => assert!(false),
281 /// _ => assert!(false)
282 /// }
283 /// }
284 /// }
285 ///
286 /// assert_eq!(test_bytes, &buffer[..]);
287 /// // The BinaryParser is emptied as it is read.
288 /// assert_eq!(binary_parser, empty[..]);
289 ///
290 /// ```
291 fn is_end(&self, custom_end: Option<usize>) -> bool;
292
293 /// Reads a variable length encoding prefix and returns
294 /// the encoded length. The formula for decoding a length
295 /// prefix is described in Length Prefixing.
296 ///
297 /// See Length Prefixing:
298 /// `<https://xrpl.org/serialization.html#length-prefixing>`
299 ///
300 /// # Examples
301 ///
302 /// ## Basic usage
303 ///
304 /// ```
305 /// use xrpl::core::binarycodec::BinaryParser;
306 /// use xrpl::core::Parser;
307 /// use xrpl::core::binarycodec::exceptions::XRPLBinaryCodecException;
308 /// use xrpl::core::exceptions::XRPLCoreException;
309 ///
310 /// let test_bytes: &[u8] = &[6, 17, 34, 51, 68, 85, 102];
311 /// let mut binary_parser: BinaryParser = BinaryParser::from(test_bytes);
312 ///
313 /// match binary_parser.read_length_prefix() {
314 /// Ok(data) => assert_eq!(6, data),
315 /// Err(e) => match e {
316 /// XRPLCoreException::XRPLBinaryCodecError(XRPLBinaryCodecException::UnexpectedLengthPrefixRange {
317 /// min: _, max: _
318 /// }) => assert!(false),
319 /// _ => assert!(false)
320 /// }
321 /// }
322 fn read_length_prefix(&mut self) -> XRPLCoreResult<usize>;
323
324 /// Reads field ID from BinaryParser and returns as
325 /// a FieldHeader object.
326 fn read_field_header(&mut self) -> XRPLCoreResult<FieldHeader>;
327
328 /// Read the field ordinal at the head of the
329 /// BinaryParser and return a FieldInstance object
330 /// representing information about the field
331 /// containedin the following bytes.
332 fn read_field(&mut self) -> XRPLCoreResult<FieldInstance>;
333
334 /// Read next bytes from BinaryParser as the given type.
335 fn read_type<T: TryFromParser>(&mut self) -> XRPLCoreResult<T, T::Error>;
336
337 /// Read value of the type specified by field from
338 /// the BinaryParser.
339 fn read_field_value<T: TryFromParser>(
340 &mut self,
341 field: &FieldInstance,
342 ) -> XRPLCoreResult<T, T::Error>
343 where
344 T::Error: From<XRPLCoreException>;
345}
346
347pub trait Serialization {
348 /// Write given bytes to this BinarySerializer.
349 ///
350 /// # Examples
351 ///
352 /// ## Basic usage
353 ///
354 /// ```
355 /// use xrpl::core::binarycodec::BinarySerializer;
356 /// use xrpl::core::binarycodec::Serialization;
357 ///
358 /// let mut test_bytes: Vec<u8> = [0, 17, 34, 51, 68, 85, 102].to_vec();
359 /// let mut serializer: BinarySerializer = BinarySerializer::new();
360 ///
361 /// serializer.append(&mut test_bytes.to_owned());
362 /// assert_eq!(test_bytes, serializer);
363 /// ```
364 fn append(&mut self, bytes: &[u8]) -> &Self;
365
366 /// Write a variable length encoded value to
367 /// the BinarySerializer.
368 ///
369 /// # Examples
370 ///
371 /// ## Basic usage
372 ///
373 /// ```
374 /// use xrpl::core::binarycodec::BinarySerializer;
375 /// use xrpl::core::binarycodec::Serialization;
376 ///
377 /// let expected: Vec<u8> = [3, 0, 17, 34].to_vec();
378 /// let mut test_bytes: Vec<u8> = [0, 17, 34].to_vec();
379 /// let mut serializer: BinarySerializer = BinarySerializer::new();
380 ///
381 /// serializer.write_length_encoded(&mut test_bytes, true);
382 /// assert_eq!(expected, serializer);
383 /// ```
384 fn write_length_encoded(&mut self, value: &[u8], encode_value: bool) -> &Self;
385
386 /// Write field and value to the buffer.
387 ///
388 /// # Examples
389 ///
390 /// ## Basic usage
391 ///
392 /// ```
393 /// use xrpl::core::binarycodec::BinarySerializer;
394 /// use xrpl::core::binarycodec::Serialization;
395 /// use xrpl::core::binarycodec::definitions::FieldInstance;
396 /// use xrpl::core::binarycodec::definitions::FieldInfo;
397 /// use xrpl::core::binarycodec::definitions::FieldHeader;
398 ///
399 /// let field_header: FieldHeader = FieldHeader {
400 /// type_code: -2,
401 /// field_code: 0,
402 /// };
403 ///
404 /// let field_info: FieldInfo = FieldInfo {
405 /// nth: 0,
406 /// is_vl_encoded: false,
407 /// is_serialized: false,
408 /// is_signing_field: false,
409 /// r#type: "Unknown".to_string(),
410 /// };
411 ///
412 /// let field_instance = FieldInstance::new(&field_info, "Generic", field_header);
413 /// let expected: Vec<u8> = [224, 0, 17, 34].to_vec();
414 /// let test_bytes: Vec<u8> = [0, 17, 34].to_vec();
415 /// let mut serializer: BinarySerializer = BinarySerializer::new();
416 ///
417 /// serializer.write_field_and_value(field_instance, &test_bytes, false);
418 /// assert_eq!(expected, serializer);
419 /// ```
420 fn write_field_and_value(
421 &mut self,
422 field: FieldInstance,
423 value: &[u8],
424 is_unl_modify_workaround: bool,
425 ) -> &Self;
426}
427
428impl Serialization for BinarySerializer {
429 fn append(&mut self, bytes: &[u8]) -> &Self {
430 self.extend_from_slice(bytes);
431 self
432 }
433
434 fn write_length_encoded(&mut self, value: &[u8], encode_value: bool) -> &Self {
435 let mut byte_object: Vec<u8> = Vec::new();
436 if encode_value {
437 // write value to byte_object
438 byte_object.extend_from_slice(value);
439 }
440 // TODO Handle unwrap better
441 let length_prefix = _encode_variable_length_prefix(&byte_object.len()).unwrap();
442
443 self.extend_from_slice(&length_prefix);
444 self.extend_from_slice(&byte_object);
445
446 self
447 }
448
449 fn write_field_and_value(
450 &mut self,
451 field: FieldInstance,
452 value: &[u8],
453 is_unl_modify_workaround: bool,
454 ) -> &Self {
455 self.extend_from_slice(&field.header.to_bytes());
456
457 if field.is_vl_encoded {
458 self.write_length_encoded(value, !is_unl_modify_workaround);
459 } else {
460 self.extend_from_slice(value);
461 }
462
463 self
464 }
465}
466
467/// Peek the first byte of the BinaryParser.
468impl Parser for BinaryParser {
469 fn peek(&self) -> Option<[u8; 1]> {
470 if !self.0.is_empty() {
471 Some(self.0[0].to_be_bytes())
472 } else {
473 None
474 }
475 }
476
477 fn skip_bytes(&mut self, n: usize) -> XRPLCoreResult<&Self> {
478 if n > self.0.len() {
479 Err(XRPLBinaryCodecException::UnexpectedParserSkipOverflow {
480 max: self.0.len(),
481 found: n,
482 }
483 .into())
484 } else {
485 self.0 = self.0[n..].to_vec();
486 Ok(self)
487 }
488 }
489
490 fn read(&mut self, n: usize) -> XRPLCoreResult<Vec<u8>> {
491 let first_n_bytes = self.0[..n].to_owned();
492
493 self.skip_bytes(n)?;
494 Ok(first_n_bytes)
495 }
496
497 fn read_uint8(&mut self) -> XRPLCoreResult<u8> {
498 let result = self.read(1)?;
499 Ok(u8::from_be_bytes(result.try_into().or(Err(
500 XRPLBinaryCodecException::InvalidReadFromBytesValue,
501 ))?))
502 }
503
504 fn read_uint16(&mut self) -> XRPLCoreResult<u16> {
505 let result = self.read(2)?;
506 Ok(u16::from_be_bytes(result.try_into().or(Err(
507 XRPLBinaryCodecException::InvalidReadFromBytesValue,
508 ))?))
509 }
510
511 fn read_uint32(&mut self) -> XRPLCoreResult<u32> {
512 let result = self.read(4)?;
513 Ok(u32::from_be_bytes(result.try_into().or(Err(
514 XRPLBinaryCodecException::InvalidReadFromBytesValue,
515 ))?))
516 }
517
518 fn is_end(&self, custom_end: Option<usize>) -> bool {
519 if let Some(end) = custom_end {
520 self.0.len() <= end
521 } else {
522 self.0.is_empty()
523 }
524 }
525
526 fn read_length_prefix(&mut self) -> XRPLCoreResult<usize> {
527 let byte1: usize = self.read_uint8()? as usize;
528
529 match byte1 {
530 // If the field contains 0 to 192 bytes of data,
531 // the first byte defines the length of the contents.
532 x if x <= MAX_SINGLE_BYTE_LENGTH => Ok(byte1),
533 // If the field contains 193 to 12480 bytes of data,
534 // the first two bytes indicate the length of the
535 // field with the following formula:
536 // 193 + ((byte1 - 193) * 256) + byte2
537 x if x <= MAX_SECOND_BYTE_VALUE => {
538 let byte2: usize = self.read_uint8()? as usize;
539 Ok((MAX_SINGLE_BYTE_LENGTH + 1)
540 + ((byte1 - (MAX_SINGLE_BYTE_LENGTH + 1)) * MAX_BYTE_VALUE)
541 + byte2)
542 }
543 // If the field contains 12481 to 918744 bytes of data,
544 // the first three bytes indicate the length of the
545 // field with the following formula:
546 // 12481 + ((byte1 - 241) * 65536) + (byte2 * 256) + byte3
547 x if x <= 254 => {
548 let byte2: usize = self.read_uint8()? as usize;
549 let byte3: usize = self.read_uint8()? as usize;
550
551 Ok(MAX_DOUBLE_BYTE_LENGTH
552 + ((byte1 - (MAX_SECOND_BYTE_VALUE + 1)) * MAX_DOUBLE_BYTE_VALUE)
553 + (byte2 * MAX_BYTE_VALUE)
554 + byte3)
555 }
556 _ => {
557 Err(XRPLBinaryCodecException::UnexpectedLengthPrefixRange { min: 1, max: 3 }.into())
558 }
559 }
560 }
561
562 fn read_field_header(&mut self) -> XRPLCoreResult<FieldHeader> {
563 let mut type_code: i16 = self.read_uint8()? as i16;
564 let mut field_code: i16 = type_code & 15;
565
566 type_code >>= 4;
567
568 if type_code == 0 {
569 type_code = self.read_uint8()? as i16;
570
571 if type_code == 0 || type_code < 16 {
572 return Err(
573 XRPLBinaryCodecException::UnexpectedTypeCodeRange { min: 1, max: 16 }.into(),
574 );
575 };
576 };
577
578 if field_code == 0 {
579 field_code = self.read_uint8()? as i16;
580
581 if field_code == 0 || field_code < 16 {
582 return Err(
583 XRPLBinaryCodecException::UnexpectedFieldCodeRange { min: 1, max: 16 }.into(),
584 );
585 };
586 };
587
588 Ok(FieldHeader {
589 type_code,
590 field_code,
591 })
592 }
593
594 fn read_field(&mut self) -> XRPLCoreResult<FieldInstance> {
595 let field_header = self.read_field_header()?;
596 let field_name = get_field_name_from_header(&field_header);
597
598 if let Some(name) = field_name {
599 if let Some(instance) = get_field_instance(name) {
600 return Ok(instance);
601 };
602 };
603
604 Err(XRPLBinaryCodecException::UnknownFieldName.into())
605 }
606
607 fn read_type<T: TryFromParser>(&mut self) -> XRPLCoreResult<T, T::Error> {
608 T::from_parser(self, None)
609 }
610
611 fn read_field_value<T: TryFromParser>(
612 &mut self,
613 field: &FieldInstance,
614 ) -> XRPLCoreResult<T, T::Error>
615 where
616 T::Error: From<XRPLCoreException>,
617 {
618 if field.is_vl_encoded {
619 let length = self.read_length_prefix()?;
620 T::from_parser(self, Some(length))
621 } else {
622 T::from_parser(self, None)
623 }
624 }
625}
626
627impl From<&[u8]> for BinaryParser {
628 fn from(hex_bytes: &[u8]) -> Self {
629 BinaryParser(hex_bytes.to_vec())
630 }
631}
632
633impl From<Vec<u8>> for BinaryParser {
634 fn from(hex_bytes: Vec<u8>) -> Self {
635 BinaryParser(hex_bytes)
636 }
637}
638
639impl TryFrom<&str> for BinaryParser {
640 type Error = XRPLCoreException;
641
642 fn try_from(hex_bytes: &str) -> XRPLCoreResult<Self, Self::Error> {
643 Ok(BinaryParser(hex::decode(hex_bytes)?))
644 }
645}
646
647impl PartialEq<[u8]> for BinaryParser {
648 fn eq(&self, bytes: &[u8]) -> bool {
649 self.0 == bytes
650 }
651}
652
653impl PartialEq<Vec<u8>> for BinaryParser {
654 fn eq(&self, bytes: &Vec<u8>) -> bool {
655 &self.0 == bytes
656 }
657}
658
659impl ExactSizeIterator for BinaryParser {
660 fn len(&self) -> usize {
661 self.0.len()
662 }
663}
664
665impl Iterator for BinaryParser {
666 type Item = u8;
667
668 fn next(&mut self) -> Option<Self::Item> {
669 if self.is_end(None) {
670 None
671 } else {
672 Some(self.read_uint8().expect("BinaryParser::next"))
673 }
674 }
675}
676
677#[cfg(test)]
678mod test {
679 use super::*;
680 use crate::alloc::string::ToString;
681 use alloc::string::String;
682
683 const TEST_HEX: &str = "00112233445566";
684
685 #[test]
686 fn test_binaryparser_from() {
687 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
688 let ref_bytes: &[u8] = test_bytes.as_ref();
689 let slice_parser = BinaryParser::from(ref_bytes);
690 let vec_parser = BinaryParser::from(test_bytes.to_owned());
691
692 assert_eq!(slice_parser, test_bytes[..]);
693 assert_eq!(vec_parser, test_bytes[..]);
694 }
695
696 #[test]
697 fn test_binaryparser_try_from() {
698 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
699 let string_parser = BinaryParser::try_from(TEST_HEX).unwrap();
700
701 assert_eq!(string_parser, test_bytes[..]);
702 }
703
704 #[test]
705 fn test_peek() {
706 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
707 let binary_parser = BinaryParser::from(test_bytes.as_ref());
708
709 assert_eq!(binary_parser.peek(), Some([test_bytes[0]; 1]));
710 }
711
712 #[test]
713 fn test_skip_bytes() {
714 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
715 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
716
717 assert!(binary_parser.skip_bytes(4).is_ok());
718 assert_eq!(binary_parser, test_bytes[4..]);
719 }
720
721 #[test]
722 fn test_read() {
723 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
724 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
725 let result = binary_parser.read(5);
726
727 assert!(result.is_ok());
728 assert_eq!(result.unwrap(), test_bytes[..5]);
729 }
730
731 #[test]
732 fn test_read_uint8() {
733 let test_hex: &str = "01000200000003";
734 let test_bytes: Vec<u8> = hex::decode(test_hex).expect("");
735 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
736 let result = binary_parser.read_uint8();
737
738 assert!(result.is_ok());
739 assert_eq!(result, Ok(1));
740 }
741
742 #[test]
743 fn test_read_uint16() {
744 let test_hex: &str = "000200000003";
745 let test_bytes: Vec<u8> = hex::decode(test_hex).expect("");
746 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
747 let result = binary_parser.read_uint16();
748
749 assert!(result.is_ok());
750 assert_eq!(result, Ok(2));
751 }
752
753 #[test]
754 fn test_read_uint32() {
755 let test_hex: &str = "00000003";
756 let test_bytes: Vec<u8> = hex::decode(test_hex).expect("");
757 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
758 let result = binary_parser.read_uint32();
759
760 assert!(result.is_ok());
761 assert_eq!(result, Ok(3));
762 }
763
764 #[test]
765 fn test_read_length_prefix() {
766 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
767 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
768 let result = binary_parser.read_length_prefix();
769
770 assert!(result.is_ok());
771 assert_eq!(result, Ok(0));
772 }
773
774 // TODO Finish tests
775 #[test]
776 fn test_read_field_header() {}
777
778 #[test]
779 fn test_read_field_value() {}
780
781 #[test]
782 fn test_read_field_and_value() {}
783
784 #[test]
785 fn test_read_type() {}
786
787 #[test]
788 fn accept_peek_skip_read() {
789 let test_bytes: Vec<u8> = hex::decode(TEST_HEX).expect("");
790 let mut binary_parser = BinaryParser::from(test_bytes.as_ref());
791
792 assert_eq!(binary_parser.peek(), Some([test_bytes[0]; 1]));
793 assert!(binary_parser.skip_bytes(3).is_ok());
794 assert_eq!(binary_parser, test_bytes[3..]);
795
796 let result = binary_parser.read(2);
797
798 assert!(result.is_ok());
799 assert_eq!(result.unwrap(), test_bytes[3..5]);
800 }
801
802 #[test]
803 fn test_binaryserializer_write_field_and_value() {
804 let field_header = FieldHeader {
805 type_code: -2,
806 field_code: 0,
807 };
808
809 let field_info = FieldInfo {
810 nth: 0,
811 is_vl_encoded: false,
812 is_serialized: false,
813 is_signing_field: false,
814 r#type: "Unknown".to_string(),
815 };
816
817 let field_instance = FieldInstance::new(&field_info, "Generic", field_header);
818 let expected: Vec<u8> = [224, 0, 17, 34].to_vec();
819 let test_bytes: Vec<u8> = [0, 17, 34].to_vec();
820 let mut serializer: BinarySerializer = BinarySerializer::new();
821
822 serializer.write_field_and_value(field_instance, &test_bytes, false);
823 assert_eq!(expected, serializer);
824 }
825
826 /// This is currently a sanity check for private
827 /// [`_encode_variable_length_prefix`], which is called by
828 /// BinarySerializer.write_length_encoded.
829 #[test]
830 fn test_encode_variable_length_prefix() {
831 for case in [100_usize, 1000, 20_000] {
832 let blob = (0..case).map(|_| "A2").collect::<String>();
833 let mut binary_serializer: BinarySerializer = BinarySerializer::new();
834
835 binary_serializer.write_length_encoded(&hex::decode(blob).expect(""), true);
836
837 let mut binary_parser: BinaryParser = BinaryParser::from(binary_serializer.as_ref());
838 let decoded_length = binary_parser.read_length_prefix();
839
840 assert!(decoded_length.is_ok());
841 assert_eq!(decoded_length, Ok(case));
842 }
843 }
844}