Skip to content

Commit ed0828b

Browse files
committedJul 24, 2017
Simplify impls of AsSocket.
1 parent c5aa371 commit ed0828b

File tree

1 file changed

+21
-43
lines changed

1 file changed

+21
-43
lines changed
 

‎src/socket/mod.rs

+21-43
Original file line numberDiff line numberDiff line change
@@ -109,50 +109,28 @@ pub trait AsSocket<T> {
109109
fn try_as_socket(&mut self) -> Option<&mut T>;
110110
}
111111

112-
impl<'a, 'b> AsSocket<RawSocket<'a, 'b>> for Socket<'a, 'b> {
113-
fn as_socket(&mut self) -> &mut RawSocket<'a, 'b> {
114-
match self {
115-
&mut Socket::Raw(ref mut socket) => socket,
116-
_ => panic!(".as_socket::<RawSocket> called on wrong socket type")
117-
}
118-
}
119-
120-
fn try_as_socket(&mut self) -> Option<&mut RawSocket<'a, 'b>> {
121-
match self {
122-
&mut Socket::Raw(ref mut socket) => Some(socket),
123-
_ => None,
124-
}
125-
}
126-
}
127-
128-
impl<'a, 'b> AsSocket<UdpSocket<'a, 'b>> for Socket<'a, 'b> {
129-
fn as_socket(&mut self) -> &mut UdpSocket<'a, 'b> {
130-
match self {
131-
&mut Socket::Udp(ref mut socket) => socket,
132-
_ => panic!(".as_socket::<UdpSocket> called on wrong socket type")
133-
}
134-
}
135-
136-
fn try_as_socket(&mut self) -> Option<&mut UdpSocket<'a, 'b>> {
137-
match self {
138-
&mut Socket::Udp(ref mut socket) => Some(socket),
139-
_ => None,
112+
macro_rules! as_socket {
113+
($socket:ty, $variant:ident) => {
114+
impl<'a, 'b> AsSocket<$socket> for Socket<'a, 'b> {
115+
fn as_socket(&mut self) -> &mut $socket {
116+
match self {
117+
&mut Socket::$variant(ref mut socket) => socket,
118+
_ => panic!(concat!(".as_socket::<",
119+
stringify!($socket),
120+
"> called on wrong socket type"))
121+
}
122+
}
123+
124+
fn try_as_socket(&mut self) -> Option<&mut $socket> {
125+
match self {
126+
&mut Socket::$variant(ref mut socket) => Some(socket),
127+
_ => None,
128+
}
129+
}
140130
}
141131
}
142132
}
143133

144-
impl<'a, 'b> AsSocket<TcpSocket<'a>> for Socket<'a, 'b> {
145-
fn as_socket(&mut self) -> &mut TcpSocket<'a> {
146-
match self {
147-
&mut Socket::Tcp(ref mut socket) => socket,
148-
_ => panic!(".as_socket::<TcpSocket> called on wrong socket type")
149-
}
150-
}
151-
152-
fn try_as_socket(&mut self) -> Option<&mut TcpSocket<'a>> {
153-
match self {
154-
&mut Socket::Tcp(ref mut socket) => Some(socket),
155-
_ => None,
156-
}
157-
}
158-
}
134+
as_socket!(RawSocket<'a, 'b>, Raw);
135+
as_socket!(UdpSocket<'a, 'b>, Udp);
136+
as_socket!(TcpSocket<'a>, Tcp);

0 commit comments

Comments
 (0)