renet/src/socket/udp.rs

252 lines
8.3 KiB
Rust
Raw Normal View History

2016-12-15 01:39:44 +08:00
use Error;
use Managed;
use wire::{InternetAddress as Address, InternetProtocolType as ProtocolType};
use wire::{InternetEndpoint as Endpoint};
use wire::{UdpPacket, UdpRepr};
use socket::{Socket, PacketRepr};
2016-12-15 01:39:44 +08:00
2016-12-16 01:07:56 +08:00
/// A buffered UDP packet.
#[derive(Debug)]
2016-12-19 03:40:02 +08:00
pub struct Packet<'a> {
2016-12-16 01:07:56 +08:00
endpoint: Endpoint,
size: usize,
payload: Managed<'a, [u8]>
2016-12-16 01:07:56 +08:00
}
2016-12-15 01:39:44 +08:00
2016-12-19 03:40:02 +08:00
impl<'a> Packet<'a> {
2016-12-16 01:07:56 +08:00
/// Create a buffered packet.
2016-12-19 03:40:02 +08:00
pub fn new<T>(payload: T) -> Packet<'a>
where T: Into<Managed<'a, [u8]>> {
2016-12-19 03:40:02 +08:00
Packet {
2016-12-16 01:07:56 +08:00
endpoint: Endpoint::INVALID,
size: 0,
payload: payload.into()
2016-12-16 01:07:56 +08:00
}
}
2016-12-17 13:12:45 +08:00
fn as_ref<'b>(&'b self) -> &'b [u8] {
&self.payload[..self.size]
}
fn as_mut<'b>(&'b mut self) -> &'b mut [u8] {
&mut self.payload[..self.size]
}
2016-12-15 01:39:44 +08:00
}
2016-12-19 03:40:11 +08:00
/// An UDP packet ring buffer.
2016-12-16 01:07:56 +08:00
#[derive(Debug)]
2016-12-17 14:27:08 +08:00
pub struct Buffer<'a, 'b: 'a> {
2016-12-19 03:40:02 +08:00
storage: Managed<'a, [Packet<'b>]>,
2016-12-16 01:07:56 +08:00
read_at: usize,
length: usize
2016-12-16 01:07:56 +08:00
}
2016-12-17 14:27:08 +08:00
impl<'a, 'b> Buffer<'a, 'b> {
2016-12-16 01:07:56 +08:00
/// Create a packet buffer with the given storage.
2016-12-17 14:27:08 +08:00
pub fn new<T>(storage: T) -> Buffer<'a, 'b>
2016-12-19 03:40:02 +08:00
where T: Into<Managed<'a, [Packet<'b>]>> {
let mut storage = storage.into();
for elem in storage.iter_mut() {
2016-12-16 01:07:56 +08:00
elem.endpoint = Default::default();
elem.size = 0;
}
2016-12-15 01:39:44 +08:00
2016-12-16 01:07:56 +08:00
Buffer {
storage: storage,
read_at: 0,
length: 0
2016-12-16 01:07:56 +08:00
}
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
fn mask(&self, index: usize) -> usize {
index % self.storage.len()
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
fn incr(&self, index: usize) -> usize {
self.mask(index + 1)
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
fn empty(&self) -> bool {
self.length == 0
}
2016-12-15 01:39:44 +08:00
2016-12-16 01:07:56 +08:00
fn full(&self) -> bool {
self.length == self.storage.len()
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
/// Enqueue an element into the buffer, and return a pointer to it, or return
/// `Err(Error::Exhausted)` if the buffer is full.
2016-12-19 03:40:02 +08:00
pub fn enqueue(&mut self) -> Result<&mut Packet<'b>, Error> {
2016-12-16 01:07:56 +08:00
if self.full() {
Err(Error::Exhausted)
} else {
let index = self.mask(self.read_at + self.length);
2016-12-19 03:40:02 +08:00
let result = &mut self.storage[index];
2016-12-16 01:07:56 +08:00
self.length += 1;
Ok(result)
2016-12-15 01:39:44 +08:00
}
}
2016-12-16 01:07:56 +08:00
/// Dequeue an element from the buffer, and return a pointer to it, or return
/// `Err(Error::Exhausted)` if the buffer is empty.
2016-12-19 03:40:02 +08:00
pub fn dequeue(&mut self) -> Result<&Packet<'b>, Error> {
2016-12-16 01:07:56 +08:00
if self.empty() {
Err(Error::Exhausted)
} else {
self.length -= 1;
let result = &self.storage[self.read_at];
2016-12-16 01:07:56 +08:00
self.read_at = self.incr(self.read_at);
Ok(result)
2016-12-15 01:39:44 +08:00
}
}
}
/// An User Datagram Protocol socket.
///
/// An UDP socket is bound to a specific endpoint, and owns transmit and receive
/// packet buffers.
2016-12-17 14:27:08 +08:00
pub struct UdpSocket<'a, 'b: 'a> {
2016-12-15 01:39:44 +08:00
endpoint: Endpoint,
2016-12-17 14:27:08 +08:00
rx_buffer: Buffer<'a, 'b>,
tx_buffer: Buffer<'a, 'b>
2016-12-15 01:39:44 +08:00
}
2016-12-17 14:27:08 +08:00
impl<'a, 'b> UdpSocket<'a, 'b> {
2016-12-15 01:39:44 +08:00
/// Create an UDP socket with the given buffers.
2016-12-17 14:27:08 +08:00
pub fn new(endpoint: Endpoint, rx_buffer: Buffer<'a, 'b>, tx_buffer: Buffer<'a, 'b>)
-> Socket<'a, 'b> {
2016-12-17 13:12:45 +08:00
Socket::Udp(UdpSocket {
2016-12-15 01:39:44 +08:00
endpoint: endpoint,
rx_buffer: rx_buffer,
tx_buffer: tx_buffer
2016-12-17 13:12:45 +08:00
})
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
/// Enqueue a packet to be sent to a given remote endpoint, and return a pointer
/// to its payload.
2016-12-15 01:39:44 +08:00
///
2016-12-16 01:07:56 +08:00
/// This function returns `Err(Error::Exhausted)` if the size is greater than what
/// the transmit buffer can accomodate.
pub fn send(&mut self, endpoint: Endpoint, size: usize) -> Result<&mut [u8], Error> {
let packet_buf = try!(self.tx_buffer.enqueue());
packet_buf.endpoint = endpoint;
packet_buf.size = size;
2016-12-17 13:12:45 +08:00
Ok(&mut packet_buf.as_mut()[..size])
}
/// Enqueue a packete to be sent to a given remote endpoint, and fill it from a slice.
///
/// See also [send](#method.send).
pub fn send_slice(&mut self, endpoint: Endpoint, data: &[u8]) -> Result<(), Error> {
let buffer = try!(self.send(endpoint, data.len()));
Ok(buffer.copy_from_slice(data))
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
/// Dequeue a packet received from a remote endpoint, and return the endpoint as well
/// as a pointer to the payload.
2016-12-15 01:39:44 +08:00
///
2016-12-16 01:07:56 +08:00
/// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
2016-12-17 13:12:45 +08:00
pub fn recv(&mut self) -> Result<(Endpoint, &[u8]), Error> {
2016-12-16 01:07:56 +08:00
let packet_buf = try!(self.rx_buffer.dequeue());
2016-12-17 13:12:45 +08:00
Ok((packet_buf.endpoint, &packet_buf.as_ref()[..packet_buf.size]))
}
/// Dequeue a packet received from a remote endpoint, and return the endpoint as well
/// as copy the payload into the given slice.
///
/// This function returns `Err(Error::Exhausted)` if the received packet has payload
/// larger than the provided slice. See also [recv](#method.recv).
pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(Endpoint, usize), Error> {
let (endpoint, buffer) = try!(self.recv());
if data.len() < buffer.len() { return Err(Error::Exhausted) }
data[..buffer.len()].copy_from_slice(buffer);
Ok((endpoint, buffer.len()))
2016-12-15 01:39:44 +08:00
}
2016-12-17 13:12:45 +08:00
/// See [Socket::collect](enum.Socket.html#method.collect).
pub fn collect(&mut self, src_addr: &Address, dst_addr: &Address,
protocol: ProtocolType, payload: &[u8])
-> Result<(), Error> {
if protocol != ProtocolType::Udp { return Err(Error::Rejected) }
let packet = try!(UdpPacket::new(payload));
let repr = try!(UdpRepr::parse(&packet, src_addr, dst_addr));
2016-12-15 01:39:44 +08:00
if repr.dst_port != self.endpoint.port { return Err(Error::Rejected) }
if !self.endpoint.addr.is_unspecified() {
if self.endpoint.addr != *dst_addr { return Err(Error::Rejected) }
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
let packet_buf = try!(self.rx_buffer.enqueue());
packet_buf.endpoint = Endpoint { addr: *src_addr, port: repr.src_port };
packet_buf.size = repr.payload.len();
2016-12-17 13:12:45 +08:00
packet_buf.as_mut()[..repr.payload.len()].copy_from_slice(repr.payload);
2016-12-16 01:07:56 +08:00
Ok(())
2016-12-15 01:39:44 +08:00
}
2016-12-17 13:12:45 +08:00
/// See [Socket::dispatch](enum.Socket.html#method.dispatch).
pub fn dispatch(&mut self, f: &mut FnMut(&Address, &Address,
ProtocolType, &PacketRepr) -> Result<(), Error>)
-> Result<(), Error> {
2016-12-16 01:07:56 +08:00
let packet_buf = try!(self.tx_buffer.dequeue());
f(&self.endpoint.addr,
&packet_buf.endpoint.addr,
ProtocolType::Udp,
&UdpRepr {
src_port: self.endpoint.port,
dst_port: packet_buf.endpoint.port,
2016-12-17 13:12:45 +08:00
payload: &packet_buf.as_ref()[..]
2016-12-16 01:07:56 +08:00
})
2016-12-15 01:39:44 +08:00
}
}
impl<'a> PacketRepr for UdpRepr<'a> {
2016-12-20 07:50:04 +08:00
fn buffer_len(&self) -> usize {
self.buffer_len()
}
fn emit(&self, src_addr: &Address, dst_addr: &Address, payload: &mut [u8]) {
let mut packet = UdpPacket::new(payload).expect("undersized payload slice");
self.emit(&mut packet, src_addr, dst_addr)
}
}
2016-12-16 01:07:56 +08:00
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn test_buffer() {
let mut storage = vec![];
for _ in 0..5 {
2016-12-19 03:40:02 +08:00
storage.push(Packet::new(vec![0]))
2016-12-16 01:07:56 +08:00
}
let mut buffer = Buffer::new(&mut storage[..]);
assert_eq!(buffer.empty(), true);
assert_eq!(buffer.full(), false);
buffer.enqueue().unwrap().size = 1;
assert_eq!(buffer.empty(), false);
assert_eq!(buffer.full(), false);
buffer.enqueue().unwrap().size = 2;
buffer.enqueue().unwrap().size = 3;
assert_eq!(buffer.dequeue().unwrap().size, 1);
assert_eq!(buffer.dequeue().unwrap().size, 2);
buffer.enqueue().unwrap().size = 4;
buffer.enqueue().unwrap().size = 5;
buffer.enqueue().unwrap().size = 6;
buffer.enqueue().unwrap().size = 7;
assert_eq!(buffer.enqueue().unwrap_err(), Error::Exhausted);
assert_eq!(buffer.empty(), false);
assert_eq!(buffer.full(), true);
assert_eq!(buffer.dequeue().unwrap().size, 3);
assert_eq!(buffer.dequeue().unwrap().size, 4);
assert_eq!(buffer.dequeue().unwrap().size, 5);
assert_eq!(buffer.dequeue().unwrap().size, 6);
assert_eq!(buffer.dequeue().unwrap().size, 7);
assert_eq!(buffer.dequeue().unwrap_err(), Error::Exhausted);
assert_eq!(buffer.empty(), true);
assert_eq!(buffer.full(), false);
}
}