Skip to content

Commit e122aeb

Browse files
authored
feat: Add Sqlx Traits for Signed Type (#1008)
1 parent 781f4bb commit e122aeb

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

crates/primitives/src/sqlx.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
use alloc::{boxed::Box, vec::Vec};
99

10+
use ruint::support::sqlx::DecodeError;
1011
use sqlx_core::{
1112
database::Database,
1213
decode::Decode,
@@ -15,7 +16,7 @@ use sqlx_core::{
1516
types::Type,
1617
};
1718

18-
use crate::FixedBytes;
19+
use crate::{FixedBytes, Signed};
1920

2021
impl<const BYTES: usize, DB> Type<DB> for FixedBytes<BYTES>
2122
where
@@ -54,3 +55,38 @@ where
5455
Self::try_from(bytes.as_slice()).map_err(|e| Box::new(e) as BoxDynError)
5556
}
5657
}
58+
59+
impl<const BITS: usize, const LIMBS: usize, DB: Database> Type<DB> for Signed<BITS, LIMBS>
60+
where
61+
Vec<u8>: Type<DB>,
62+
{
63+
fn type_info() -> DB::TypeInfo {
64+
<Vec<u8> as Type<DB>>::type_info()
65+
}
66+
67+
fn compatible(ty: &DB::TypeInfo) -> bool {
68+
<Vec<u8> as Type<DB>>::compatible(ty)
69+
}
70+
}
71+
72+
impl<'a, const BITS: usize, const LIMBS: usize, DB: Database> Encode<'a, DB> for Signed<BITS, LIMBS>
73+
where
74+
Vec<u8>: Encode<'a, DB>,
75+
{
76+
fn encode_by_ref(
77+
&self,
78+
buf: &mut <DB as Database>::ArgumentBuffer<'a>,
79+
) -> Result<IsNull, BoxDynError> {
80+
self.0.to_be_bytes_vec().encode_by_ref(buf)
81+
}
82+
}
83+
84+
impl<'a, const BITS: usize, const LIMBS: usize, DB: Database> Decode<'a, DB> for Signed<BITS, LIMBS>
85+
where
86+
Vec<u8>: Decode<'a, DB>,
87+
{
88+
fn decode(value: <DB as Database>::ValueRef<'a>) -> Result<Self, BoxDynError> {
89+
let bytes = Vec::<u8>::decode(value)?;
90+
Self::try_from_be_slice(bytes.as_slice()).ok_or_else(|| DecodeError::Overflow.into())
91+
}
92+
}

0 commit comments

Comments
 (0)