alloy_primitives/
sqlx.rs

1//! Support for the [`sqlx`](https://crates.io/crates/sqlx) crate.
2//!
3//! Supports big-endian binary serialization via sqlx binary types (e.g., BINARY(N), BYTEA, BLOB).
4//! Similar to [`ruint`'s implementation](https://github.com/recmo/uint/blob/main/src/support/sqlx.rs)
5
6#![cfg_attr(docsrs, doc(cfg(feature = "sqlx")))]
7
8use alloc::{boxed::Box, vec::Vec};
9
10use sqlx_core::{
11    database::Database,
12    decode::Decode,
13    encode::{Encode, IsNull},
14    error::BoxDynError,
15    types::Type,
16};
17
18use crate::FixedBytes;
19
20impl<const BYTES: usize, DB> Type<DB> for FixedBytes<BYTES>
21where
22    DB: Database,
23    Vec<u8>: Type<DB>,
24{
25    fn type_info() -> DB::TypeInfo {
26        <Vec<u8> as Type<DB>>::type_info()
27    }
28
29    fn compatible(ty: &DB::TypeInfo) -> bool {
30        <Vec<u8> as Type<DB>>::compatible(ty)
31    }
32}
33
34impl<'a, const BYTES: usize, DB> Encode<'a, DB> for FixedBytes<BYTES>
35where
36    DB: Database,
37    Vec<u8>: Encode<'a, DB>,
38{
39    fn encode_by_ref(
40        &self,
41        buf: &mut <DB as Database>::ArgumentBuffer<'a>,
42    ) -> Result<IsNull, BoxDynError> {
43        self.as_slice().to_vec().encode_by_ref(buf)
44    }
45}
46
47impl<'a, const BYTES: usize, DB> Decode<'a, DB> for FixedBytes<BYTES>
48where
49    DB: Database,
50    Vec<u8>: Decode<'a, DB>,
51{
52    fn decode(value: <DB as Database>::ValueRef<'a>) -> Result<Self, BoxDynError> {
53        let bytes = Vec::<u8>::decode(value)?;
54        Self::try_from(bytes.as_slice()).map_err(|e| Box::new(e) as BoxDynError)
55    }
56}