1use cdbc::decode::Decode;
2use cdbc::encode::{Encode, IsNull};
3use cdbc::error::BoxDynError;
4use crate::{
5 PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres,
6};
7use cdbc::types::Type;
8
9impl PgHasArrayType for u8 {
10 fn array_type_info() -> PgTypeInfo {
11 PgTypeInfo::BYTEA
12 }
13}
14
15impl PgHasArrayType for &'_ [u8] {
16 fn array_type_info() -> PgTypeInfo {
17 PgTypeInfo::BYTEA_ARRAY
18 }
19}
20
21impl PgHasArrayType for Vec<u8> {
22 fn array_type_info() -> PgTypeInfo {
23 <[&[u8]] as Type<Postgres>>::type_info()
24 }
25}
26
27impl Encode<'_, Postgres> for &'_ [u8] {
28 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
29 buf.extend_from_slice(self);
30
31 IsNull::No
32 }
33}
34
35impl Encode<'_, Postgres> for Vec<u8> {
36 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
37 <&[u8] as Encode<Postgres>>::encode(self, buf)
38 }
39}
40
41impl<'r> Decode<'r, Postgres> for &'r [u8] {
42 fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
43 match value.format() {
44 PgValueFormat::Binary => value.as_bytes(),
45 PgValueFormat::Text => {
46 Err("unsupported decode to `&[u8]` of BYTEA in a simple query; use a prepared query or decode to `Vec<u8>`".into())
47 }
48 }
49 }
50}
51
52impl Decode<'_, Postgres> for Vec<u8> {
53 fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
54 Ok(match value.format() {
55 PgValueFormat::Binary => value.as_bytes()?.to_owned(),
56 PgValueFormat::Text => {
57 hex::decode(&value.as_str()?[2..])?
59 }
60 })
61 }
62}