xrpl_binary_codec 0.16.7

Binary serialization for XRPL Protocol objects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
use crate::alloc::{format, string::ToString, vec::Vec};
use crate::error::BinaryCodecError;
use crate::serializer::field_id::{FieldCode, FieldId, TypeCode};
use xrpl_types::{
    serialize::{Serialize, SerializeArray},
    AccountId, Amount, Blob, CurrencyCode, DropsAmount, Hash128, Hash160, Hash256, IssuedValue,
    UInt16, UInt32, UInt8, Uint64,
};

pub mod field_id;
pub mod field_info;

#[derive(Debug, Default)]
pub struct Serializer {
    /// Buffer in which fields are initially serialized. Fields are not sorted in this buffer
    buffer: Vec<u8>,
    /// Tracks which fields have been serialized to the buffer
    serialized_fields: Vec<SerializedFieldIndex>,
}

impl xrpl_types::serialize::Serializer for Serializer {
    type Error = BinaryCodecError;
    type SerializeArray<'a> = ArraySerializer<'a>;

    fn serialize_account_id(
        &mut self,
        field_name: &str,
        account_id: AccountId,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::AccountId, |ser| {
            ser.push_account_id(account_id)?;
            Ok(())
        })
    }

    fn serialize_amount(
        &mut self,
        field_name: &str,
        amount: Amount,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::Amount, |ser| {
            ser.push_amount(amount)?;
            Ok(())
        })
    }

    fn serialize_blob(&mut self, field_name: &str, blob: &Blob) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::Blob, |ser| {
            ser.push_blob(blob)?;
            Ok(())
        })
    }

    fn serialize_hash128(
        &mut self,
        field_name: &str,
        hash128: Hash128,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::Hash128, |ser| {
            ser.push_hash128(hash128)?;
            Ok(())
        })
    }

    fn serialize_hash160(
        &mut self,
        field_name: &str,
        hash160: Hash160,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::Hash160, |ser| {
            ser.push_hash160(hash160)?;
            Ok(())
        })
    }

    fn serialize_hash256(
        &mut self,
        field_name: &str,
        hash256: Hash256,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::Hash256, |ser| {
            ser.push_hash256(hash256)?;
            Ok(())
        })
    }

    fn serialize_uint8(&mut self, field_name: &str, uint8: UInt8) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::UInt8, |ser| {
            ser.push_uint8(uint8)?;
            Ok(())
        })
    }

    fn serialize_uint16(
        &mut self,
        field_name: &str,
        uint16: UInt16,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::UInt16, |ser| {
            ser.push_uint16(uint16)?;
            Ok(())
        })
    }

    fn serialize_uint32(
        &mut self,
        field_name: &str,
        uint32: UInt32,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::UInt32, |ser| {
            ser.push_uint32(uint32)?;
            Ok(())
        })
    }

    fn serialize_uint64(
        &mut self,
        field_name: &str,
        uint64: Uint64,
    ) -> Result<(), BinaryCodecError> {
        self.serialize_field(field_name, TypeCode::UInt64, |ser| {
            ser.push_uint64(uint64)?;
            Ok(())
        })
    }

    fn serialize_array(
        &mut self,
        field_name: &str,
    ) -> Result<Self::SerializeArray<'_>, Self::Error> {
        let start_index = self.start_field(field_name, TypeCode::Array)?;
        Ok(ArraySerializer {
            serializer: self,
            start_index,
        })
    }
}

#[derive(Debug)]
pub struct ArraySerializer<'a> {
    serializer: &'a mut Serializer,
    start_index: SerializeFieldStartIndex,
}

impl<'a> SerializeArray for ArraySerializer<'a> {
    type Error = BinaryCodecError;

