mirror of
https://github.com/launchbadge/sqlx
synced 2024-11-10 14:34:19 +00:00
Add support for IpAddr (#1822)
This commit is contained in:
parent
339e0580ca
commit
59ad2ecc92
2 changed files with 65 additions and 0 deletions
62
sqlx-core/src/postgres/types/ipaddr.rs
Normal file
62
sqlx-core/src/postgres/types/ipaddr.rs
Normal file
|
@ -0,0 +1,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())
|
||||
}
|
||||
}
|
|
@ -205,6 +205,9 @@ mod json;
|
|||
#[cfg(feature = "ipnetwork")]
|
||||
mod ipnetwork;
|
||||
|
||||
#[cfg(feature = "ipnetwork")]
|
||||
mod ipaddr;
|
||||
|
||||
#[cfg(feature = "mac_address")]
|
||||
mod mac_address;
|
||||
|
||||
|
|
Loading…
Reference in a new issue