postgres_types_extra/
pg_xid.rs

1use bytes::BytesMut;
2use postgres_types::{IsNull, accepts, to_sql_checked};
3
4use std::fmt::Display;
5
6use postgres_types::{FromSql, ToSql, Type};
7use std::{error::Error, fmt::Formatter};
8
9#[derive(Clone, Debug, Default, Eq, PartialEq)]
10pub struct PgXid(u32);
11
12impl<'a> FromSql<'a> for PgXid {
13    fn from_sql(_: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
14        // XIDs are stored as 4-byte big-endian
15        let array: [u8; 4] = raw.try_into().expect("Bad Xid");
16        let res = u32::from_be_bytes(array);
17
18        Ok(Self(res))
19    }
20
21    accepts!(XID);
22}
23
24impl ToSql for PgXid {
25    fn to_sql(&self, _: &Type, out: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
26        out.extend_from_slice(&self.0.to_be_bytes());
27        Ok(IsNull::No)
28    }
29
30    accepts!(XID);
31    to_sql_checked!();
32}
33
34impl Display for PgXid {
35    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36        write!(f, "{}", self.0)?;
37
38        Ok(())
39    }
40}