    fn serialize_object<T: Serialize>(
        &mut self,
        field_name: &str,
        object: &T,
    ) -> Result<(), Self::Error> {
        let field_id = field_id(field_name, TypeCode::Object)?;
        self.serializer.push_field_id(field_id)?;
        let mut object_serializer = Serializer::new();
        object.serialize(&mut object_serializer)?;
        self.serializer
            .push_slice(&object_serializer.into_bytes()?)?;
        self.serializer
            .push_field_id(FieldId::from_type_field(TypeCode::Object, FieldCode(1)))?;
        Ok(())
    }

    fn end(self) -> Result<(), Self::Error> {
        self.serializer
            .push_field_id(FieldId::from_type_field(TypeCode::Array, FieldCode(1)))?;
        self.serializer.end_field(self.start_index);
        Ok(())
    }
}

/// Represents a field serialized to to the buffer
#[derive(Debug)]
struct SerializedFieldIndex {
    /// id of the serialized field
    field_id: FieldId,
    /// index of serialized bytes in buffer
    index: usize,
    /// length of serialized bytes
    length: usize,
}

/// Represents that serialization of a field to the buffer has been started
#[derive(Debug)]
struct SerializeFieldStartIndex {
    /// id of the serialized field
    field_id: FieldId,
    /// index of serialized bytes in buffer
    index: usize,
}

impl SerializeFieldStartIndex {
    fn new(field_id: FieldId, index: usize) -> Self {
        Self { field_id, index }
    }

    fn end(self, end_index: usize) -> SerializedFieldIndex {
        SerializedFieldIndex {
            field_id: self.field_id,
            index: self.index,
            length: end_index - self.index,
        }
    }
}

impl Serializer {
    pub fn new() -> Self {
        Self {
            buffer: Vec::new(),
            serialized_fields: Vec::new(),
        }
    }

    pub fn into_bytes(self) -> Result<Vec<u8>, BinaryCodecError> {
        let mut bytes = Vec::with_capacity(self.buffer.len());
        let mut serialized_fields = self.serialized_fields;
        serialized_fields.sort_by_key(|f| f.field_id);
        for field_pair in serialized_fields.windows(2) {
            if field_pair[0].field_id == field_pair[1].field_id {
                return Err(BinaryCodecError::FieldOrder(
                    "Two fields with same id".to_string(),
                ));
            }
        }
        for field in serialized_fields {
            bytes.extend_from_slice(&self.buffer[field.index..field.index + field.length]);
        }
        Ok(bytes)
    }

    fn start_field(
        &mut self,
        field_name: &str,
        field_type: TypeCode,
    ) -> Result<SerializeFieldStartIndex, BinaryCodecError> {
        let field_id = field_id(field_name, field_type)?;
        let start_index = SerializeFieldStartIndex::new(field_id, self.buffer.len());
        self.push_field_id(field_id)?;
        Ok(start_index)
    }

    fn end_field(&mut self, start_index: SerializeFieldStartIndex) {
        let index = start_index.end(self.buffer.len());
        self.serialized_fields.push(index);
    }

    fn serialize_field(
        &mut self,
        field_name: &str,
        field_type: TypeCode,
        serialize_field_data_closure: impl FnOnce(&mut Serializer) -> Result<(), BinaryCodecError>,
    ) -> Result<(), BinaryCodecError> {
        let start_index = self.start_field(field_name, field_type)?;
        serialize_field_data_closure(self)?;
        self.end_field(start_index);

        Ok(())
    }

    fn push(&mut self, value: u8) -> Result<(), BinaryCodecError> {
        self.push_slice(&[value])
    }

    fn push_slice(&mut self, bytes: &[u8]) -> Result<(), BinaryCodecError> {
        self.buffer.extend_from_slice(bytes);
        Ok(())
    }

    fn push_uint8(&mut self, value: UInt8) -> Result<(), BinaryCodecError> {
        self.push(value)
    }

    fn push_uint16(&mut self, value: UInt16) -> Result<(), BinaryCodecError> {
        self.push_slice(&value.to_be_bytes())
    }

