Skip to main content

sqlx_pg_ext_uint/
c_u64.rs

1use std::error::Error as StdError;
2
3use sqlx::{
4    Decode, Encode, Postgres, Type,
5    encode::IsNull,
6    postgres::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef},
7};
8
9const PG_EXT_TYPE: &str = "uint8";
10const PG_ARRAY_EXT_TYPE: &str = "uint8[]";
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
13pub struct U64 {
14    value: u64,
15}
16
17impl From<u64> for U64 {
18    fn from(value: u64) -> Self {
19        Self { value }
20    }
21}
22
23impl From<U64> for u64 {
24    fn from(value: U64) -> Self {
25        value.value
26    }
27}
28
29impl U64 {
30    pub fn get_type_size() -> usize {
31        std::mem::size_of::<u64>()
32    }
33}
34
35impl<'q> Encode<'q, Postgres> for U64 {
36    fn encode_by_ref(
37        &self,
38        buf: &mut PgArgumentBuffer,
39    ) -> Result<IsNull, Box<dyn StdError + Send + Sync + 'static>> {
40        let bytes = self.value.to_be_bytes();
41        if bytes.len() != Self::get_type_size() {
42            return Err(format!(
43                "Invalid size for u64, data_len: {}, expected: {}",
44                bytes.len(),
45                Self::get_type_size()
46            )
47            .into());
48        }
49        <[u8; _] as Encode<Postgres>>::encode_by_ref(&bytes, buf)
50    }
51    fn size_hint(&self) -> usize {
52        Self::get_type_size()
53    }
54}
55
56impl<'r> Decode<'r, Postgres> for U64 {
57    fn decode(value: PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
58        let bytes = <[u8; _] as Decode<Postgres>>::decode(value)?;
59        if bytes.len() != Self::get_type_size() {
60            return Err(format!(
61                "Invalid size for u64, data_len: {}, expected: {}",
62                bytes.len(),
63                Self::get_type_size()
64            )
65            .into());
66        }
67        Ok(u64::from_be_bytes(bytes).into())
68    }
69}
70
71impl Type<Postgres> for U64 {
72    fn type_info() -> PgTypeInfo {
73        PgTypeInfo::with_name(PG_EXT_TYPE)
74    }
75}
76
77impl PgHasArrayType for U64 {
78    fn array_type_info() -> PgTypeInfo {
79        PgTypeInfo::with_name(PG_ARRAY_EXT_TYPE)
80    }
81}