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
use std::sync::Arc;
use std::net::Shutdown;
use std::io::{Read, Write, Error};
use futures::Poll;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_core::net::TcpStream;

pub struct SharedTcpStream {
	io: Arc<TcpStream>,
}

impl SharedTcpStream {
	pub fn new(a: Arc<TcpStream>) -> Self {
		SharedTcpStream {
			io: a,
		}
	}

	pub fn shutdown(&self) {
		// error is irrelevant here, the connection is dropped anyway
		let _ = self.io.shutdown(Shutdown::Both);
	}
}

impl From<TcpStream> for SharedTcpStream {
	fn from(a: TcpStream) -> Self {
		SharedTcpStream::new(Arc::new(a))
	}
}

impl Read for SharedTcpStream {
	fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
		Read::read(&mut (&*self.io as &TcpStream), buf)
	}
}

impl AsyncRead for SharedTcpStream {}

impl AsyncWrite for SharedTcpStream {
	fn shutdown(&mut self) -> Poll<(), Error> {
		self.io.shutdown(Shutdown::Both).map(Into::into)
	}
}

impl Write for SharedTcpStream {
	fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
		Write::write(&mut (&*self.io as &TcpStream), buf)
	}

	fn flush(&mut self) -> Result<(), Error> {
		Write::flush(&mut (&*self.io as &TcpStream))
	}
}

impl Clone for SharedTcpStream {
	fn clone(&self) -> Self {
		SharedTcpStream::new(self.io.clone())
	}
}