bevnet 0.1.0

A library for networking in Bevy.
Documentation
use dashmap::DashMap;
use serde::{de::DeserializeOwned, Serialize};

/// A [Packet] that can be sent over the network.
pub trait Packet: DeserializeOwned + Serialize + Sync + Send + 'static {
    const ID: u32;
}

/// A macro to easily implement [Packet].
#[macro_export]
macro_rules! impl_packet {
    ($t:ty) => {
        impl ::bevnet::Packet for $t {
            const ID: u32 = ::const_fnv1a_hash::fnv1a_hash_32(
                concat!(module_path!(), "::", stringify!($t)).as_bytes(),
                None,
            );
        }
    };
}

/// A container for the received [Packet]s.
pub struct PacketReceiver {
    /// The received data.
    data: DashMap<u32, Vec<Vec<u8>>>,
}

impl PacketReceiver {
    /// Creates a new [PacketReceiver].
    pub fn new() -> Self {
        Self {
            data: DashMap::new(),
        }
    }

    /// Clears all the [Packet]s.
    pub fn clear(&self) {
        self.data.clear();
    }

    /// Inserts a the received raw [Packet] into the [PacketReceiver].
    pub fn insert(&self, id: u32, data: Vec<u8>) {
        self.data.entry(id).or_default().push(data);
    }

    /// Extract all the [Packet]s of a given type.
    pub fn extract<P: Packet>(&self) -> Vec<P> {
        match self.data.get_mut(&P::ID) {
            Some(mut data) => data
                .value_mut()
                .drain(..)
                .filter_map(|data| bincode::deserialize(&data).ok())
                .collect(),
            None => Vec::new(),
        }
    }
}