From 1bd0d9271ebaee06ec252197fa1c58feeba2229f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Obr=C3=A9jan?= Date: Thu, 23 Jun 2022 15:38:59 +0200 Subject: [PATCH] Implement `ToSql` & `FromSql` for `Box<[T]>` --- postgres-types/src/lib.rs | 41 +++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/postgres-types/src/lib.rs b/postgres-types/src/lib.rs index f9c1c5ce..6f72a733 100644 --- a/postgres-types/src/lib.rs +++ b/postgres-types/src/lib.rs @@ -452,10 +452,11 @@ impl WrongType { /// /// # Arrays /// -/// `FromSql` is implemented for `Vec` and `[T; N]` where `T` implements -/// `FromSql`, and corresponds to one-dimensional Postgres arrays. **Note:** -/// the impl for arrays only exist when the Cargo feature `array-impls` is -/// enabled. +/// `FromSql` is implemented for `Vec`, `Box<[T]>` and `[T; N]` where `T` +/// implements `FromSql`, and corresponds to one-dimensional Postgres arrays. +/// +/// **Note:** the impl for arrays only exist when the Cargo feature `array-impls` +/// is enabled. pub trait FromSql<'a>: Sized { /// Creates a new value of this type from a buffer of data of the specified /// Postgres `Type` in its binary format. @@ -580,6 +581,16 @@ impl<'a, T: FromSql<'a>, const N: usize> FromSql<'a> for [T; N] { } } +impl<'a, T: FromSql<'a>> FromSql<'a> for Box<[T]> { + fn from_sql(ty: &Type, raw: &'a [u8]) -> Result> { + Vec::::from_sql(ty, raw).map(Vec::into_boxed_slice) + } + + fn accepts(ty: &Type) -> bool { + Vec::::accepts(ty) + } +} + impl<'a> FromSql<'a> for Vec { fn from_sql(_: &Type, raw: &'a [u8]) -> Result, Box> { Ok(types::bytea_from_sql(raw).to_owned()) @@ -783,10 +794,12 @@ pub enum IsNull { /// /// # Arrays /// -/// `ToSql` is implemented for `Vec`, `&[T]` and `[T; N]` where `T` -/// implements `ToSql`, and corresponds to one-dimensional Postgres arrays with -/// an index offset of 1. **Note:** the impl for arrays only exist when the -/// Cargo feature `array-impls` is enabled. +/// `ToSql` is implemented for `Vec`, `&[T]`, `Box<[T]>` and `[T; N]` where +/// `T` implements `ToSql`, and corresponds to one-dimensional Postgres arrays +/// with an index offset of 1. +/// +/// **Note:** the impl for arrays only exist when the Cargo feature `array-impls` +/// is enabled. pub trait ToSql: fmt::Debug { /// Converts the value of `self` into the binary format of the specified /// Postgres `Type`, appending it to `out`. @@ -927,6 +940,18 @@ impl ToSql for Vec { to_sql_checked!(); } +impl ToSql for Box<[T]> { + fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { + <&[T] as ToSql>::to_sql(&&**self, ty, w) + } + + fn accepts(ty: &Type) -> bool { + <&[T] as ToSql>::accepts(ty) + } + + to_sql_checked!(); +} + impl ToSql for Vec { fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result> { <&[u8] as ToSql>::to_sql(&&**self, ty, w)