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