lyanne 0.6.2

Tick-based communication library for server-client architectures.
Documentation
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Sets of data that are transferred over the communication.

use std::{
    any::{Any, TypeId},
    collections::HashMap,
    fmt::Debug,
    io,
};

use crate::{self as lyanne};

#[cfg(feature = "sd_bincode")]
#[cfg_attr(docsrs, doc(cfg(feature = "sd_bincode")))]
pub use bincode;

#[cfg(any(feature = "sd_bincode"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "sd_bincode"))))]
pub extern crate lyanne_derive;
#[cfg(any(feature = "sd_bincode"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "sd_bincode"))))]
pub use lyanne_derive::Packet;

pub type PacketId = u16;
pub type PacketToDowncast = dyn Any + Send + Sync;

/// Adds essential packages
///
/// Does not necessarily need to be used with [`PacketRegistry`], it just needs
/// to be something that has a function with similar annotation of [`PacketRegistry::add`].
///
/// Useful for creating wrappers, which have not only a [`PacketRegistry`], but also another package registry.
///
/// # Examples
/// ```rust,no_run
/// use lyanne::{add_essential_packets, packets::{Packet, PacketRegistry}};
///
/// struct PacketRegistryLogger {
///     packet_registry: PacketRegistry
/// }
/// impl PacketRegistryLogger {
///     fn add<P: Packet>(&mut self) {
///         let id = self.packet_registry.add::<P>();
///         println!("Packet added with {} id", id);
///     }
/// }
///
/// let mut packet_registry_logger = PacketRegistryLogger {
///     packet_registry: PacketRegistry::empty()
/// };
/// add_essential_packets!(packet_registry_logger);
/// ```
#[macro_export]
macro_rules! add_essential_packets {
    ($exit:expr) => {
        $exit.add::<lyanne::packets::ClientTickEndPacket>();
        $exit.add::<lyanne::packets::ServerTickEndPacket>();
        $exit.add::<lyanne::packets::EmptyPacket>();
    };
}

/// Set of data used for exchanging information.
pub trait Packet: Sized + Debug + 'static + Any + Send + Sync {
    /// If no serializer (such as the `sd_bincode` feature) is being used,
    /// it is still possible to create packages by serializing them manually.
    ///
    /// # Examples
    /// ```rust,no_run
    /// use lyanne::packets::Packet;
    ///
    /// // Creating a packet.
    /// #[derive(Debug)]
    /// struct HelloPacket {
    ///     player_name: String,
    /// }
    ///
    /// impl Packet for HelloPacket {
    ///     // Serializing the fields of the packet manually.
    ///     fn serialize_packet(&self) -> std::io::Result<Vec<u8>> {
    ///         Ok(self.player_name.clone().into_bytes())
    ///     }
    ///
    ///     fn deserialize_packet(bytes: &[u8]) -> std::io::Result<Self> {
    ///         todo!()
    ///     }
    /// }
    /// ```
    fn serialize_packet(&self) -> io::Result<Vec<u8>>;

    /// If no serializer (such as the `sd_bincode` feature) is being used,
    /// it is still possible to create packages by deserializing them manually.
    ///
    /// # Examples
    /// ```rust,no_run
    /// use lyanne::packets::Packet;
    ///
    /// // Creating a packet.
    /// #[derive(Debug)]
    /// struct HelloPacket {
    ///     player_name: String,
    /// }
    ///
    /// impl Packet for HelloPacket {
    ///     fn serialize_packet(&self) -> std::io::Result<Vec<u8>> {
    ///         todo!();
    ///     }
    ///
    ///     // Deserializing the fields of the packet manually.
    ///     fn deserialize_packet(bytes: &[u8]) -> std::io::Result<Self> {
    ///         match String::from_utf8(bytes.to_vec()) {
    ///             Ok(player_name) => Ok(Self { player_name }),
    ///             Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, e)),
    ///         }
    ///     }
    /// }
    /// ```
    fn deserialize_packet(bytes: &[u8]) -> io::Result<Self>;

    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    type ClientSchedule: lyanne::bevy_ecs::schedule::ScheduleLabel;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    fn client_schedule() -> Self::ClientSchedule;

    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    type ServerSchedule: lyanne::bevy_ecs::schedule::ScheduleLabel;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    fn server_schedule() -> Self::ServerSchedule;
}

