Skip to content

Commit

Permalink
Add support for IpAddr
Browse files Browse the repository at this point in the history
  • Loading branch information
meh committed Apr 20, 2022
1 parent b934f82 commit 7f9c21d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
56 changes: 56 additions & 0 deletions sqlx-core/src/postgres/types/ipaddr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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> {
IpNetwork::decode(value).map(|n| n.ip())
}
}
3 changes: 3 additions & 0 deletions sqlx-core/src/postgres/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ mod json;
#[cfg(feature = "ipnetwork")]
mod ipnetwork;

#[cfg(feature = "ipnetwork")]
mod ipaddr;

#[cfg(feature = "mac_address")]
mod mac_address;

Expand Down

0 comments on commit 7f9c21d

Please sign in to comment.