http1/protocol/
connection.rs

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
use std::{
    fmt::Debug,
    io::{Read, Write},
    net::{SocketAddr, TcpStream},
};

use super::h1::io::IoStream;

/// Represents a request connection stream to read the request and write the response.
pub enum Connection {
    Tcp(TcpStream),
    Io(IoStream),
}

impl Connection {
    pub fn from_io<T>(io: T) -> Self
    where
        T: Read + Write + Send + Sync + 'static,
    {
        Connection::Io(IoStream::new(io))
    }

    pub fn try_clone(&self) -> Option<Connection> {
        match self {
            Connection::Tcp(tcp_stream) => tcp_stream.try_clone().ok().map(Connection::Tcp),
            Connection::Io(io) => Some(Connection::Io(io.clone())),
        }
    }

    pub fn peer_addr(&self) -> Option<SocketAddr> {
        match self {
            Connection::Tcp(tcp_stream) => tcp_stream.peer_addr().ok(),
            Connection::Io(_) => None,
        }
    }
}

impl Debug for Connection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Connection")
    }
}

impl Read for Connection {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            Connection::Tcp(tcp_stream) => Read::read(tcp_stream, buf),
            Connection::Io(arc) => Read::read(arc, buf),
        }
    }
}

impl Write for Connection {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            Connection::Tcp(tcp_stream) => Write::write(tcp_stream, buf),
            Connection::Io(arc) => Write::write(arc, buf),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            Connection::Tcp(tcp_stream) => Write::flush(tcp_stream),
            Connection::Io(arc) => Write::flush(arc),
        }
    }
}

/// Request connection information after a request is accepted.
#[derive(Clone)]
pub struct Connected {
    peer_addr: Option<SocketAddr>,
}

impl Connected {
    pub fn from_connection(conn: &Connection) -> Self {
        Connected {
            peer_addr: conn.peer_addr(),
        }
    }

    pub fn peer_addr(&self) -> Option<SocketAddr> {
        self.peer_addr
    }
}