#[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
#[derive(lyanne::bevy_ecs::system::Resource)]
pub struct ClientPacketResource<P: Packet> {
    pub packet: Option<P>,
}

#[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
#[derive(lyanne::bevy_ecs::system::Resource)]
pub struct ServerPacketResource<P: Packet> {
    pub packet: Option<P>,
}

/// Registry holder for the Packets.
///
/// Needed to store how to deserialize and serialize each packet.
///
/// # Examples
/// ```rust,no_run
/// use lyanne::packets::{Packet, PacketRegistry};
/// use serde::{Deserialize, Serialize};
///
/// // Creating packets.
/// #[derive(Packet, Deserialize, Serialize, Debug)]
/// struct HelloPacket {
///     player_name: String,
/// }
/// #[derive(Packet, Deserialize, Serialize, Debug)]
/// struct MessagePacket {
///     message: String,
/// }
///
/// // Essential packages are required for communication.
/// let mut packet_registry = PacketRegistry::with_essential();
///
/// // Adding custom packets to the registry.
/// packet_registry.add::<HelloPacket>();
/// packet_registry.add::<MessagePacket>();
/// ```
pub struct PacketRegistry {
    packet_type_ids: HashMap<TypeId, PacketId>,
    serde_map: HashMap<
        PacketId,
        (
            // Serialize, uses a `Packet`, and serialize it into a SerializedPacket
            Box<dyn Fn(&PacketToDowncast) -> io::Result<SerializedPacket> + Send + Sync>,
            // Deserialize, uses a `Vec<u8>`, and deserialize it into a Packet
            Box<dyn Fn(&[u8]) -> io::Result<Box<PacketToDowncast>> + Send + Sync>,
        ),
    >,
    last_id: PacketId,
}

impl PacketRegistry {
    /// Constructs a empty registry.
    ///
    /// # Warning
    /// A registry needs essential packages, which can be easily added with the `add_essential_packets!` macro.
    ///
    /// # Examples
    /// ```rust,no_run
    /// use lyanne::{add_essential_packets, packets::PacketRegistry};
    ///
    /// let mut packet_registry = PacketRegistry::empty();
    /// add_essential_packets!(packet_registry);
    /// ```
    ///
    pub fn empty() -> Self {
        Self {
            packet_type_ids: HashMap::new(),
            serde_map: HashMap::new(),
            last_id: 0,
        }
    }

    /// Constructs a registry, with the essential packets.
    pub fn with_essential() -> Self {
        let mut exit = Self::empty();
        add_essential_packets!(exit);
        exit
    }

