| 1 |
#![cfg(feature = "borsh")] |
| 2 |
use std::fmt; |
| 3 |
extern crate arrayvec; |
| 4 |
extern crate borsh; |
| 5 |
|
| 6 |
fn assert_ser<T: borsh::BorshSerialize>(v: &T, expected_bytes: &[u8]) { |
| 7 |
let mut actual_bytes = Vec::new(); |
| 8 |
v.serialize(&mut actual_bytes).unwrap(); |
| 9 |
assert_eq!(actual_bytes, expected_bytes); |
| 10 |
} |
| 11 |
|
| 12 |
fn assert_roundtrip<T: borsh::BorshSerialize + borsh::BorshDeserialize + PartialEq + fmt::Debug>(v: &T) { |
| 13 |
let mut bytes = Vec::new(); |
| 14 |
v.serialize(&mut bytes).unwrap(); |
| 15 |
let v_de = T::try_from_slice(&bytes).unwrap(); |
| 16 |
assert_eq!(*v, v_de); |
| 17 |
} |
| 18 |
|
| 19 |
mod array_vec { |
| 20 |
use arrayvec::ArrayVec; |
| 21 |
use super::{assert_ser, assert_roundtrip}; |
| 22 |
|
| 23 |
#[test] |
| 24 |
fn test_empty() { |
| 25 |
let vec = ArrayVec::<u32, 0>::new(); |
| 26 |
assert_ser(&vec, b"\0\0\0\0"); |
| 27 |
assert_roundtrip(&vec); |
| 28 |
} |
| 29 |
|
| 30 |
#[test] |
| 31 |
fn test_full() { |
| 32 |
let mut vec = ArrayVec::<u32, 3>::new(); |
| 33 |
vec.push(0xdeadbeef); |
| 34 |
vec.push(0x123); |
| 35 |
vec.push(0x456); |
| 36 |
assert_ser(&vec, b"\x03\0\0\0\xef\xbe\xad\xde\x23\x01\0\0\x56\x04\0\0"); |
| 37 |
assert_roundtrip(&vec); |
| 38 |
} |
| 39 |
|
| 40 |
#[test] |
| 41 |
fn test_with_free_capacity() { |
| 42 |
let mut vec = ArrayVec::<u32, 3>::new(); |
| 43 |
vec.push(0xdeadbeef); |
| 44 |
assert_ser(&vec, b"\x01\0\0\0\xef\xbe\xad\xde"); |
| 45 |
assert_roundtrip(&vec); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
mod array_string { |
| 50 |
use arrayvec::ArrayString; |
| 51 |
use super::{assert_ser, assert_roundtrip}; |
| 52 |
|
| 53 |
#[test] |
| 54 |
fn test_empty() { |
| 55 |
let string = ArrayString::<0>::new(); |
| 56 |
assert_ser(&string, b"\0\0\0\0"); |
| 57 |
assert_roundtrip(&string); |
| 58 |
} |
| 59 |
|
| 60 |
#[test] |
| 61 |
fn test_full() { |
| 62 |
let string = ArrayString::from_byte_string(b"hello world").unwrap(); |
| 63 |
assert_ser(&string, b"\x0b\0\0\0hello world"); |
| 64 |
assert_roundtrip(&string); |
| 65 |
} |
| 66 |
|
| 67 |
#[test] |
| 68 |
fn test_with_free_capacity() { |
| 69 |
let string = ArrayString::<16>::from("hello world").unwrap(); |
| 70 |
assert_ser(&string, b"\x0b\0\0\0hello world"); |
| 71 |
assert_roundtrip(&string); |
| 72 |
} |
| 73 |
} |