sqlx_core/any/types/
blob.rs

1use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
2use crate::database::Database;
3use crate::decode::Decode;
4use crate::encode::{Encode, IsNull};
5use crate::error::BoxDynError;
6use crate::types::Type;
7use std::borrow::Cow;
8
9impl Type<Any> for [u8] {
10    fn type_info() -> AnyTypeInfo {
11        AnyTypeInfo {
12            kind: AnyTypeInfoKind::Blob,
13        }
14    }
15}
16
17impl<'q> Encode<'q, Any> for &'q [u8] {
18    fn encode_by_ref(
19        &self,
20        buf: &mut <Any as Database>::ArgumentBuffer<'q>,
21    ) -> Result<IsNull, BoxDynError> {
22        buf.0.push(AnyValueKind::Blob((*self).into()));
23        Ok(IsNull::No)
24    }
25}
26
27impl<'r> Decode<'r, Any> for &'r [u8] {
28    fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
29        match value.kind {
30            AnyValueKind::Blob(Cow::Borrowed(blob)) => Ok(blob),
31            // This shouldn't happen in practice, it means the user got an `AnyValueRef`
32            // constructed from an owned `Vec<u8>` which shouldn't be allowed by the API.
33            AnyValueKind::Blob(Cow::Owned(_text)) => {
34                panic!("attempting to return a borrow that outlives its buffer")
35            }
36            other => other.unexpected(),
37        }
38    }
39}
40
41impl Type<Any> for Vec<u8> {
42    fn type_info() -> AnyTypeInfo {
43        <[u8] as Type<Any>>::type_info()
44    }
45}
46
47impl<'q> Encode<'q, Any> for Vec<u8> {
48    fn encode_by_ref(
49        &self,
50        buf: &mut <Any as Database>::ArgumentBuffer<'q>,
51    ) -> Result<IsNull, BoxDynError> {
52        buf.0.push(AnyValueKind::Blob(Cow::Owned(self.clone())));
53        Ok(IsNull::No)
54    }
55}
56
57impl<'r> Decode<'r, Any> for Vec<u8> {
58    fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
59        match value.kind {
60            AnyValueKind::Blob(blob) => Ok(blob.into_owned()),
61            other => other.unexpected(),
62        }
63    }
64}