    /// Adds a packet to the registry.
    ///
    /// # Examples
    /// ```rust,no_run
    /// use lyanne::packets::{Packet, PacketRegistry};
    /// use serde::{Deserialize, Serialize};
    ///
    /// #[derive(Packet, Deserialize, Serialize, Debug)]
    /// struct HelloPacket {
    ///     player_name: String,
    /// }
    ///
    /// let mut packet_registry = PacketRegistry::with_essential();
    /// packet_registry.add::<HelloPacket>();
    /// ```
    pub fn add<P: Packet>(&mut self) -> PacketId {
        self.last_id += 1;
        let packet_id = self.last_id;
        let type_id = TypeId::of::<P>();

        let packet_id_copy = packet_id;
        let packet_id_bytes = packet_id_copy.to_le_bytes();
        let serialize = move |packet: &PacketToDowncast| -> io::Result<SerializedPacket> {
            let packet = packet.downcast_ref::<P>().ok_or_else(|| {
                return io::Error::new(io::ErrorKind::InvalidData, "Type mismatch");
            })?;

            let mut bytes = P::serialize_packet(packet)?;

            let packet_length = bytes.len() as PacketId;
            let packet_length_bytes = packet_length.to_le_bytes();

            let mut full_bytes: Vec<u8> = Vec::with_capacity(bytes.len() + 4);
            full_bytes.extend_from_slice(&packet_id_bytes);
            full_bytes.extend(packet_length_bytes);
            full_bytes.append(&mut bytes);

            Ok(SerializedPacket {
                packet_id: packet_id_copy,
                bytes: full_bytes,
            })
        };

        let deserialize = |bytes: &[u8]| -> io::Result<Box<PacketToDowncast>> {
            let packet = P::deserialize_packet(&bytes)?;
            Ok(Box::new(packet))
        };

        self.packet_type_ids.insert(type_id, packet_id);
        self.serde_map
            .insert(packet_id, (Box::new(serialize), Box::new(deserialize)));

        packet_id
    }

    /// Check if the essential packets were registered.
    pub fn check_essential(&self) -> bool {
        self.try_get_packet_id::<ClientTickEndPacket>().is_some()
            && self.try_get_packet_id::<ServerTickEndPacket>().is_some()
            && self.try_get_packet_id::<EmptyPacket>().is_some()
    }

    /// Get the if of the packet.
    ///
    /// # Returns
    /// - Some(&PacketId) if the packet is not registered.
    /// - None if the packet is not registered.
    pub fn try_get_packet_id<P: Packet>(&self) -> Option<&PacketId> {
        self.packet_type_ids.get(&TypeId::of::<P>())
    }

    /// Panic version of [`PacketRegistry::try_get_packet_id`].
    ///
    /// Get the if of the packet.
    ///
    /// # Panics
    /// If the packet is not registered.
    #[cfg(not(feature = "no_panics"))]
    pub fn get_packet_id<P: Packet>(&self) -> &PacketId {
        self.try_get_packet_id::<P>()
            .expect("Packet is not registered.")
    }

    /// Serializes a packet.
    ///
    /// # Errors
    /// If the packet is not in the registry, or the bytes serialization fails.
    pub fn try_serialize<P: Packet>(&self, packet: &P) -> io::Result<SerializedPacket> {
        let packet_id = self.try_get_packet_id::<P>();
        if let Some(packet_id) = packet_id {
            let (serialize, _) = self.serde_map.get(packet_id).unwrap();
            let serialized = serialize(packet)?;

            Ok(serialized)
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Packet id not found".to_owned(),
            ));
        }
    }

    /// Panic version of [`PacketRegistry::try_serialize`].
    ///
    /// Serializes a packet.
    ///
    /// # Panics
    /// If the packet is not in the registry, or the bytes serialization fails.
    #[cfg(not(feature = "no_panics"))]
    pub fn serialize<P: Packet>(&self, packet: &P) -> SerializedPacket {
        self.try_serialize(packet)
            .expect("Failed to serialize packet.")
    }

    /// Deserializes a packet.
    ///
    /// # Errors
    /// If the packet is not in the registry, or the bytes deserialization fails.
    pub fn try_deserialize(
        &self,
        serialized_packet: &SerializedPacket,
    ) -> io::Result<Box<PacketToDowncast>> {
        if let Some((_, deserialize)) = self.serde_map.get(&serialized_packet.packet_id) {
            let deserialized = deserialize(&serialized_packet.bytes[4..])?;
            Ok(deserialized)
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Packet id not found",
            ));
        }
    }

    /// Panic version of [`PacketRegistry::try_deserialize`].
    ///
    /// Deserializes a packet.
    ///
    /// # Panics
    /// If the packet is not in the registry, or the bytes deserialization fails.
    #[cfg(not(feature = "no_panics"))]
    pub fn deserialize(&self, serialized_packet: &SerializedPacket) -> Box<PacketToDowncast> {
        self.try_deserialize(serialized_packet)
            .expect("Failed to deserialize packet.")
    }

    pub fn empty_serialized_list(&self) -> SerializedPacketList {
        SerializedPacketList::single(
            self.try_serialize(&EmptyPacket)
                .expect("EmptyPacket was not registered."),
        )
    }
}