    fn push_uint32(&mut self, value: UInt32) -> Result<(), BinaryCodecError> {
        self.push_slice(&value.to_be_bytes())
    }

    fn push_uint64(&mut self, value: Uint64) -> Result<(), BinaryCodecError> {
        self.push_slice(&value.to_be_bytes())
    }

    fn push_hash128(&mut self, value: Hash128) -> Result<(), BinaryCodecError> {
        self.push_slice(&value.0)
    }

    fn push_hash160(&mut self, value: Hash160) -> Result<(), BinaryCodecError> {
        self.push_slice(&value.0)
    }

    fn push_hash256(&mut self, value: Hash256) -> Result<(), BinaryCodecError> {
        self.push_slice(&value.0)
    }

    fn push_blob(&mut self, blob: &Blob) -> Result<(), BinaryCodecError> {
        self.push_vl_prefix(blob.0.len())?;
        self.push_slice(&blob.0)?;
        Ok(())
    }

    /// Push field id <https://xrpl.org/serialization.html#field-ids>
    fn push_field_id(&mut self, field_id: FieldId) -> Result<(), BinaryCodecError> {
        // rippled implementation: https://github.com/seelabs/rippled/blob/cecc0ad75849a1d50cc573188ad301ca65519a5b/src/ripple/protocol/impl/Serializer.cpp#L117-L148
        let header: Vec<u8> = field_id.into();
        self.push_slice(&header)
    }

    /// Push length prefix according to <https://xrpl.org/serialization.html#length-prefixing>
    fn push_vl_prefix(&mut self, length: usize) -> Result<(), BinaryCodecError> {
        if length <= 192 {
            self.push(length as u8)?;
            Ok(())
        } else if length <= 12480 {
            let length = length - 193;
            self.push(193 + (length >> 8) as u8)?;
            self.push((length & 0xff) as u8)?;
            Ok(())
        } else if length <= 918744 {
            let length = length - 12481;
            self.push(241 + (length >> 16) as u8)?;
            self.push(((length >> 8) & 0xff) as u8)?;
            self.push((length & 0xff) as u8)?;
            Ok(())
        } else {
            Err(BinaryCodecError::OutOfRange(format!(
                "Variable length out of range: {}",
                length
            )))
        }
    }

    /// <https://xrpl.org/serialization.html#amount-fields>
    fn push_drops_amount(&mut self, drops: DropsAmount) -> Result<(), BinaryCodecError> {
        const POSITIVE_MASK: u64 = 0x4000000000000000;
        self.push_uint64(POSITIVE_MASK | drops.drops())
    }

    /// <https://xrpl.org/serialization.html#issued-currency-amount-format>
    fn push_issued_value(&mut self, value: IssuedValue) -> Result<(), BinaryCodecError> {
        const ISSUED_MASK: u64 = 0x8000000000000000;
        const POSITIVE_MASK: u64 = 0x4000000000000000;

        let (mantissa, positive) = match value.mantissa() {
            0 => {
                self.push_uint64(ISSUED_MASK)?;
                return Ok(());
            }
            1.. => (value.mantissa() as u64, true),
            ..=-1 => (-value.mantissa() as u64, false),
        };
        let exponent = (value.exponent() + 97) as u64;
        self.push_uint64(
            ISSUED_MASK | (if positive { POSITIVE_MASK } else { 0 }) | mantissa | (exponent << 54),
        )?;
        Ok(())
    }

    fn push_amount(&mut self, amount: Amount) -> Result<(), BinaryCodecError> {
        match amount {
            Amount::Drops(drops) => self.push_drops_amount(drops),
            Amount::Issued(issued) => {
                self.push_issued_value(issued.value())?;
                self.push_currency_code(issued.currency())?;
                self.push_account_id_no_length_prefix(issued.issuer())?;
                Ok(())
            }
        }
    }

