Skip to content

Commit 59ad2ec

Browse files
authored
Add support for IpAddr (#1822)
1 parent 339e058 commit 59ad2ec

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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::postgres::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef, Postgres};
9+
use crate::types::Type;
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) -> IsNull {
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+
}

sqlx-core/src/postgres/types/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,9 @@ mod json;
205205
#[cfg(feature = "ipnetwork")]
206206
mod ipnetwork;
207207

208+
#[cfg(feature = "ipnetwork")]
209+
mod ipaddr;
210+
208211
#[cfg(feature = "mac_address")]
209212
mod mac_address;
210213

0 commit comments

Comments
 (0)