| 1 | use std::net::IpAddr; |
| 2 | |
| 3 | use ipnetwork::IpNetwork; |
| 4 | |
| 5 | use crate::decode::Decode; |
| 6 | use crate::encode::{Encode, IsNull}; |
| 7 | use crate::error::BoxDynError; |
| 8 | use crate::types::Type; |
| 9 | use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef, Postgres}; |
| 10 | |
| 11 | impl Type<Postgres> for IpAddr |
| 12 | where |
| 13 | IpNetwork: Type<Postgres>, |
| 14 | { |
| 15 | fn type_info() -> PgTypeInfo { |
| 16 | IpNetwork::type_info() |
| 17 | } |
| 18 | |
| 19 | fn compatible(ty: &PgTypeInfo) -> bool { |
| 20 | IpNetwork::compatible(ty) |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | impl PgHasArrayType for IpAddr { |
| 25 | fn array_type_info() -> PgTypeInfo { |
| 26 | <IpNetwork as PgHasArrayType>::array_type_info() |
| 27 | } |
| 28 | |
| 29 | fn array_compatible(ty: &PgTypeInfo) -> bool { |
| 30 | <IpNetwork as PgHasArrayType>::array_compatible(ty) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl<'db> Encode<'db, Postgres> for IpAddr |
| 35 | where |
| 36 | IpNetwork: Encode<'db, Postgres>, |
| 37 | { |
| 38 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 39 | IpNetwork::from(*self).encode_by_ref(buf) |
| 40 | } |
| 41 | |
| 42 | fn size_hint(&self) -> usize { |
| 43 | IpNetwork::from(*self).size_hint() |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | impl<'db> Decode<'db, Postgres> for IpAddr |
| 48 | where |
| 49 | IpNetwork: Decode<'db, Postgres>, |
| 50 | { |
| 51 | fn decode(value: PgValueRef<'db>) -> Result<Self, BoxDynError> { |
| 52 | let ipnetwork = IpNetwork::decode(value)?; |
| 53 | |
| 54 | if ipnetwork.is_ipv4() && ipnetwork.prefix() != 32 |
| 55 | || ipnetwork.is_ipv6() && ipnetwork.prefix() != 128 |
| 56 | { |
| 57 | Err("lossy decode from inet/cidr")? |
| 58 | } |
| 59 | |
| 60 | Ok(ipnetwork.ip()) |
| 61 | } |
| 62 | } |