| 1 |
use std::io::prelude::*; |
| 2 |
|
| 3 |
use crate::deserialize::{self, FromSql}; |
| 4 |
use crate::pg::{Pg, PgValue}; |
| 5 |
use crate::serialize::{self, IsNull, Output, ToSql}; |
| 6 |
use crate::sql_types::MacAddr; |
| 7 |
|
| 8 |
#[allow(dead_code)] |
| 9 |
mod foreign_derives { |
| 10 |
use super::*; |
| 11 |
use crate::deserialize::FromSqlRow; |
| 12 |
use crate::expression::AsExpression; |
| 13 |
|
| 14 |
#[derive(AsExpression, FromSqlRow)] |
| 15 |
#[diesel(foreign_derive)] |
| 16 |
#[diesel(sql_type = MacAddr)] |
| 17 |
struct ByteArrayProxy([u8; 6]); |
| 18 |
} |
| 19 |
|
| 20 |
#[cfg(feature = "postgres_backend")] |
| 21 |
impl FromSql<MacAddr, Pg> for [u8; 6] { |
| 22 |
fn from_sql(value: PgValue<'_>) -> deserialize::Result<Self> { |
| 23 |
value |
| 24 |
.as_bytes() |
| 25 |
.try_into() |
| 26 |
.map_err(|_| "invalid network address format: input isn't 6 bytes.".into()) |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
#[cfg(feature = "postgres_backend")] |
| 31 |
impl ToSql<MacAddr, Pg> for [u8; 6] { |
| 32 |
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result { |
| 33 |
out.write_all(&self[..]) |
| 34 |
.map(|_| IsNull::No) |
| 35 |
.map_err(Into::into) |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
#[cfg(test)] |
| 40 |
#[diesel_test_helper::test] |
| 41 |
fn macaddr_roundtrip() { |
| 42 |
use crate::query_builder::bind_collector::ByteWrapper; |
| 43 |
|
| 44 |
let mut buffer = Vec::new(); |
| 45 |
let mut bytes = Output::test(ByteWrapper(&mut buffer)); |
| 46 |
let input_address = [0x52, 0x54, 0x00, 0xfb, 0xc6, 0x16]; |
| 47 |
ToSql::<MacAddr, Pg>::to_sql(&input_address, &mut bytes).unwrap(); |
| 48 |
let output_address: [u8; 6] = FromSql::from_sql(PgValue::for_test(&buffer)).unwrap(); |
| 49 |
assert_eq!(input_address, output_address); |
| 50 |
} |