Add impl for Type, Decode, and Encode for Box<str> and Box<[u8]> (#2712)

This commit is contained in:
Grant G
2023-09-11 19:28:18 -07:00
committed by GitHub
parent a6a2af115e
commit c0d4019d17
6 changed files with 155 additions and 0 deletions

View File

@@ -22,6 +22,12 @@ impl<const N: usize> PgHasArrayType for &'_ [u8; N] {
}
}
impl PgHasArrayType for Box<[u8]> {
fn array_type_info() -> PgTypeInfo {
<[&[u8]] as Type<Postgres>>::type_info()
}
}
impl PgHasArrayType for Vec<u8> {
fn array_type_info() -> PgTypeInfo {
<[&[u8]] as Type<Postgres>>::type_info()
@@ -42,6 +48,12 @@ impl Encode<'_, Postgres> for &'_ [u8] {
}
}
impl Encode<'_, Postgres> for Box<[u8]> {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
<&[u8] as Encode<Postgres>>::encode(self.as_ref(), buf)
}
}
impl Encode<'_, Postgres> for Vec<u8> {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
<&[u8] as Encode<Postgres>>::encode(self, buf)
@@ -74,6 +86,15 @@ fn text_hex_decode_input(value: PgValueRef<'_>) -> Result<&[u8], BoxDynError> {
.map_err(Into::into)
}
impl Decode<'_, Postgres> for Box<[u8]> {
fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
Ok(match value.format() {
PgValueFormat::Binary => Box::from(value.as_bytes()?),
PgValueFormat::Text => Box::from(hex::decode(text_hex_decode_input(value)?)?),
})
}
}
impl Decode<'_, Postgres> for Vec<u8> {
fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
Ok(match value.format() {

View File

@@ -33,6 +33,16 @@ impl Type<Postgres> for Cow<'_, str> {
}
}
impl Type<Postgres> for Box<str> {
fn type_info() -> PgTypeInfo {
<&str as Type<Postgres>>::type_info()
}
fn compatible(ty: &PgTypeInfo) -> bool {
<&str as Type<Postgres>>::compatible(ty)
}
}
impl Type<Postgres> for String {
fn type_info() -> PgTypeInfo {
<&str as Type<Postgres>>::type_info()
@@ -63,6 +73,16 @@ impl PgHasArrayType for Cow<'_, str> {
}
}
impl PgHasArrayType for Box<str> {
fn array_type_info() -> PgTypeInfo {
<&str as PgHasArrayType>::array_type_info()
}
fn array_compatible(ty: &PgTypeInfo) -> bool {
<&str as PgHasArrayType>::array_compatible(ty)
}
}
impl PgHasArrayType for String {
fn array_type_info() -> PgTypeInfo {
<&str as PgHasArrayType>::array_type_info()
@@ -90,6 +110,12 @@ impl Encode<'_, Postgres> for Cow<'_, str> {
}
}
impl Encode<'_, Postgres> for Box<str> {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
<&str as Encode<Postgres>>::encode(&**self, buf)
}
}
impl Encode<'_, Postgres> for String {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
<&str as Encode<Postgres>>::encode(&**self, buf)
@@ -108,6 +134,12 @@ impl<'r> Decode<'r, Postgres> for Cow<'r, str> {
}
}
impl<'r> Decode<'r, Postgres> for Box<str> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
Ok(Box::from(value.as_str()?))
}
}
impl Decode<'_, Postgres> for String {
fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
Ok(value.as_str()?.to_owned())