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