djin_protocol/wire/dgram/
mod.rs

1use crate::{wire::middleware, Parcel, Error, Settings};
2
3use std::io::prelude::*;
4use std::io::Cursor;
5use std;
6
7/// A datagram-based packet pipeline.
8#[derive(Clone, Debug)]
9pub struct Pipeline<P: Parcel, M: middleware::Pipeline>
10{
11    pub middleware: M,
12    pub settings: Settings,
13
14    _a: std::marker::PhantomData<P>,
15}
16
17impl<P,M> Pipeline<P,M>
18    where P: Parcel, M: middleware::Pipeline
19{
20    pub fn new(middleware: M,
21                settings: Settings) -> Self {
22        Pipeline {
23            middleware, settings,
24            _a: std::marker::PhantomData,
25        }
26    }
27
28    /// Reads a packet from a buffer which contains a single packet.
29    pub fn receive_from(&mut self, buffer: &mut dyn Read)
30        -> Result<P, Error> {
31        let raw_bytes: Result<Vec<u8>, _> = buffer.bytes().collect();
32        let raw_bytes = raw_bytes?;
33
34        let mut bytes = Cursor::new(self.middleware.decode_data(raw_bytes)?);
35        P::read(&mut bytes, &self.settings)
36    }
37
38    /// Writes a packet into a buffer.
39    pub fn send_to(&mut self, buffer: &mut dyn Write, packet: &P)
40        -> Result<(), Error> {
41        let bytes = self.middleware.encode_data(packet.raw_bytes(&self.settings)?)?;
42        buffer.write(&bytes)?;
43        Ok(())
44    }
45}
46