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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use amplify::Bipolar;
use inet2_addr::InetSocketAddr;
use super::{Duplex, Error, RecvFrame, SendFrame};
use crate::session::noise;
use crate::transport::generic::{self, TcpInetStream};
#[derive(Debug, From)]
pub struct Stream(TcpStream);
pub type Connection = generic::Connection<Stream>;
impl Stream {
#[inline]
pub fn with(stream: TcpStream) -> Stream { Stream::from(stream) }
}
impl Connection {
pub fn connect(inet_addr: InetSocketAddr) -> Result<Self, Error> {
let stream = TcpStream::connect_inet_socket(inet_addr)?;
Ok(Connection::with(stream, inet_addr))
}
pub fn accept(listener: &TcpListener) -> Result<Self, Error> {
let (stream, inet_addr) = TcpStream::accept_inet_socket(listener)?;
Ok(Connection::with(stream, inet_addr.into()))
}
}
impl generic::Stream for Stream {}
impl Bipolar for Stream {
type Left = Stream;
type Right = Stream;
#[inline]
fn join(left: Self::Left, right: Self::Right) -> Self {
Stream::from(TcpStream::join(left.0, right.0))
}
#[inline]
fn split(self) -> (Self::Left, Self::Right) {
let (l, r) = self.0.split();
(Stream::from(l), Stream::from(r))
}
}
impl Duplex for Stream {
#[inline]
fn as_receiver(&mut self) -> &mut dyn RecvFrame { self }
#[inline]
fn as_sender(&mut self) -> &mut dyn SendFrame { self }
#[inline]
fn split(self) -> (Box<dyn RecvFrame + Send>, Box<dyn SendFrame + Send>) {
let (r, s) = Bipolar::split(self);
(Box::new(r), Box::new(s))
}
}
impl RecvFrame for Stream {
fn recv_frame(&mut self) -> Result<Vec<u8>, Error> {
let mut buf: Vec<u8> =
vec![0u8; noise::TAGGED_MESSAGE_LENGTH_HEADER_SIZE];
self.0.read_exact(&mut buf)?;
Ok(buf)
}
#[inline]
fn recv_raw(&mut self, len: usize) -> Result<Vec<u8>, Error> {
self.0.recv_raw(len)
}
}
impl SendFrame for Stream {
#[inline]
fn send_frame(&mut self, data: &[u8]) -> Result<usize, Error> {
self.0.send_frame(data)
}
#[inline]
fn send_raw(&mut self, data: &[u8]) -> Result<usize, Error> {
self.0.send_raw(data)
}
}