Skip to main content

zaun_community_protocol/envelope/
version.rs

1//! Version rules (§1.1).
2
3use super::{ErrorBody, VersionRange};
4
5/// Chooses the highest version in both ranges (`session.hello`, §6.2).
6///
7/// # Errors
8/// `UNSUPPORTED_VERSION` carrying `host` when the ranges do not overlap (or `client` is empty,
9/// `min > max`). Send it as a version-1 envelope (`ResponseEnvelope::error` does); the
10/// connection stays unnegotiated.
11pub fn negotiate(client: VersionRange, host: VersionRange) -> Result<u16, ErrorBody> {
12    let high = client.max.min(host.max);
13    let low = client.min.max(host.min);
14    if low <= high {
15        Ok(high)
16    } else {
17        Err(ErrorBody::unsupported_version(host))
18    }
19}
20
21/// Checks an inbound envelope's `v` against the connection's negotiated version.
22///
23/// After negotiation `v` MUST equal it; otherwise `UNSUPPORTED_VERSION` with this crate's
24/// range ([`VersionRange::CURRENT`]). Before negotiation any `v` passes: only `session.hello`
25/// is answered then (anything else gets `HELLO_REQUIRED`), and its `versions` body decides.
26///
27/// # Errors
28/// `UNSUPPORTED_VERSION` when `v` differs from the negotiated version.
29// SPEC: §1.1 does not say which `v` an un-negotiated `session.hello` carries. The frozen fields
30// exist "so that session.hello ... can always be exchanged", so we accept any `v` there rather
31// than reject a newer client's hello that would negotiate down to 1.
32pub fn check_version(v: u16, negotiated: Option<u16>) -> Result<(), ErrorBody> {
33    match negotiated {
34        Some(n) if n != v => Err(ErrorBody::unsupported_version(VersionRange::CURRENT)),
35        _ => Ok(()),
36    }
37}