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
use std::collections::VecDeque;

use tracing::debug;

use crate::{
    util::MsgNumGenerator, AckList, BitStreamWrite, InternalPacket, PacketReliability, RakNetTime,
};

#[derive(Default)]
pub struct Queue {
    inner: VecDeque<(BitStreamWrite, PacketReliability)>,
}

impl Queue {
    pub fn push(&mut self, bs: BitStreamWrite, reliability: PacketReliability) {
        self.inner.push_back((bs, reliability));
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    pub fn generate_datagram(
        &mut self,
        output: &mut BitStreamWrite,
        msg_num_gen: &mut MsgNumGenerator,
        time: RakNetTime,
        acks: &mut AckList,
    ) {
        debug!(
            "Generating Datagram for acks {:?} and {} packets",
            acks,
            self.inner.len()
        );
        let mut wrote_data = false;

        if acks.is_empty() {
            output.write_0();
        } else {
            output.write_1(); // has acks
            output.write(0u32); // time
            acks.serialize(output);
            acks.clear(); // FIXME: Clear only written
        }

        if let Some((payload, reliability)) = self.inner.pop_front() {
            // FIXME: limit
            let msg_num = msg_num_gen.next();
            let data_bit_size = payload.num_bits();
            debug!(
                "Writing {:?} packet #{}, bitlen {}: {:?}",
                reliability,
                msg_num,
                data_bit_size,
                payload.data()
            );
            let internal_packet = InternalPacket {
                time,
                msg_num,
                reliability,
                ordering: None,
                is_split_packet: false,
                data_bit_size,
                data: payload.data(),
            };

            if !wrote_data {
                output.write_1();
                output.write(time);
                wrote_data = true;
            }
            let _bits_written = internal_packet.write(output);
        }

        debug!("queue.len: {}", self.inner.len());

        if !wrote_data {
            output.write_0();
        }
    }
}