File: borsh.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (73 lines) | stat: -rw-r--r-- 1,985 bytes parent folder | download | duplicates (12)
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
#![cfg(feature = "borsh")]
use std::fmt;
extern crate arrayvec;
extern crate borsh;

fn assert_ser<T: borsh::BorshSerialize>(v: &T, expected_bytes: &[u8]) {
    let mut actual_bytes = Vec::new();
    v.serialize(&mut actual_bytes).unwrap();
    assert_eq!(actual_bytes, expected_bytes);
}

fn assert_roundtrip<T: borsh::BorshSerialize + borsh::BorshDeserialize + PartialEq + fmt::Debug>(v: &T) {
    let mut bytes = Vec::new();
    v.serialize(&mut bytes).unwrap();
    let v_de = T::try_from_slice(&bytes).unwrap();
    assert_eq!(*v, v_de);
}

mod array_vec {
    use arrayvec::ArrayVec;
    use super::{assert_ser, assert_roundtrip};

    #[test]
    fn test_empty() {
        let vec = ArrayVec::<u32, 0>::new();
        assert_ser(&vec, b"\0\0\0\0");
        assert_roundtrip(&vec);
    }

    #[test]
    fn test_full() {
        let mut vec = ArrayVec::<u32, 3>::new();
        vec.push(0xdeadbeef);
        vec.push(0x123);
        vec.push(0x456);
        assert_ser(&vec, b"\x03\0\0\0\xef\xbe\xad\xde\x23\x01\0\0\x56\x04\0\0");
        assert_roundtrip(&vec);
    }

    #[test]
    fn test_with_free_capacity() {
        let mut vec = ArrayVec::<u32, 3>::new();
        vec.push(0xdeadbeef);
        assert_ser(&vec, b"\x01\0\0\0\xef\xbe\xad\xde");
        assert_roundtrip(&vec);
    }
}

mod array_string {
    use arrayvec::ArrayString;
    use super::{assert_ser, assert_roundtrip};

    #[test]
    fn test_empty() {
        let string = ArrayString::<0>::new();
        assert_ser(&string, b"\0\0\0\0");
        assert_roundtrip(&string);
    }

    #[test]
    fn test_full() {
        let string = ArrayString::from_byte_string(b"hello world").unwrap();
        assert_ser(&string, b"\x0b\0\0\0hello world");
        assert_roundtrip(&string);
    }

    #[test]
    fn test_with_free_capacity() {
        let string = ArrayString::<16>::from("hello world").unwrap();
        assert_ser(&string, b"\x0b\0\0\0hello world");
        assert_roundtrip(&string);
    }
}