/// Represents a packet serialized to bytes.
pub struct SerializedPacket {
    pub(crate) packet_id: PacketId,
    pub(crate) bytes: Vec<u8>,
}

impl SerializedPacket {
    pub fn clone(&self) -> Self {
        Self {
            packet_id: self.packet_id,
            bytes: self.bytes.clone(),
        }
    }

    pub fn read_first(buf: &[u8], packet_buf_index: usize) -> io::Result<SerializedPacket> {
        if buf.len() - packet_buf_index < 4 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Buf size is not big sufficient to read packet id and packet length",
            ));
        }

        let packet_id = PacketId::from_le_bytes([buf[packet_buf_index], buf[packet_buf_index + 1]]);
        let packet_length: PacketId =
            PacketId::from_le_bytes([buf[packet_buf_index + 2], buf[packet_buf_index + 3]]);

        let packet_size: usize = packet_length.into();
        if buf.len() < 4 + packet_buf_index + packet_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "Buf size ({:}) is not big sufficient, minimal is {:?}",
                    buf.len(),
                    4 + packet_buf_index + packet_size
                ),
            ));
        } else {
            return Ok(SerializedPacket {
                packet_id,
                bytes: buf[packet_buf_index..4 + packet_buf_index + packet_size].to_vec(),
            });
        }
    }
}

/// Deserialized packets stored in a map, by their IDs.
#[derive(Debug)]
pub struct DeserializedMessageMap {
    inner: HashMap<PacketId, Vec<DeserializedPacket>>,
}

impl DeserializedMessageMap {
    /// The list (if there is some) of the packet type (`P`).
    ///
    /// That list will never be empty.
    /// # Errors
    /// - If the packet type (`P`) was not registered in `packet_registry`.
    /// - If the packet_map is invalid, and has packets that can not be converted to `P` in the list.
    pub fn try_collect_list<P: Packet>(
        &mut self,
        packet_registry: &PacketRegistry,
    ) -> io::Result<Option<Vec<P>>> {
        if let Some(packet_id) = packet_registry.try_get_packet_id::<P>() {
            if let Some(list) = self.inner.remove(&packet_id) {
                let mut exit = Vec::<P>::new();
                for packet in list {
                    if let Ok(downcast) = packet.packet.downcast::<P>() {
                        exit.push(*downcast);
                    } else {
                        return Err(io::Error::new(
                            io::ErrorKind::Other,
                            "Packet could not be converted into P.",
                        ));
                    }
                }
                Ok(Some(exit))
            } else {
                Ok(None)
            }
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Packet is not registered.",
            ))
        }
    }

    /// Panic version of [`DeserializedMessageMap::try_collect_list`].
    ///
    /// The list (if there is some) of the packet type (`P`).
    ///
    /// That list will never be empty.
    /// # Panics
    /// - If the packet type (`P`) was not registered in `packet_registry`.
    /// - If the packet_map is invalid, and has packets that can not be converted to `P` in the list.
    #[cfg(not(feature = "no_panics"))]
    pub fn collect_list<P: Packet>(&mut self, packet_registry: &PacketRegistry) -> Option<Vec<P>> {
        self.try_collect_list(packet_registry)
            .expect("Failed to collect packets into list from map.")
    }
}

/// Represents a deserialized packet.
///
/// Ready to be downcasted to the type
/// represented by the `packet_id`.
#[derive(Debug)]
pub struct DeserializedPacket {
    pub packet_id: PacketId,
    pub packet: Box<PacketToDowncast>,
}

