Auto merge of #77261 - oli-obk:const_generic_array_serializer, r=matthewjasper

Deduplicate and generalize some (de/)serializer impls

I noticed this while implementing #77227 and getting a "not implemented for [T; 16]" error. There's likely more things we can deduplicate in this file, but I didn't need any additional changes.
This commit is contained in:
bors 2020-09-28 08:33:00 +00:00
commit 96555ba608
2 changed files with 12 additions and 23 deletions

View File

@ -13,6 +13,7 @@
#![feature(never_type)]
#![feature(nll)]
#![feature(associated_type_bounds)]
#![feature(min_const_generics)]
#![cfg_attr(test, feature(test))]
#![allow(rustc::internal)]

View File

@ -539,12 +539,8 @@ fn encode(&self, s: &mut S) -> Result<(), S::Error> {
impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))?
}
Ok(())
})
let slice: &[T] = self;
slice.encode(s)
}
}
@ -560,22 +556,18 @@ fn decode(d: &mut D) -> Result<Vec<T>, D::Error> {
}
}
impl<S: Encoder> Encodable<S> for [u8; 20] {
impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))?
}
Ok(())
})
let slice: &[T] = self;
slice.encode(s)
}
}
impl<D: Decoder> Decodable<D> for [u8; 20] {
fn decode(d: &mut D) -> Result<[u8; 20], D::Error> {
impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
fn decode(d: &mut D) -> Result<[u8; N], D::Error> {
d.read_seq(|d, len| {
assert!(len == 20);
let mut v = [0u8; 20];
assert!(len == N);
let mut v = [0u8; N];
for i in 0..len {
v[i] = d.read_seq_elt(i, |d| Decodable::decode(d))?;
}
@ -589,12 +581,8 @@ impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
[T]: ToOwned<Owned = Vec<T>>,
{
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_seq(self.len(), |s| {
for (i, e) in self.iter().enumerate() {
s.emit_seq_elt(i, |s| e.encode(s))?
}
Ok(())
})
let slice: &[T] = self;
slice.encode(s)
}
}