Skip to main content

naia_shared/messages/
request.rs

1use std::marker::PhantomData;
2
3use crate::Message;
4
5/// Marker trait for message types that expect a typed response.
6pub trait Request: Message {
7    /// The corresponding response type returned by the remote endpoint.
8    type Response: Response;
9}
10
11/// Marker trait for message types that are sent as a reply to a `Request`.
12pub trait Response: Message {}
13
14/// Typed token held by the sender to identify a pending request when its response arrives.
15#[derive(Clone, Eq, PartialEq, Hash)]
16pub struct ResponseSendKey<S: Response> {
17    response_id: GlobalResponseId,
18    phantom_s: PhantomData<S>,
19}
20
21impl<S: Response> ResponseSendKey<S> {
22    /// Creates a `ResponseSendKey` tied to the given global response ID.
23    pub fn new(id: GlobalResponseId) -> Self {
24        Self {
25            response_id: id,
26            phantom_s: PhantomData,
27        }
28    }
29
30    /// Returns the global response ID carried by this key.
31    pub fn response_id(&self) -> GlobalResponseId {
32        self.response_id
33    }
34}
35
36/// Typed token held by the receiver to identify which request a response answers.
37#[derive(Clone, Eq, PartialEq, Hash, Copy)]
38pub struct ResponseReceiveKey<S: Response> {
39    request_id: GlobalRequestId,
40    phantom_s: PhantomData<S>,
41}
42
43impl<S: Response> ResponseReceiveKey<S> {
44    /// Creates a `ResponseReceiveKey` tied to the given global request ID.
45    pub fn new(request_id: GlobalRequestId) -> Self {
46        Self {
47            request_id,
48            phantom_s: PhantomData,
49        }
50    }
51
52    /// Returns the global request ID carried by this key.
53    pub fn request_id(&self) -> GlobalRequestId {
54        self.request_id
55    }
56}
57
58/// Globally-unique identifier for an outgoing request, spanning all connections.
59#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
60pub struct GlobalRequestId {
61    id: u64,
62}
63
64impl GlobalRequestId {
65    /// Creates a `GlobalRequestId` from a raw u64.
66    pub fn new(id: u64) -> Self {
67        Self { id }
68    }
69}
70
71/// Globally-unique identifier for a response to a specific request.
72#[derive(Clone, Copy, Eq, Hash, PartialEq)]
73pub struct GlobalResponseId {
74    id: u64,
75}
76
77impl GlobalResponseId {
78    /// Creates a `GlobalResponseId` from a raw u64.
79    pub fn new(id: u64) -> Self {
80        Self { id }
81    }
82}