ratman_netmod/frame.rs
1//! Networking frames
2
3use crate::{SeqBuilder, SeqData, SeqId};
4use identity::{Identity, ID_LEN};
5use serde::{Deserialize, Serialize};
6
7/// Encoded recipient data
8///
9/// A `Frame` can either be addressed to a single user on the network,
10/// or to the network as a whole. The latter is called `Flood` and
11/// should primarily be used for small payload sequences.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13pub enum Recipient {
14 /// Addressed to a single user ID on the network
15 User(Identity),
16 /// Spreading a `Frame` to the whole network
17 Flood,
18}
19
20/// Describes an endpoint's send target
21///
22/// This is different from a Recipient in that it doesn't encode
23/// information about a user on the global network. It's values are
24/// used by one-to-many Endpoint implementors to desambiguate their
25/// own routing tables without having to replicate the Ratman internal
26/// routing table.
27///
28/// If your endpoint doesn't implement a one-to-many link (i.e. if
29/// it's always one-to-one), just let this value to `Single(0)`
30/// (`Target::default()`)
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Target {
33 /// Send message to all reachable endpoints
34 Flood,
35 /// Encodes a specific target ID
36 Single(u16),
37}
38
39impl Default for Target {
40 fn default() -> Self {
41 Self::Single(0)
42 }
43}
44
45/// A sequence of data, represented by a single network packet
46///
47/// Because a `Frame` is usually created in a sequence, the
48/// constructors assume chainable operations, such as a `Vec<Frame>`
49/// can be returned with all sequence ID information correctly setup.
50#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
51pub struct Frame {
52 /// Sender information
53 pub sender: Identity,
54 /// Recipient information
55 pub recipient: Recipient,
56 /// Data sequence identifiers
57 pub seq: SeqData,
58 /// Raw data payload
59 pub payload: Vec<u8>,
60}
61
62impl Frame {
63 /// Produce a new dummy frame that sends nonsense data from nowhere to everyone.
64 pub fn dummy() -> Self {
65 SeqBuilder::new(
66 Identity::from([0; ID_LEN]),
67 Recipient::Flood,
68 Identity::random(),
69 )
70 .add(vec![0xDE, 0xAD, 0xBE, 0xEF])
71 .build()
72 .remove(0)
73 }
74
75 /// Build a one-off frame with inline payload
76 pub fn inline_flood(sender: Identity, payload: Vec<u8>) -> Frame {
77 SeqBuilder::new(sender, Recipient::Flood, Identity::random())
78 .add(payload)
79 .build()
80 .remove(0)
81 }
82
83 /// Return the sequence Id of a frame
84 pub fn seqid(&self) -> SeqId {
85 self.seq.seqid
86 }
87}