From 39153ad594cf572af710adfdd7b268db6e279fd4 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 15 Jun 2021 15:04:54 +0200 Subject: [PATCH] Implement Encode for unsized types as well Allows implementations of `Encode` on pointers to extern types (RFC-1861) and other unsized types, should it be desired. --- src/encode.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/encode.rs b/src/encode.rs index cd592103f..b817a7c00 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -79,25 +79,29 @@ slice_encode_impl!( 27, 28, 29, 30, 31, 32 ); -/* -External crates cannot implement Encode for pointers or Optionals, but they -*can* implement it for references. rust-lang/rust#25126 - -As a workaround, we provide implementations for these types that return the -same encoding as references. -*/ -unsafe impl Encode for *const T where for<'b> &'b T: Encode { + +// External crates cannot implement Encode for pointers or [`Option`], but +// they *can* implement it for references. See +// [rust-lang/rust#25126](https://github.com/rust-lang/rust/issues/25126) +// +// So, as a workaround, we provide implementations for these types that return +// the same encoding as references. +// +// Using `?Sized` is safe here because we delegate to other implementations +// (which will verify that the implementation is safe for the unsized type). + +unsafe impl Encode for *const T where for<'b> &'b T: Encode { const ENCODING: Encoding<'static> = <&T>::ENCODING; } -unsafe impl Encode for *mut T where for<'b> &'b mut T: Encode { +unsafe impl Encode for *mut T where for<'b> &'b mut T: Encode { const ENCODING: Encoding<'static> = <&mut T>::ENCODING; } -unsafe impl<'a, T> Encode for Option<&'a T> where for<'b> &'b T: Encode { +unsafe impl<'a, T: ?Sized> Encode for Option<&'a T> where for<'b> &'b T: Encode { const ENCODING: Encoding<'static> = <&T>::ENCODING; } -unsafe impl<'a, T> Encode for Option<&'a mut T> where for<'b> &'b mut T: Encode { +unsafe impl<'a, T: ?Sized> Encode for Option<&'a mut T> where for<'b> &'b mut T: Encode { const ENCODING: Encoding<'static> = <&mut T>::ENCODING; }