Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Encode for unsized types as well #9

Merged
merged 1 commit into from
Aug 31, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> 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<T: ?Sized> Encode for *const T where for<'b> &'b T: Encode {
const ENCODING: Encoding<'static> = <&T>::ENCODING;
}

unsafe impl<T> Encode for *mut T where for<'b> &'b mut T: Encode {
unsafe impl<T: ?Sized> 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;
}