icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
//! The protocol version both ends compile in, and the handshake check.

/// `(major, minor)`. Minor bumps only add optional fields; a different major cannot talk.
pub const PROTOCOL: (u16, u16) = (1, 0);

/// The peer speaks a different major version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error(
    "protocol mismatch: this side speaks {}.{}, the peer speaks {}.{}",
    ours.0,
    ours.1,
    theirs.0,
    theirs.1
)]
pub struct VersionMismatch {
    /// [`PROTOCOL`].
    pub ours: (u16, u16),
    /// What the peer sent.
    pub theirs: (u16, u16),
}

/// Checks the peer's version from the handshake: the same major is accepted whatever the
/// minor.
pub fn accepts(peer: (u16, u16)) -> Result<(), VersionMismatch> {
    if peer.0 == PROTOCOL.0 {
        return Ok(());
    }
    Err(VersionMismatch {
        ours: PROTOCOL,
        theirs: peer,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn same_major_is_accepted_whatever_the_minor() {
        let table = [
            ((1, 0), true),
            ((1, 7), true),
            ((0, 9), false),
            ((2, 0), false),
            ((u16::MAX, 0), false),
        ];
        for (peer, ok) in table {
            assert_eq!(accepts(peer).is_ok(), ok, "{peer:?}");
        }
    }

    #[test]
    fn mismatch_names_both_versions() {
        let message = accepts((2, 3)).err().map(|e| e.to_string());
        assert_eq!(
            message.as_deref(),
            Some("protocol mismatch: this side speaks 1.0, the peer speaks 2.3")
        );
    }
}