nibblecode 0.1.0

A serialization format based on rkyv
Documentation
use core::fmt::Debug;

use crate::test::to_bytes;
use crate::{Serialize, access_mut};

/// Serializes the given type to bytes, accesses the archived version, and calls
/// the given function with it.
pub fn to_archived<T: Serialize>(value: &T, f: impl FnOnce(&mut T::Archived)) {
	to_bytes(value, |bytes| to_archived_from_bytes::<T>(bytes, f));
}

/// Accesses the archived version and calls the given function with it.
pub fn to_archived_from_bytes<T: Serialize>(bytes: &mut [u8], f: impl FnOnce(&mut T::Archived)) {
	let archived_value = access_mut::<T>(bytes).unwrap();
	f(archived_value);
}

/// Serializes and deserializes the given value, checking for equality with the
/// archived and deserialized values using the given comparison function.
pub fn roundtrip_with<T: Debug + Serialize<Archived: Debug>>(
	value: &T,
	cmp: impl Fn(&T, &T::Archived),
) {
	to_archived(value, |archived_value| cmp(value, &*archived_value));
}

/// Serializes and deserializes the given value, checking for equality with the
/// archived and deserialized values.
pub fn roundtrip<T: Debug + Serialize<Archived: Debug + PartialEq<T>>>(value: &T) {
	roundtrip_with(value, |a, b| assert_eq!(b, a));
}