1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::time::Duration;

use lunatic::{
    serializer::{Bincode, Serializer},
    Mailbox, MailboxResult, Tag,
};
use serde::{Deserialize, Serialize};

/// A lunatic mailbox with a tag.
///
/// This is useful for receiving messages with the given tag,
/// even if the current process does not take `M` message type.
#[derive(Clone, Copy, Debug)]
pub struct TaggedMailbox<M, S = Bincode, L = ()>
where
    S: Serializer<M>,
{
    tag: Tag,
    mailbox: Mailbox<M, S, L>,
}

impl<M, S, L> TaggedMailbox<M, S, L>
where
    S: Serializer<M>,
{
    /// Creates a new tag and mailbox, returning a [TaggedMailbox].
    pub fn new() -> Self {
        TaggedMailbox {
            tag: Tag::new(),
            mailbox: unsafe { Mailbox::new() },
        }
    }

    /// Creates a [TaggedMailbox] from an existing [Tag].
    pub fn from_tag(tag: Tag) -> Self {
        TaggedMailbox {
            tag,
            mailbox: unsafe { Mailbox::new() },
        }
    }

    /// Returns the inner tag.
    pub fn tag(&self) -> Tag {
        self.tag
    }

    /// Receives a message with a timeout.
    pub fn receive_timeout(&self, timeout: Duration) -> MailboxResult<M> {
        self.mailbox.tag_receive_timeout(&[self.tag], timeout)
    }
}

impl<M, S> TaggedMailbox<M, S, ()>
where
    S: Serializer<M>,
{
    /// Receives a message.
    pub fn receive(&self) -> M {
        self.mailbox.tag_receive(&[self.tag])
    }
}

impl<M, S, L> Default for TaggedMailbox<M, S, L>
where
    S: Serializer<M>,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<M, S, L> PartialEq for TaggedMailbox<M, S, L>
where
    S: Serializer<M>,
{
    fn eq(&self, other: &Self) -> bool {
        self.tag == other.tag
    }
}

impl<M, S, L> Eq for TaggedMailbox<M, S, L> where S: Serializer<M> {}

impl<M, Se, L> Serialize for TaggedMailbox<M, Se, L>
where
    Se: Serializer<M>,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.tag.serialize(serializer)
    }
}

impl<'de, M, S, L> Deserialize<'de> for TaggedMailbox<M, S, L>
where
    S: Serializer<M>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let tag = Tag::deserialize(deserializer)?;
        Ok(TaggedMailbox {
            tag,
            mailbox: unsafe { Mailbox::new() },
        })
    }
}