const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
const FNV_PRIME: u64 = 0x100000001b3;
const fn fnv1a(bytes: &[u8], mut hash: u64) -> u64 {
let mut i = 0;
while i < bytes.len() {
hash ^= bytes[i] as u64;
hash = hash.wrapping_mul(FNV_PRIME);
i += 1;
}
hash
}
#[doc(hidden)]
pub const fn fold_unordered(hashes: &[u64]) -> u64 {
let mut acc = 0u64;
let mut i = 0;
while i < hashes.len() {
acc = acc.wrapping_add(hashes[i]);
i += 1;
}
acc
}
pub trait WireFingerprint {
const WIRE_FINGERPRINT: u64;
}
#[derive(Clone, Copy)]
pub enum FingerprintTag {
FixedInt,
Float,
Bool,
Sequence,
Struct,
Enum,
}
impl FingerprintTag {
const fn wire_value(self) -> u8 {
match self {
Self::FixedInt => 0,
Self::Float => 1,
Self::Bool => 2,
Self::Sequence => 3,
Self::Struct => 4,
Self::Enum => 5,
}
}
}
#[derive(Clone, Copy)]
pub enum Signedness {
Unsigned,
Signed,
}
impl Signedness {
const fn wire_value(self) -> u8 {
match self {
Self::Unsigned => 0,
Self::Signed => 1,
}
}
}
#[derive(Clone, Copy)]
pub enum Endianness {
Little,
Big,
}
impl Endianness {
const fn wire_value(self) -> u8 {
match self {
Self::Little => 0,
Self::Big => 1,
}
}
}
#[derive(Clone, Copy)]
pub enum Constraint {
None,
NonZero,
NotNan,
UnicodeScalar,
Utf8,
}
impl Constraint {
const fn wire_value(self) -> u8 {
match self {
Self::None => 0,
Self::NonZero => 1,
Self::NotNan => 2,
Self::UnicodeScalar => 3,
Self::Utf8 => 4,
}
}
}
#[derive(Clone, Copy)]
enum FingerprintSlot {
Tag,
Width,
Signedness,
Endianness,
Constraint,
LenBound,
Nested,
DiscriminantTag,
Variants,
}
impl FingerprintSlot {
const fn wire_value(self) -> u8 {
match self {
Self::Tag => 0,
Self::Width => 1,
Self::Signedness => 2,
Self::Endianness => 3,
Self::Constraint => 4,
Self::LenBound => 5,
Self::Nested => 6,
Self::DiscriminantTag => 7,
Self::Variants => 8,
}
}
}
pub struct FingerprintBuilder(u64);
impl FingerprintBuilder {
pub const fn new() -> Self {
Self(FNV_OFFSET_BASIS)
}
const fn fold_bytes(self, bytes: &[u8]) -> Self {
Self(fnv1a(bytes, self.0))
}
const fn fold_u64(self, v: u64) -> Self {
self.fold_bytes(&v.to_le_bytes())
}
const fn fold_slot(self, s: FingerprintSlot) -> Self {
self.fold_bytes(&[s.wire_value()])
}
pub const fn tag(self, t: FingerprintTag) -> Self {
self.fold_slot(FingerprintSlot::Tag)
.fold_bytes(&[t.wire_value()])
}
pub const fn nested<T: WireFingerprint>(self) -> Self {
self.fold_slot(FingerprintSlot::Nested)
.fold_u64(T::WIRE_FINGERPRINT)
}
pub const fn signedness(self, s: Signedness) -> Self {
self.fold_slot(FingerprintSlot::Signedness)
.fold_bytes(&[s.wire_value()])
}
pub const fn endianness(self, e: Endianness) -> Self {
self.fold_slot(FingerprintSlot::Endianness)
.fold_bytes(&[e.wire_value()])
}
pub const fn constraint(self, c: Constraint) -> Self {
self.fold_slot(FingerprintSlot::Constraint)
.fold_bytes(&[c.wire_value()])
}
pub const fn width(self, bytes: u8) -> Self {
self.fold_slot(FingerprintSlot::Width).fold_bytes(&[bytes])
}
pub const fn len_bound(self, bound: u64) -> Self {
self.fold_slot(FingerprintSlot::LenBound).fold_u64(bound)
}
pub const fn discriminant_tag(self, v: u128) -> Self {
self.fold_slot(FingerprintSlot::DiscriminantTag)
.fold_bytes(&v.to_le_bytes())
}
pub const fn variants(self, hashes: &[u64]) -> Self {
self.fold_slot(FingerprintSlot::Variants)
.fold_u64(fold_unordered(hashes))
.fold_u64(hashes.len() as u64)
}
pub const fn finish(self) -> u64 {
self.0
}
}
impl Default for FingerprintBuilder {
fn default() -> Self {
Self::new()
}
}
#[diagnostic::on_unimplemented(
message = "byteable: wire-format fingerprint mismatch (asserted {EXPECTED}, actual {ACTUAL})",
label = "asserted fingerprint {EXPECTED} does not match this type's actual fingerprint {ACTUAL}",
note = "if this change was intentional, replace the asserted value with {ACTUAL}"
)]
#[doc(hidden)]
pub trait FingerprintEq<const EXPECTED: u64, const ACTUAL: u64> {}
#[doc(hidden)]
impl<const N: u64> FingerprintEq<N, N> for () {}
#[doc(hidden)]
pub const fn assert_fingerprint<const EXPECTED: u64, const ACTUAL: u64>()
where
(): FingerprintEq<EXPECTED, ACTUAL>,
{
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn same_inputs_produce_same_hash() {
let a = FingerprintBuilder::new()
.tag(FingerprintTag::FixedInt)
.width(4)
.finish();
let b = FingerprintBuilder::new()
.tag(FingerprintTag::FixedInt)
.width(4)
.finish();
assert_eq!(a, b);
}
#[test]
fn different_tags_produce_different_hashes() {
let a = FingerprintBuilder::new()
.tag(FingerprintTag::FixedInt)
.finish();
let b = FingerprintBuilder::new()
.tag(FingerprintTag::Float)
.finish();
assert_ne!(a, b);
}
#[test]
fn different_methods_with_equal_values_do_not_collide() {
let a = FingerprintBuilder::new().width(1).finish();
let b = FingerprintBuilder::new()
.constraint(Constraint::NonZero)
.finish();
assert_ne!(a, b);
}
#[test]
fn discriminant_tag_distinguishes_high_and_low_bits() {
let a = FingerprintBuilder::new().discriminant_tag(1).finish();
let b = FingerprintBuilder::new()
.discriminant_tag(1u128 + (1u128 << 64))
.finish();
assert_ne!(a, b);
}
#[test]
fn fingerprint_slot_wire_values_are_stable_by_construction() {
assert_eq!(FingerprintSlot::Tag.wire_value(), 0);
assert_eq!(FingerprintSlot::Width.wire_value(), 1);
assert_eq!(FingerprintSlot::Signedness.wire_value(), 2);
assert_eq!(FingerprintSlot::Endianness.wire_value(), 3);
assert_eq!(FingerprintSlot::Constraint.wire_value(), 4);
assert_eq!(FingerprintSlot::LenBound.wire_value(), 5);
assert_eq!(FingerprintSlot::Nested.wire_value(), 6);
assert_eq!(FingerprintSlot::DiscriminantTag.wire_value(), 7);
assert_eq!(FingerprintSlot::Variants.wire_value(), 8);
}
#[test]
fn different_widths_produce_different_hashes() {
let a = FingerprintBuilder::new()
.tag(FingerprintTag::FixedInt)
.width(4)
.finish();
let b = FingerprintBuilder::new()
.tag(FingerprintTag::FixedInt)
.width(8)
.finish();
assert_ne!(a, b);
}
#[test]
fn fingerprint_tag_wire_values_are_stable_by_construction() {
assert_eq!(FingerprintTag::FixedInt.wire_value(), 0);
assert_eq!(FingerprintTag::Float.wire_value(), 1);
assert_eq!(FingerprintTag::Bool.wire_value(), 2);
assert_eq!(FingerprintTag::Sequence.wire_value(), 3);
assert_eq!(FingerprintTag::Struct.wire_value(), 4);
assert_eq!(FingerprintTag::Enum.wire_value(), 5);
}
#[test]
fn fold_unordered_is_order_independent() {
assert_eq!(fold_unordered(&[1, 2, 3]), fold_unordered(&[3, 1, 2]));
}
#[test]
fn fold_unordered_distinguishes_different_sets() {
assert_ne!(fold_unordered(&[1, 2, 3]), fold_unordered(&[1, 2, 4]));
}
#[test]
fn fold_unordered_empty_is_zero() {
assert_eq!(fold_unordered(&[]), 0);
}
}
mod wire_format_table_coverage {
use super::WireFingerprint;
use crate::{BigEndian, LittleEndian};
const fn covered<T: WireFingerprint + ?Sized>() {}
const _: () = {
covered::<u8>();
covered::<i8>();
covered::<u16>();
covered::<u32>();
covered::<u64>();
covered::<u128>();
covered::<i16>();
covered::<i32>();
covered::<i64>();
covered::<i128>();
covered::<f32>();
covered::<f64>();
covered::<bool>();
covered::<char>();
covered::<BigEndian<u32>>();
covered::<LittleEndian<u32>>();
covered::<core::num::NonZero<u32>>();
covered::<core::num::Wrapping<u32>>();
covered::<core::num::Saturating<u32>>();
covered::<core::cmp::Ordering>();
covered::<core::cmp::Reverse<u32>>();
covered::<Option<u32>>();
covered::<Result<u32, u8>>();
covered::<core::ops::Bound<u32>>();
covered::<str>();
covered::<core::time::Duration>();
covered::<core::net::Ipv4Addr>();
covered::<core::net::Ipv6Addr>();
covered::<core::net::SocketAddrV4>();
covered::<core::net::SocketAddrV6>();
covered::<core::net::IpAddr>();
covered::<core::net::SocketAddr>();
covered::<[u32; 4]>();
covered::<core::ops::Range<u32>>();
covered::<core::ops::RangeInclusive<u32>>();
covered::<core::ops::RangeFrom<u32>>();
covered::<core::ops::RangeTo<u32>>();
covered::<core::ops::RangeToInclusive<u32>>();
covered::<core::ops::RangeFull>();
covered::<core::marker::PhantomData<u32>>();
covered::<(u8,)>();
covered::<(u8, u8)>();
covered::<(u8, u8, u8)>();
covered::<(u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8)>();
covered::<(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8)>();
};
#[cfg(feature = "alloc")]
const _: () = {
covered::<alloc::string::String>();
covered::<alloc::vec::Vec<u32>>();
covered::<alloc::collections::VecDeque<u32>>();
covered::<alloc::collections::LinkedList<u32>>();
covered::<alloc::collections::BTreeSet<u32>>();
covered::<alloc::collections::BTreeMap<u32, u8>>();
};
#[cfg(feature = "std")]
const _: () = {
covered::<std::collections::HashMap<u32, u8>>();
covered::<std::collections::HashSet<u32>>();
covered::<std::path::PathBuf>();
covered::<std::path::Path>();
covered::<std::ffi::CString>();
covered::<core::ffi::CStr>();
covered::<std::sync::Arc<u32>>();
covered::<std::rc::Rc<u32>>();
covered::<std::boxed::Box<u32>>();
covered::<std::time::SystemTime>();
};
}