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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use super::constant;
use super::shared_internal::*;
use failure::Error;
use futures_io::{AsyncRead, AsyncWrite};
use futures_util::{AsyncReadExt, AsyncWriteExt};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Address {
    IPv4([u8; 4]),
    IPv6([u8; 16]),
    DomainName(Vec<u8>),
}

impl Address {
    pub async fn read<AR>(reader: &mut AR) -> Result<Self, Error>
    where
        AR: AsyncRead + Unpin,
    {
        let address_type = read_u8(reader).await?;
        match address_type {
            constant::address_type::IPV4 => {
                let mut buf = [0u8; 4];
                reader.read_exact(buf.as_mut()).await?;
                Ok(Address::IPv4(buf))
            }
            constant::address_type::IPV6 => {
                let mut buf = [0u8; 16];
                reader.read_exact(buf.as_mut()).await?;
                Ok(Address::IPv6(buf))
            }
            constant::address_type::DOMAIN_NAME => {
                let len = read_u8(reader).await?;
                let v = read_vec(reader, len as usize).await?;
                Ok(Address::DomainName(v))
            }
            _ => Err(crate::error::InvalidAddressTypeError(address_type))?,
        }
    }

    pub async fn write<AW>(&self, writer: &mut AW) -> std::io::Result<()>
    where
        AW: AsyncWrite + Unpin,
    {
        match self {
            Address::IPv4(val) => {
                let head = [constant::address_type::IPV4];
                writer.write_all(&head).await?;
                writer.write_all(val).await?;
                Ok(())
            }
            Address::IPv6(val) => {
                let head = [constant::address_type::IPV6];
                writer.write_all(&head).await?;
                writer.write_all(val).await?;
                Ok(())
            }
            Address::DomainName(val) => {
                let head = [constant::address_type::DOMAIN_NAME, val.len() as u8];
                writer.write_all(&head).await?;
                writer.write_all(val).await?;
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test_util::*;
    use futures_util::io::Cursor;

    #[test]
    fn read_invalid_type() {
        let mut reader = Cursor::new(&[0x2]);
        let future = Address::read(&mut reader);
        let result = extract_future_output(future);
        let err = result.unwrap_err();
        let err = err
            .downcast::<crate::error::InvalidAddressTypeError>()
            .unwrap();
        assert_eq!(err, crate::error::InvalidAddressTypeError(0x2));
    }

    #[test]
    fn read_ipv4_ok() {
        let mut reader = Cursor::new(&[constant::address_type::IPV4, 127, 0, 0, 1]);
        let future = Address::read(&mut reader);
        let result = extract_future_output(future);
        assert_eq!(result.unwrap(), Address::IPv4([127, 0, 0, 1]));
    }

    #[test]
    fn read_ipv6_ok() {
        let mut reader = Cursor::new(&[
            constant::address_type::IPV6,
            1,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0xFF,
        ]);
        let future = Address::read(&mut reader);
        let result = extract_future_output(future);
        assert_eq!(
            result.unwrap(),
            Address::IPv6([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF])
        );
    }

    #[test]
    fn read_domain_name_ok() {
        let mut reader = Cursor::new(&[
            constant::address_type::DOMAIN_NAME,
            11,
            'e' as u8,
            'x' as u8,
            'a' as u8,
            'm' as u8,
            'p' as u8,
            'l' as u8,
            'e' as u8,
            '.' as u8,
            'c' as u8,
            'o' as u8,
            'm' as u8,
        ]);
        let future = Address::read(&mut reader);
        let result = extract_future_output(future);
        assert_eq!(
            result.unwrap(),
            Address::DomainName("example.com".as_bytes().to_vec())
        );
    }

    #[test]
    fn write_ipv4_ok() {
        let mut writer = [0u8; 1 + 4];
        let mut writer = Cursor::new(&mut writer[..]);
        let res = Address::IPv4([127, 0, 0, 1]);
        let future = res.write(&mut writer);
        let result = extract_future_output(future);
        assert_eq!(result.unwrap(), ());
        assert_eq!(writer.into_inner(), [0x1, 127, 0, 0, 1])
    }

    #[test]
    fn write_ipv6_ok() {
        let mut writer = [0u8; 1 + 16];
        let mut writer = Cursor::new(&mut writer[..]);
        let res = Address::IPv6([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF]);
        let future = res.write(&mut writer);
        let result = extract_future_output(future);
        assert_eq!(result.unwrap(), ());
        assert_eq!(
            writer.into_inner(),
            [0x4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF]
        )
    }

    #[test]
    fn write_domain_name_ok() {
        let mut writer = [0u8; 1 + 1 + 11];
        let mut writer = Cursor::new(&mut writer[..]);
        let res = Address::DomainName("example.com".as_bytes().to_vec());
        let future = res.write(&mut writer);
        let result = extract_future_output(future);
        assert_eq!(result.unwrap(), ());
        assert_eq!(
            writer.into_inner(),
            [
                0x3, 11, 'e' as u8, 'x' as u8, 'a' as u8, 'm' as u8, 'p' as u8, 'l' as u8,
                'e' as u8, '.' as u8, 'c' as u8, 'o' as u8, 'm' as u8,
            ]
        )
    }
}