summaryrefslogtreecommitdiff
path: root/src/event.rs
blob: 6339afe76d101bc2976c88968a85738a8aeb1ec0 (plain)
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
use std::{cell::Cell, time::Instant};

use getset::Getters;

use crate::event::{
    connection::ConnectionEvent, disconnect::DisconnectEvent, received::PacketReceivedEvent,
    sent::PacketSentEvent,
};

pub mod handler;
pub mod listener;

pub mod connection;
pub mod disconnect;
pub mod received;
pub mod sent;

pub enum EventKind<Packet, Uid>
where
    Uid: PartialEq,
{
    Connection(ConnectionEvent<Uid>),
    PacketReceived(PacketReceivedEvent<Packet>),
    PacketSent(PacketSentEvent<Packet>),
    Disconnect(DisconnectEvent<Uid>),
}

#[derive(Getters)]
pub struct Event<Packet, Uid>
where
    Uid: PartialEq,
{
    #[get = "pub"]
    instant: Instant,

    #[get = "pub"]
    connection_id: Uid,
    canceled: Cell<bool>,
    #[get = "pub"]
    kind: EventKind<Packet, Uid>,
}

impl<Packet, Uid> Event<Packet, Uid>
where
    Uid: PartialEq,
{
    pub fn new(connection_id: Uid, kind: EventKind<Packet, Uid>) -> Self {
        Self {
            connection_id,
            instant: Instant::now(),
            canceled: Cell::new(true),
            kind,
        }
    }

    pub fn differed(connection_id: Uid, when: Instant, kind: EventKind<Packet, Uid>) -> Self {
        Self {
            connection_id,
            instant: when,
            canceled: Cell::new(true),
            kind,
        }
    }

    pub fn canceled(&self) -> bool {
        self.canceled.get()
    }

    pub fn cancel(&self) {
        self.canceled.set(true);
    }
}