    /// <https://xrpl.org/serialization.html#currency-codes>
    fn push_currency_code(&mut self, currency_code: CurrencyCode) -> Result<(), BinaryCodecError> {
        match currency_code {
            CurrencyCode::Xrp => self.push_slice(&[0u8; 20]),
            CurrencyCode::Standard(code) => {
                self.push_slice(&[0u8; 12])?;
                self.push_slice(&code.as_bytes())?;
                self.push_slice(&[0u8; 5])?;
                Ok(())
            }
            CurrencyCode::NonStandard(code) => self.push_slice(code.as_bytes()),
        }
    }

    fn push_account_id(&mut self, id: AccountId) -> Result<(), BinaryCodecError> {
        self.push_vl_prefix(20).expect("20 is within valid range");
        self.push_slice(&id.0)
    }

    fn push_account_id_no_length_prefix(&mut self, id: AccountId) -> Result<(), BinaryCodecError> {
        self.push_slice(&id.0)
    }
}

pub fn field_id(field_name: &str, field_type: TypeCode) -> Result<FieldId, BinaryCodecError> {
    let field_info = field_info::field_info(field_name).ok_or_else(|| {
        BinaryCodecError::InvalidField(format!("Field with name {} is not known", field_name))
    })?;
    if field_type != field_info.field_type {
        return Err(BinaryCodecError::InvalidField(format!(
            "Field with name {} must have type {}",
            field_name, field_info.field_type
        )));
    }
    Ok(FieldId::from_type_field(
        field_info.field_type,
        field_info.field_code,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use ascii::AsciiChar;
    use assert_matches::assert_matches;
    use enumflags2::BitFlags;
    use xrpl_types::serialize::{Serialize, Serializer};
    use xrpl_types::OfferCreateTransaction;

    fn serializer() -> super::Serializer {
        super::Serializer::new()
    }

    fn buffer(serializer: &super::Serializer) -> &[u8] {
        &serializer.buffer
    }

    struct TestObject {
        field1: UInt32,
        field2: UInt32,
    }

    impl Serialize for TestObject {
        fn serialize<S: Serializer>(&self, serializer: &mut S) -> Result<(), S::Error> {
            serializer.serialize_uint32("NetworkID", self.field1)?; // field code 1
            serializer.serialize_uint32("Flags", self.field2)?; // field code 2
            Ok(())
        }
    }

    struct TestObjectSerializeFieldsOutOfOrder {
        field1: UInt32,
        field2: UInt32,
    }

    impl Serialize for TestObjectSerializeFieldsOutOfOrder {
        fn serialize<S: Serializer>(&self, serializer: &mut S) -> Result<(), S::Error> {
            serializer.serialize_uint32("Flags", self.field2)?; // field code 2
            serializer.serialize_uint32("NetworkID", self.field1)?; // field code 1
            Ok(())
        }
    }

    #[test]
    fn test_push_uint8() {
        let mut s = serializer();
        let value = 0x12;
        s.push_uint8(value).unwrap();
        assert_eq!(buffer(&s), [0x12u8]);
    }

    #[test]
    fn test_push_uint16() {
        let mut s = serializer();
        let value = 0x12 + (0x34 << 8);
        s.push_uint16(value).unwrap();
        assert_eq!(buffer(&s), [0x34, 0x12]);
    }

    #[test]
    fn test_push_uint32() {
        let mut s = serializer();
        let value = 0x12 + (0x34 << 24);
        s.push_uint32(value).unwrap();
        assert_eq!(buffer(&s), [0x34, 0x00, 0x00, 0x12]);
    }

    #[test]
    fn test_push_uint64() {
        let mut s = serializer();
        let value = 0x12 + (0x34 << 56);
        s.push_uint64(value).unwrap();
        assert_eq!(buffer(&s), [0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12]);
    }

    #[test]
    fn test_push_h128() {
        let mut s = serializer();
        let value = Hash128([
            0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x12,
        ]);
        s.push_hash128(value).unwrap();
        assert_eq!(
            buffer(&s),
            [
                0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x12
            ]
        );
    }

    #[test]
    fn test_push_h160() {
        let mut s = serializer();
        let value = Hash160([
            0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
        ]);
        s.push_hash160(value).unwrap();
        assert_eq!(
            buffer(&s),
            [
                0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x12
            ]
        );
    }

    #[test]
    fn test_push_h256() {
        let mut s = serializer();
        let value = Hash256([
            0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x12,
        ]);
        s.push_hash256(value).unwrap();
        assert_eq!(
            buffer(&s),
            [
                0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x12
            ]
        );
    }

    #[test]
    fn test_push_blob() {
        let mut s = serializer();
        let value = Blob(vec![0x34, 0x00, 0x12]);
        s.push_blob(&value).unwrap();
        assert_eq!(buffer(&s), [3, 0x34, 0x00, 0x12]);
    }

    #[test]
    fn test_push_account_id() {
        let mut s = serializer();
        let value = AccountId([
            0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
        ]);
        s.push_account_id(value).unwrap();
        assert_eq!(
            buffer(&s),
            [
                20, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12
            ]
        );
    }

    #[test]
    fn test_push_account_id_no_length_prefix() {
        let mut s = serializer();
        let value = AccountId([
            0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
        ]);
        s.push_account_id_no_length_prefix(value).unwrap();
        assert_eq!(
            buffer(&s),
            [
                0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x12
            ]
        );
    }

    /// Tests length prefix according to <https://xrpl.org/serialization.html#length-prefixing>
    #[test]
    #[allow(clippy::erasing_op, clippy::identity_op)]
    fn test_push_vl_prefix() {
        // test range 0 to 192
        let mut s = serializer();
        s.push_vl_prefix(0).unwrap();
        s.push_vl_prefix(1).unwrap();
        s.push_vl_prefix(192).unwrap();
        assert_eq!(buffer(&s), [0, 1, 192]);

        // test range 193 to 12480
        let mut s = serializer();
        s.push_vl_prefix(193 + ((193 - 193) * 256) + 0).unwrap();
        s.push_vl_prefix(193 + ((193 - 193) * 256) + 1).unwrap();
        assert_eq!(193 + ((240 - 193) * 256) + 255, 12480);
        s.push_vl_prefix(193 + ((240 - 193) * 256) + 255).unwrap();
        assert_eq!(buffer(&s), [193, 0, 193, 1, 240, 255]);

        // test range 12481 to 918744
        let mut s = serializer();
        s.push_vl_prefix(12481 + ((241 - 241) * 65536) + (0 * 256) + 0)
            .unwrap();
        s.push_vl_prefix(12481 + ((241 - 241) * 65536) + (0 * 256) + 1)
            .unwrap();
        s.push_vl_prefix(12481 + ((241 - 241) * 65536) + (1 * 256) + 0)
            .unwrap();
        s.push_vl_prefix(12481 + ((241 - 241) * 65536) + (255 * 256) + 255)
            .unwrap();
        assert_eq!(12481 + ((254 - 241) * 65536) + (212 * 256) + 23, 918744);
        s.push_vl_prefix(12481 + ((254 - 241) * 65536) + (212 * 256) + 23)
            .unwrap();
        assert_eq!(
            buffer(&s),
            [241, 0, 0, 241, 0, 1, 241, 1, 0, 241, 255, 255, 254, 212, 23]
        );

        // test out of range
        let mut s = serializer();
        let result = s.push_vl_prefix(918745);
        assert_matches!(result, Err(BinaryCodecError::OutOfRange(message)) => {
            assert!(message.contains("Variable length out of range"), "message: {}", message);
        });
    }

    #[test]
    fn test_push_currency_code_xrp() {
        let mut s = serializer();
        let code = CurrencyCode::xrp();
        s.push_currency_code(code).unwrap();
        assert_eq!(buffer(&s), [0u8; 20]);
    }

    #[test]
    fn test_push_currency_code_standard() {
        let mut s = serializer();
        let code = CurrencyCode::standard([AsciiChar::U, AsciiChar::S, AsciiChar::D]).unwrap();
        s.push_currency_code(code).unwrap();
        let bytes = buffer(&s);
        assert_eq!(bytes[0..12], [0u8; 12]);
        assert_eq!(
            bytes[12..15],
            [
                AsciiChar::U.as_byte(),
                AsciiChar::S.as_byte(),
                AsciiChar::D.as_byte()
            ]
        );
        assert_eq!(bytes[15..20], [0u8; 5]);
    }

    #[test]
    fn test_push_currency_code_non_standard() {
        let mut s = serializer();
        let code = CurrencyCode::non_standard([
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
        ])
        .unwrap();
        s.push_currency_code(code).unwrap();
        assert_eq!(
            buffer(&s),
            [
                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
            ]
        );
    }

    #[test]
    fn test_push_drops_amount() {
        let mut s = serializer();
        let value = DropsAmount::from_drops(10_000).unwrap();
        s.push_drops_amount(value).unwrap();
        assert_eq!(buffer(&s), [0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x27, 0x10]);
    }

    /// Test serializing zero issued value
    #[test]
    fn test_push_issued_value_zero() {
        let mut s = serializer();
        let value = IssuedValue::zero();
        s.push_issued_value(value).unwrap();
        assert_eq!(buffer(&s), [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
    }

    /// Test serializing positive issued value
    #[test]
    fn test_push_issued_value_positive() {
        let mut s = serializer();
        let value = IssuedValue::from_mantissa_exponent(1_000_000_000_000_000, -10).unwrap();
        s.push_issued_value(value).unwrap();
        let bytes = buffer(&s);
        assert_eq!(
            bytes,
            [0xD5, 0xC3, 0x8D, 0x7E, 0xA4, 0xC6, 0x80, 0x00,],
            "actual: {}",
            hex::encode(bytes),
        );
    }

    /// Test serializing negative issued value
    #[test]
    fn test_push_issued_value_negative() {
        let mut s = serializer();
        let value = IssuedValue::from_mantissa_exponent(-1_000_000_000_000_000, -10).unwrap();
        s.push_issued_value(value).unwrap();
        let bytes = buffer(&s);
        assert_eq!(
            bytes,
            [0x95, 0xC3, 0x8D, 0x7E, 0xA4, 0xC6, 0x80, 0x00,],
            "actual: {}",
            hex::encode(bytes),
        );
    }

    #[test]
    fn test_push_amount_drops() {
        let mut s = serializer();
        let value = Amount::drops(10_000).unwrap();
        s.push_amount(value).unwrap();
        assert_eq!(buffer(&s), [0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x27, 0x10]);
    }

    #[test]
    fn test_push_amount_issued() {
        let mut s = serializer();
        let value = IssuedValue::from_mantissa_exponent(1_000_000_000_000_000, -10).unwrap();
        let currency = CurrencyCode::non_standard([
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
        ])
        .unwrap();
        let issuer = AccountId([
            0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
        ]);
        let amount = Amount::issued(value, currency, issuer).unwrap();
        s.push_amount(amount).unwrap();
        let bytes = buffer(&s);
        assert_eq!(
            bytes,
            [
                0xD5, 0xC3, 0x8D, 0x7E, 0xA4, 0xC6, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
                0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x12
            ],
            "actual: {}",
            hex::encode(bytes),
        );
    }

    #[test]
    fn test_push_field_id_4bit_type_4bit_field() {
        let mut s = serializer();
        let field_id = FieldId::from_type_field(TypeCode::UInt32, FieldCode(0b0100));
        s.push_field_id(field_id).unwrap();
        assert_eq!(buffer(&s), [0b0010_0100]);
    }

    #[test]
    fn test_push_field_id_4bit_type_8bit_field() {
        let mut s = serializer();
        let field_id = FieldId::from_type_field(TypeCode::UInt32, FieldCode(0b0001_0100));
        s.push_field_id(field_id).unwrap();
        assert_eq!(buffer(&s), [0b0010_0000, 0b0001_0100]);
    }

    #[test]
    fn test_push_field_id_8bit_type_8bit_field() {
        let mut s = serializer();
        let field_id = FieldId::from_type_field(TypeCode::Hash160, FieldCode(0b0001_0100));
        s.push_field_id(field_id).unwrap();
        assert_eq!(buffer(&s), [0, 0b0001_0001, 0b0001_0100]);
    }

    #[test]
    fn test_push_field_id_8bit_type_4bit_field() {
        let mut s = serializer();
        let field_id = FieldId::from_type_field(TypeCode::Hash160, FieldCode(0b0100));
        s.push_field_id(field_id).unwrap();
        assert_eq!(buffer(&s), [0b0000_0100, 0b0001_0001]);
    }

    /// Test pushing array of objects
    #[test]
    fn test_push_empty_array() {
        let mut s = serializer();
        let array = s.serialize_array("Memos").unwrap(); // field code 9
        array.end().unwrap();
        assert_eq!(buffer(&s), [0b1111_1001, 0b1111_0001]);
    }

    /// Test pushing array of objects
    #[test]
    fn test_push_array() {
        let mut s = serializer();
        let object1 = TestObject {
            field1: 12,
            field2: 23,
        };
        let object2 = TestObject {
            field1: 34,
            field2: 45,
        };
        let mut array = s.serialize_array("Memos").unwrap(); // field code 9
        array.serialize_object("Memo", &object1).unwrap(); // field code 10
        array.serialize_object("Memo", &object2).unwrap(); // field code 10
        array.end().unwrap();
        assert_eq!(
            buffer(&s),
            [
                0b1111_1001,
                0b1110_1010,
                0b0010_0001,
                0,
                0,
                0,
                12,
                0b0010_0010,
                0,
                0,
                0,
                23,
                0b1110_0001,
                0b1110_1010,
                0b0010_0001,
                0,
                0,
                0,
                34,
                0b0010_0010,
                0,
                0,
                0,
                45,
                0b1110_0001,
                0b1111_0001
            ]
        );
    }

    /// Test pushing array of objects with out of order fields
    #[test]
    fn test_push_array_out_of_order_fields() {
        let mut s = serializer();
        let object1 = TestObjectSerializeFieldsOutOfOrder {
            field1: 12,
            field2: 23,
        };
        let object2 = TestObjectSerializeFieldsOutOfOrder {
            field1: 34,
            field2: 45,
        };
        let mut array = s.serialize_array("Memos").unwrap(); // field code 9
        array.serialize_object("Memo", &object1).unwrap(); // field code 10
        array.serialize_object("Memo", &object2).unwrap(); // field code 10
        array.end().unwrap();
        assert_eq!(
            buffer(&s),
            [
                0b1111_1001,
                0b1110_1010,
                0b0010_0001,
                0,
                0,
                0,
                12,
                0b0010_0010,
                0,
                0,
                0,
                23,
                0b1110_0001,
                0b1110_1010,
                0b0010_0001,
                0,
                0,
                0,
                34,
                0b0010_0010,
                0,
                0,
                0,
                45,
                0b1110_0001,
                0b1111_0001
            ]
        );
    }

    /// Test serialize fields (in correct order)
    #[test]
    fn test_serialize_fields() {
        let mut s = serializer();
        s.serialize_uint32("NetworkID", 12).unwrap(); // field code 1
        s.serialize_uint32("Flags", 23).unwrap(); // field code 2
        s.serialize_uint64("IndexNext", 34).unwrap(); // field code 1
        assert_eq!(
            s.into_bytes().unwrap(),
            [
                0b0010_0001,
                0,
                0,
                0,
                12,
                0b0010_0010,
                0,
                0,
                0,
                23,
                0b0011_0001,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                34
            ]
        );
    }

    /// Test serialize fields out of order
    #[test]
    fn test_serialize_fields_type_code_order() {
        let mut s = serializer();
        s.serialize_uint64("IndexNext", 34).unwrap(); // field code 1
        s.serialize_uint32("NetworkID", 12).unwrap(); // field code 1
        assert_eq!(
            s.into_bytes().unwrap(),
            [
                0b0010_0001,
                0,
                0,
                0,
                12,
                0b0011_0001,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                34
            ]
        );
    }

    /// Test serialize fields out of order
    #[test]
    fn test_serialize_fields_field_code_order() {
        let mut s = serializer();
        s.serialize_uint32("Flags", 23).unwrap(); // field code 2
        s.serialize_uint32("NetworkID", 12).unwrap(); // field code 1
        assert_eq!(
            s.into_bytes().unwrap(),
            [0b0010_0001, 0, 0, 0, 12, 0b0010_0010, 0, 0, 0, 23,]
        );
    }

    /// Test serialize fields where field ordering is wrong
    #[test]
    fn test_serialize_fields_same_field_id() {
        let mut s = serializer();
        s.serialize_uint32("Flags", 34).unwrap();
        let result = s.serialize_uint32("Flags", 12).and_then(|_| s.into_bytes());
        assert_matches!(result, Err(BinaryCodecError::FieldOrder(message)) => {
            assert!(message.contains("Two fields with same id"), "message: {}", message);
        });
    }

    /// Tests the example <https://xrpl.org/serialization.html#examples>
    #[test]
    fn test_serialize_offer_create() {
        let mut s = serializer();
        let mut tx = OfferCreateTransaction::new(
            AccountId::from_address("rMBzp8CgpE441cp5PVyA9rpVV7oT8hP3ys").unwrap(),
            Amount::drops(15000000000).unwrap(),
            Amount::issued(
                IssuedValue::from_mantissa_exponent(70728, -1).unwrap(),
                CurrencyCode::standard([AsciiChar::U, AsciiChar::S, AsciiChar::D]).unwrap(),
                AccountId::from_address("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B").unwrap(),
            )
            .unwrap(),
        );
        tx.common.fee = Some(DropsAmount::from_drops(10).unwrap());
        tx.common.sequence = Some(1752792);
        tx.common.signing_pub_key = Some(Blob(
            hex::decode("03EE83BB432547885C219634A1BC407A9DB0474145D69737D09CCDC63E1DEE7FE3")
                .unwrap(),
        ));
        tx.common.txn_signature = Some(Blob(hex::decode("30440220143759437C04F7B61F012563AFE90D8DAFC46E86035E1D965A9CED282C97D4CE02204CFD241E86F17E011298FC1A39B63386C74306A5DE047E213B0F29EFA4571C2C").unwrap()));
        tx.expiration = Some(595640108);
        tx.flags = BitFlags::from_bits(524288).unwrap();
        tx.offer_sequence = Some(1752791);

        tx.serialize(&mut s).unwrap();
        assert_eq!(hex::encode_upper(s.into_bytes().unwrap()), "120007220008000024001ABED82A2380BF2C2019001ABED764D55920AC9391400000000000000000000000000055534400000000000A20B3C85F482532A9578DBB3950B85CA06594D165400000037E11D60068400000000000000A732103EE83BB432547885C219634A1BC407A9DB0474145D69737D09CCDC63E1DEE7FE3744630440220143759437C04F7B61F012563AFE90D8DAFC46E86035E1D965A9CED282C97D4CE02204CFD241E86F17E011298FC1A39B63386C74306A5DE047E213B0F29EFA4571C2C8114DD76483FACDEE26E60D8A586BB58D09F27045C46");
    }
}