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
use std::net::IpAddr;

use ipnetwork::IpNetwork;

use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::postgres::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef, Postgres};
use crate::types::Type;

impl Type<Postgres> for IpAddr
where
    IpNetwork: Type<Postgres>,
{
    fn type_info() -> PgTypeInfo {
        IpNetwork::type_info()
    }

    fn compatible(ty: &PgTypeInfo) -> bool {
        IpNetwork::compatible(ty)
    }
}

impl PgHasArrayType for IpAddr {
    fn array_type_info() -> PgTypeInfo {
        <IpNetwork as PgHasArrayType>::array_type_info()
    }

    fn array_compatible(ty: &PgTypeInfo) -> bool {
        <IpNetwork as PgHasArrayType>::array_compatible(ty)
    }
}

impl<'db> Encode<'db, Postgres> for IpAddr
where
    IpNetwork: Encode<'db, Postgres>,
{
    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
        IpNetwork::from(*self).encode_by_ref(buf)
    }

    fn size_hint(&self) -> usize {
        IpNetwork::from(*self).size_hint()
    }
}

impl<'db> Decode<'db, Postgres> for IpAddr
where
    IpNetwork: Decode<'db, Postgres>,
{
    fn decode(value: PgValueRef<'db>) -> Result<Self, BoxDynError> {
        let ipnetwork = IpNetwork::decode(value)?;

        if ipnetwork.is_ipv4() && ipnetwork.prefix() != 32
            || ipnetwork.is_ipv6() && ipnetwork.prefix() != 128
        {
            Err("lossy decode from inet/cidr")?
        }

        Ok(ipnetwork.ip())
    }
}