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
use std::cell::RefCell;
use std::fmt;
use std::io;
use std::net::{ToSocketAddrs, UdpSocket};
use IntoInner;
use socket::Socket;
use sys::c;
pub struct UdpBuilder {
socket: RefCell<Option<Socket>>,
}
impl UdpBuilder {
pub fn new_v4() -> io::Result<UdpBuilder> {
Socket::new(c::AF_INET, c::SOCK_DGRAM).map(::FromInner::from_inner)
}
pub fn new_v6() -> io::Result<UdpBuilder> {
Socket::new(c::AF_INET6, c::SOCK_DGRAM).map(::FromInner::from_inner)
}
pub fn bind<T>(&self, addr: T) -> io::Result<UdpSocket>
where T: ToSocketAddrs
{
try!(self.with_socket(|sock| {
let addr = try!(::one_addr(addr));
sock.bind(&addr)
}));
Ok(self.socket.borrow_mut().take().unwrap().into_inner().into_udp_socket())
}
fn with_socket<F>(&self, f: F) -> io::Result<()>
where F: FnOnce(&Socket) -> io::Result<()>
{
match *self.socket.borrow() {
Some(ref s) => f(s),
None => Err(io::Error::new(io::ErrorKind::Other,
"builder has already finished its socket")),
}
}
}
impl fmt::Debug for UdpBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "UdpBuilder {{ socket: {:?} }}",
self.socket.borrow().as_ref().unwrap())
}
}
impl ::AsInner for UdpBuilder {
type Inner = RefCell<Option<Socket>>;
fn as_inner(&self) -> &RefCell<Option<Socket>> { &self.socket }
}
impl ::FromInner for UdpBuilder {
type Inner = Socket;
fn from_inner(sock: Socket) -> UdpBuilder {
UdpBuilder { socket: RefCell::new(Some(sock)) }
}
}