impl DeserializedPacket {
    pub fn deserialize_list(
        buf: &[u8],
        packet_registry: &PacketRegistry,
    ) -> io::Result<Vec<DeserializedPacket>> {
        let mut packet_buf_index = 0;
        let mut received_packets: Vec<DeserializedPacket> = Vec::new();
        loop {
            if buf.len() == packet_buf_index {
                break;
            }

            match SerializedPacket::read_first(buf, packet_buf_index) {
                Ok(serialized_packet) => {
                    packet_buf_index += serialized_packet.bytes.len();
                    if let Some((_, deserialize)) =
                        packet_registry.serde_map.get(&serialized_packet.packet_id)
                    {
                        match deserialize(&serialized_packet.bytes[4..]) {
                            Ok(deserialized) => {
                                received_packets.push(DeserializedPacket {
                                    packet_id: serialized_packet.packet_id,
                                    packet: deserialized,
                                });
                            }
                            Err(e) => {
                                return Err(io::Error::new(io::ErrorKind::InvalidData, e));
                            }
                        }
                    } else {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            format!("packet id not registered: {}", serialized_packet.packet_id),
                        ));
                    }
                }
                Err(e) => {
                    return Err(io::Error::new(io::ErrorKind::InvalidData, e));
                }
            }
        }
        if received_packets.is_empty() {
            Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "The list has no packets.",
            ))
        } else {
            Ok(received_packets)
        }
    }

    pub fn deserialize_list_as_map(
        buf: &[u8],
        packet_registry: &PacketRegistry,
    ) -> io::Result<DeserializedMessageMap> {
        let mut packet_buf_index = 0;
        let mut received_packets: HashMap<PacketId, Vec<DeserializedPacket>> = HashMap::new();
        loop {
            if buf.len() == packet_buf_index {
                break;
            }

            match SerializedPacket::read_first(buf, packet_buf_index) {
                Ok(serialized_packet) => {
                    packet_buf_index += serialized_packet.bytes.len();
                    if let Some((_, deserialize)) =
                        packet_registry.serde_map.get(&serialized_packet.packet_id)
                    {
                        match deserialize(&serialized_packet.bytes[4..]) {
                            Ok(deserialized) => {
                                received_packets
                                    .entry(serialized_packet.packet_id)
                                    .or_insert_with(|| Vec::new())
                                    .push(DeserializedPacket {
                                        packet_id: serialized_packet.packet_id,
                                        packet: deserialized,
                                    });
                            }
                            Err(e) => {
                                return Err(io::Error::new(io::ErrorKind::InvalidData, e));
                            }
                        }
                    } else {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            format!("packet id not registered: {}", serialized_packet.packet_id),
                        ));
                    }
                }
                Err(e) => {
                    return Err(io::Error::new(io::ErrorKind::InvalidData, e));
                }
            }
        }
        if received_packets.is_empty() {
            Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "The list has no packets.",
            ))
        } else {
            Ok(DeserializedMessageMap {
                inner: received_packets,
            })
        }
    }
}

/// List of serialized packets.
pub struct SerializedPacketList {
    pub(crate) bytes: Vec<u8>,
}

impl SerializedPacketList {
    /// Creates a SerializedPacketList from `stored`.
    ///
    /// # Errors
    /// If `stored` is empty.
    pub fn try_non_empty(stored: Vec<SerializedPacket>) -> Option<SerializedPacketList> {
        if stored.is_empty() {
            return None;
        }

        let total_size = stored
            .iter()
            .map(|packet| packet.bytes.len())
            .sum::<usize>();
        let mut bytes = Vec::with_capacity(total_size);

        for mut packet in stored {
            bytes.append(&mut packet.bytes);
        }

        Some(SerializedPacketList { bytes })
    }

