|
| 1 | +use mac_address::MacAddress; |
| 2 | + |
| 3 | +use std::convert::TryInto; |
| 4 | + |
| 5 | +use crate::decode::Decode; |
| 6 | +use crate::encode::{Encode, IsNull}; |
| 7 | +use crate::error::BoxDynError; |
| 8 | +use crate::postgres::{PgArgumentBuffer, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 9 | +use crate::types::Type; |
| 10 | + |
| 11 | +impl Type<Postgres> for MacAddress { |
| 12 | + fn type_info() -> PgTypeInfo { |
| 13 | + PgTypeInfo::MACADDR |
| 14 | + } |
| 15 | + |
| 16 | + fn compatible(ty: &PgTypeInfo) -> bool { |
| 17 | + *ty == PgTypeInfo::MACADDR |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +impl Type<Postgres> for [MacAddress] { |
| 22 | + fn type_info() -> PgTypeInfo { |
| 23 | + PgTypeInfo::MACADDR_ARRAY |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +impl Type<Postgres> for Vec<MacAddress> { |
| 28 | + fn type_info() -> PgTypeInfo { |
| 29 | + <[MacAddress] as Type<Postgres>>::type_info() |
| 30 | + } |
| 31 | + |
| 32 | + fn compatible(ty: &PgTypeInfo) -> bool { |
| 33 | + <[MacAddress] as Type<Postgres>>::compatible(ty) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl Encode<'_, Postgres> for MacAddress { |
| 38 | + fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull { |
| 39 | + buf.extend_from_slice(&self.bytes()); // write just the address |
| 40 | + IsNull::No |
| 41 | + } |
| 42 | + |
| 43 | + fn size_hint(&self) -> usize { |
| 44 | + 6 |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl Decode<'_, Postgres> for MacAddress { |
| 49 | + fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 50 | + let bytes = match value.format() { |
| 51 | + PgValueFormat::Binary => value.as_bytes()?, |
| 52 | + PgValueFormat::Text => { |
| 53 | + return Ok(value.as_str()?.parse()?); |
| 54 | + } |
| 55 | + }; |
| 56 | + |
| 57 | + if bytes.len() == 6 { |
| 58 | + return Ok(MacAddress::new(bytes.try_into().unwrap())); |
| 59 | + } |
| 60 | + |
| 61 | + Err("invalid data received when expecting an MACADDR".into()) |
| 62 | + } |
| 63 | +} |
0 commit comments