rust/src/libstd/rt/io/net/udp.rs

108 lines
2.9 KiB
Rust
Raw Normal View History

// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
2013-06-19 17:23:55 -07:00
use option::{Option, Some, None};
use result::{Ok, Err};
2013-06-17 12:34:58 -07:00
use rt::io::net::ip::IpAddr;
2013-06-19 17:23:55 -07:00
use rt::io::{Reader, Writer};
use rt::io::{io_error, read_error, EndOfFile};
use rt::rtio::{RtioUdpSocketObject, RtioUdpSocket, IoFactory, IoFactoryObject};
use rt::local::Local;
pub struct UdpSocket {
rtsocket: ~RtioUdpSocketObject
}
impl UdpSocket {
fn new(s: ~RtioUdpSocketObject) -> UdpSocket {
UdpSocket { rtsocket: s }
}
pub fn bind(addr: IpAddr) -> Option<UdpSocket> {
let socket = unsafe {
let io = Local::unsafe_borrow::<IoFactoryObject>();
(*io).udp_bind(addr)
};
match socket {
Ok(s) => { Some(UdpSocket { rtsocket: s }) }
Err(ioerr) => {
io_error::cond.raise(ioerr);
return None;
}
}
}
pub fn recvfrom(&self, buf: &mut [u8]) -> Option<(uint, IpAddr)> {
match (*self.rtsocket).recvfrom(buf) {
Ok((nread, src)) => Some((nread, src)),
Err(ioerr) => {
// EOF is indicated by returning None
// XXX do we ever find EOF reading UDP packets?
if ioerr.kind != EndOfFile {
read_error::cond.raise(ioerr);
}
None
}
}
}
pub fn sendto(&self, buf: &[u8], dst: IpAddr) {
match (*self.rtsocket).sendto(buf, dst) {
Ok(_) => (),
Err(ioerr) => {
io_error::cond.raise(ioerr);
}
}
}
// XXX convert ~self to self eventually
pub fn connect(~self, other: IpAddr) -> UdpStream {
UdpStream { socket: self, connectedTo: other }
}
}
2013-06-17 12:34:58 -07:00
pub struct UdpStream {
2013-06-19 17:23:55 -07:00
socket: ~UdpSocket,
connectedTo: IpAddr
2013-06-17 12:34:58 -07:00
}
impl UdpStream {
2013-06-19 17:23:55 -07:00
pub fn as_socket<T>(&self, f: &fn(&UdpSocket) -> T) -> T {
f(self.socket)
2013-06-17 12:34:58 -07:00
}
2013-06-19 17:23:55 -07:00
pub fn disconnect(self) -> ~UdpSocket {
let UdpStream { socket: s, _ } = self;
s
}
}
impl Reader for UdpStream {
2013-06-19 17:23:55 -07:00
fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
let conn = self.connectedTo;
do self.as_socket |sock| {
sock.recvfrom(buf)
.map_consume(|(nread,src)| if src == conn {nread} else {0})
}
}
fn eof(&mut self) -> bool { fail!() }
}
impl Writer for UdpStream {
2013-06-19 17:23:55 -07:00
fn write(&mut self, buf: &[u8]) {
do self.as_socket |sock| {
sock.sendto(buf, self.connectedTo);
}
}
2013-06-19 17:23:55 -07:00
fn flush(&mut self) { fail!() }
}