Skip to main content

rill_protocol/io/
transport.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashSet;
3use std::fmt;
4use std::hash::Hash;
5use std::marker::PhantomData;
6
7/// An `Envelope` with service-layer messages
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub enum ServiceEnvelope<T: Origin, D, S> {
10    Service(S),
11    Envelope(Envelope<T, D>),
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Envelope<T: Origin, D> {
16    pub direct_id: DirectId<T>,
17    pub data: D,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct WideEnvelope<T: Origin, D> {
22    pub direction: Direction<T>,
23    pub data: D,
24}
25
26/// The origin of `DirectId`.
27pub trait Origin: Default + Clone + PartialEq + Eq + Hash {}
28
29#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
30pub struct DirectId<T: Origin> {
31    value: u64,
32    origin: PhantomData<T>,
33}
34
35impl<T: Origin> fmt::Debug for DirectId<T> {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_tuple("DirectId").field(&self.value).finish()
38    }
39}
40
41impl<T: Origin> From<usize> for DirectId<T> {
42    fn from(value: usize) -> Self {
43        Self {
44            // TODO: TryInto
45            value: value as u64,
46            origin: PhantomData,
47        }
48    }
49}
50
51impl<T: Origin> From<DirectId<T>> for usize {
52    fn from(this: DirectId<T>) -> usize {
53        // TODO: TryInto
54        this.value as usize
55    }
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub enum Direction<T: Origin> {
60    Direct(DirectId<T>),
61    Multicast(HashSet<DirectId<T>>),
62    // TODO: Remove, since all streames bootstrapped from
63    // a predefined path the Broadcast direction is not needed anymore.
64    Broadcast,
65}
66
67impl<T: Origin> Direction<T> {
68    pub fn into_vec(self) -> Vec<DirectId<T>> {
69        match self {
70            Self::Direct(direct_id) => vec![direct_id],
71            Self::Multicast(ids) => ids.into_iter().collect(),
72            Self::Broadcast => Vec::new(),
73        }
74    }
75}
76
77impl<T: Origin> Direction<T> {
78    pub fn broadcast() -> Self {
79        Self::Broadcast
80    }
81}
82
83impl<T: Origin> From<&HashSet<DirectId<T>>> for Direction<T> {
84    fn from(set: &HashSet<DirectId<T>>) -> Self {
85        let mut iter = set.iter();
86        match iter.len() {
87            0 => Self::Broadcast,
88            1 => {
89                let direct_id = iter.next().cloned().unwrap();
90                Self::Direct(direct_id)
91            }
92            _ => {
93                let ids = iter.cloned().collect();
94                Self::Multicast(ids)
95            }
96        }
97    }
98}
99
100impl<T: Origin> From<DirectId<T>> for Direction<T> {
101    fn from(direct_id: DirectId<T>) -> Self {
102        Self::Direct(direct_id)
103    }
104}