total_space/
messages.rs

1use crate::utilities::*;
2
3use num_traits::FromPrimitive;
4use num_traits::ToPrimitive;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::fmt::Result as FormatterResult;
8
9/// The type of the index of a message in the configuration.
10///
11/// "A total of 256 in-flight messages should be enough for everybody" ;-)
12#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Debug)]
13pub struct MessageIndex(u8);
14
15impl IndexLike for MessageIndex {
16    fn from_usize(value: usize) -> MessageIndex {
17        MessageIndex(u8::from_usize(value).unwrap())
18    }
19
20    fn to_usize(&self) -> usize {
21        let MessageIndex(value) = self;
22        u8::to_usize(value).unwrap()
23    }
24
25    // BEGIN MAYBE TESTED
26    fn invalid() -> MessageIndex {
27        MessageIndex(u8::max_value())
28    }
29    // END MAYBE TESTED
30}
31
32// BEGIN MAYBE TESTED
33
34impl Display for MessageIndex {
35    fn fmt(&self, formatter: &mut Formatter<'_>) -> FormatterResult {
36        write!(formatter, "{}", self.to_usize())
37    }
38}
39
40/// Possible way to order a message.
41#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Debug)]
42pub enum MessageOrder {
43    /// Deliver the message immediately, before any other message.
44    Immediate,
45
46    /// Deliver the message in any order relative to all other unordered messages.
47    Unordered,
48
49    /// Deliver the message in the specified order relative to all other ordered messages between
50    /// the same source and target.
51    Ordered(MessageIndex),
52}
53
54/// A message in-flight between agents.
55#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Debug)]
56pub struct Message<Payload: DataLike> {
57    /// How the message is ordered.
58    pub order: MessageOrder,
59
60    /// The source agent index.
61    pub source_index: usize,
62
63    /// The target agent index.
64    pub target_index: usize,
65
66    /// The actual payload.
67    pub payload: Payload,
68
69    /// The replaced message, if any.
70    pub replaced: Option<Payload>,
71}
72
73impl<Payload: DataLike> Default for Message<Payload> {
74    fn default() -> Self {
75        Message {
76            order: MessageOrder::Unordered,
77            source_index: usize::max_value(),
78            target_index: usize::max_value(),
79            payload: Default::default(),
80            replaced: None,
81        }
82    }
83}