Skip to content

Commit

Permalink
Encode/Decode impl for Cow<'_, str>
Browse files Browse the repository at this point in the history
  • Loading branch information
Drevoed committed Jul 24, 2021
1 parent f0d0dce commit 10fe6de
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions sqlx-core/src/postgres/types/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use crate::error::BoxDynError;
use crate::postgres::types::array_compatible;
use crate::postgres::{PgArgumentBuffer, PgTypeInfo, PgValueRef, Postgres};
use crate::types::Type;
use std::borrow::Cow;
use crate::database::{HasArguments, HasValueRef};

impl Type<Postgres> for str {
fn type_info() -> PgTypeInfo {
Expand All @@ -22,6 +24,16 @@ impl Type<Postgres> for str {
}
}

impl Type<Postgres> for Cow<'_, 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 [&'_ str] {
fn type_info() -> PgTypeInfo {
PgTypeInfo::TEXT_ARRAY
Expand Down Expand Up @@ -50,6 +62,15 @@ impl Encode<'_, Postgres> for &'_ str {
}
}

impl Encode<'_, Postgres> for Cow<'_, str> {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
match self {
Cow::Borrowed(str) => str.encode(buf),
Cow::Owned(str) => <&str as Encode<Postgres>>::encode(&**str, buf)
}
}
}

impl Encode<'_, Postgres> for String {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
<&str as Encode<Postgres>>::encode(&**self, buf)
Expand All @@ -62,6 +83,12 @@ impl<'r> Decode<'r, Postgres> for &'r str {
}
}

impl<'r> Decode<'r, Postgres> for Cow<'r, str> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
Ok(Cow::Borrowed(value.as_str()?))
}
}

impl Type<Postgres> for String {
fn type_info() -> PgTypeInfo {
<&str as Type<Postgres>>::type_info()
Expand Down

0 comments on commit 10fe6de

Please sign in to comment.