pub const PROTOCOL: (u16, u16) = (1, 0);
#[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 {
pub ours: (u16, u16),
pub theirs: (u16, u16),
}
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")
);
}
}