    /// Panic version of [`SerializedPacketList::try_non_empty`].
    ///
    /// Creates a SerializedPacketList from `stored`.
    ///
    /// # Panics
    /// If `stored` is empty.
    #[cfg(not(feature = "no_panics"))]
    pub fn non_empty(stored: Vec<SerializedPacket>) -> SerializedPacketList {
        SerializedPacketList::try_non_empty(stored).expect("SerializedPacketList can not be empty")
    }

    /// Creates a SerializedPacketList with a single packet.
    pub fn single(stored: SerializedPacket) -> SerializedPacketList {
        SerializedPacketList::try_non_empty(vec![stored]).unwrap()
    }
}

/// Packet sent by the client in every message.
#[derive(Debug)]
pub struct ClientTickEndPacket;
impl Packet for ClientTickEndPacket {
    fn serialize_packet(&self) -> std::io::Result<Vec<u8>> {
        Ok(Vec::new())
    }

    fn deserialize_packet(_bytes: &[u8]) -> std::io::Result<Self> {
        Ok(Self)
    }

    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    type ClientSchedule = ClientTickEndPacketClientSchedule;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    fn client_schedule() -> Self::ClientSchedule {
        ClientTickEndPacketClientSchedule
    }

    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    type ServerSchedule = ClientTickEndPacketServerSchedule;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    fn server_schedule() -> Self::ServerSchedule {
        ClientTickEndPacketServerSchedule
    }
}
#[allow(dead_code)]
#[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
#[derive(lyanne::bevy_ecs::schedule::ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClientTickEndPacketClientSchedule;
#[allow(dead_code)]
#[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
#[derive(lyanne::bevy_ecs::schedule::ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClientTickEndPacketServerSchedule;

/// Packet sent by the server in every message.
#[derive(Debug)]
pub struct ServerTickEndPacket;
impl Packet for ServerTickEndPacket {
    fn serialize_packet(&self) -> std::io::Result<Vec<u8>> {
        Ok(Vec::new())
    }

    fn deserialize_packet(_bytes: &[u8]) -> std::io::Result<Self> {
        Ok(Self)
    }

    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    type ClientSchedule = ServerTickEndPacketClientSchedule;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    fn client_schedule() -> Self::ClientSchedule {
        ServerTickEndPacketClientSchedule
    }

    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    type ServerSchedule = ServerTickEndPacketServerSchedule;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    fn server_schedule() -> Self::ServerSchedule {
        ServerTickEndPacketServerSchedule
    }
}
#[allow(dead_code)]
#[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
#[derive(lyanne::bevy_ecs::schedule::ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServerTickEndPacketClientSchedule;
#[allow(dead_code)]
#[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
#[derive(lyanne::bevy_ecs::schedule::ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServerTickEndPacketServerSchedule;

/// Empty packet, useful to send an empty message.
///
/// Since it is not possible to send messages without sending any packets.
#[derive(Debug)]
pub struct EmptyPacket;
impl Packet for EmptyPacket {
    fn serialize_packet(&self) -> std::io::Result<Vec<u8>> {
        Ok(Vec::new())
    }

    fn deserialize_packet(_bytes: &[u8]) -> std::io::Result<Self> {
        Ok(Self)
    }

    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    type ClientSchedule = EmptyPacketClientSchedule;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
    fn client_schedule() -> Self::ClientSchedule {
        EmptyPacketClientSchedule
    }

    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    type ServerSchedule = EmptyPacketServerSchedule;
    #[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
    fn server_schedule() -> Self::ServerSchedule {
        EmptyPacketServerSchedule
    }
}
#[allow(dead_code)]
#[cfg(all(feature = "bevy_packet_schedules", feature = "client"))]
#[derive(lyanne::bevy_ecs::schedule::ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct EmptyPacketClientSchedule;
#[allow(dead_code)]
#[cfg(all(feature = "bevy_packet_schedules", feature = "server"))]
#[derive(lyanne::bevy_ecs::schedule::ScheduleLabel, Debug, Clone, PartialEq, Eq, Hash)]
pub struct EmptyPacketServerSchedule;