arin_protocol/envelope.rs
1//! The `v` field that wraps every message.
2
3use crate::version::Version;
4use serde::{Deserialize, Serialize};
5
6/// A message plus the protocol version it was written against.
7///
8/// The version lives beside the body rather than inside it, so version negotiation can
9/// happen before the body is interpreted. On the wire the two are flat:
10///
11/// ```json
12/// {"v":"0.2","type":"session_end"}
13/// ```
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct Envelope<T> {
16 /// The `v` field.
17 #[serde(rename = "v")]
18 pub version: Version,
19 /// The message itself.
20 #[serde(flatten)]
21 pub body: T,
22}
23
24impl<T> Envelope<T> {
25 /// Wrap a body at the version this build speaks.
26 pub fn current(body: T) -> Self {
27 Self {
28 version: crate::PROTOCOL_VERSION,
29 body,
30 }
31 }
32
33 /// Wrap a body at an explicit version.
34 pub const fn new(version: Version, body: T) -> Self {
35 Self { version, body }
36 }
37
38 /// Replace the body, keeping the version.
39 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Envelope<U> {
40 Envelope {
41 version: self.version,
42 body: f(self.body),
43 }
44 }
45}