#![allow(clippy::missing_docs_in_private_items)]
#![allow(clippy::missing_errors_doc)]
#![cfg(test)]
use oct::serdes::{self, Serialise};
struct Test<const N: usize> {
buf: [u8; N],
}
impl<const N: usize> Test<N> {
#[must_use]
pub fn new() -> Self {
Self { buf: [0; N] }
}
fn serialise<T: Serialise>(&mut self, value: T) -> serdes::Result<&[u8]> {
let mut w = self.buf.as_mut_slice();
value.serialise(&mut w)?;
let remaining = w.len();
let written = self.buf.len() - remaining;
Ok(&self.buf[..written])
}
}
#[test]
fn test_serialise() {
let mut test = Test::<128>::new();
assert_eq!(
test.serialise(0x00_u8).unwrap(),
[0x00],
);
assert_eq!(
test.serialise(0xFF_u8).unwrap(),
[0xFF],
);
assert_eq!(
test.serialise(0x80_u8).unwrap(),
[0x80],
);
assert_eq!(
test.serialise(0x0F_7E_u16).unwrap(),
[0x7E, 0x0F],
);
assert_eq!(
test.serialise(0x00_2F_87_E7_u32).unwrap(),
[0xE7, 0x87, 0x2F, 0x00],
);
assert_eq!(
test.serialise(0xF3_37_CF_8B_DB_03_2B_39_u64).unwrap(),
[0x39, 0x2B, 0x03, 0xDB, 0x8B, 0xCF, 0x37, 0xF3],
);
assert_eq!(
test.serialise(0x45_A0_15_6A_36_77_17_8A_83_2E_3C_2C_84_10_58_1A_u128).unwrap(),
[
0x1A, 0x58, 0x10, 0x84, 0x2C, 0x3C, 0x2E, 0x83,
0x8A, 0x17, 0x77, 0x36, 0x6A, 0x15, 0xA0, 0x45,
],
);
assert_eq!(
test.serialise(0x1A4_usize).unwrap(),
[0xA4, 0x01],
);
test.serialise(0x10000_usize).unwrap_err();
assert_eq!(
test.serialise(['\u{03B4}', '\u{0190}', '\u{03BB}', '\u{03A4}', '\u{03B1}']).unwrap(),
[
0xB4, 0x03, 0x00, 0x00, 0x90, 0x01, 0x00, 0x00,
0xBB, 0x03, 0x00, 0x00, 0xA4, 0x03, 0x00, 0x00,
0xB1, 0x03, 0x00, 0x00,
],
);
assert_eq!(
test.serialise("A").unwrap(),
[0x01, 0x00, 0x41],
);
assert_eq!(
test.serialise("l\u{00F8}gma\u{00F0}ur").unwrap(),
[
0x0A, 0x00, 0x6C, 0xC3, 0xB8, 0x67, 0x6D, 0x61,
0xC3, 0xB0, 0x75, 0x72,
],
);
assert_eq!(
test.serialise(Result::<u16, char>::Ok(0x4545)).unwrap(),
[0x00, 0x45, 0x45],
);
assert_eq!(
test.serialise(Result::<u16, char>::Err(char::REPLACEMENT_CHARACTER)).unwrap(),
[0x01, 0xFD, 0xFF, 0x00, 0x00],
);
assert_eq!(
test.serialise(Option::<()>::None).unwrap(),
[0x00],
);
assert_eq!(
test.serialise(Option::<()>::Some(())).unwrap(),
[0x01],
);
}
#[cfg(feature = "proc_macro")]
#[test]
fn test_derive_serialise() {
#[derive(Serialise)]
#[repr(transparent)]
struct Foo(char);
#[repr(u8)]
#[derive(Serialise)]
enum Bar {
Unit = 0x45,
Pretty(bool) = 127,
Teacher { initials: [char; 0x3] },
}
let mut test = Test::<16>::new();
assert_eq!(
test.serialise(Foo('\u{FDF2}')).unwrap(),
[0xF2, 0xFD, 0x00, 0x00],
);
assert_eq!(
test.serialise(Bar::Unit).unwrap(),
[0x00],
);
assert_eq!(
test.serialise(Bar::Pretty(true)).unwrap(),
[0x01, 0x01],
);
assert_eq!(
test.serialise(Bar::Teacher { initials: ['T', 'L', '\0'] }).unwrap(),
[
0x02, 0x54, 0x00, 0x00, 0x00, 0x4C, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
],
);
}