@@ -327,14 +327,35 @@ impl<'a> serialize::Decoder for Decoder<'a> {
327
327
}
328
328
}
329
329
330
- // Specialize encoding byte slices. The default implementation for slices encodes and emits each
331
- // element individually. This isn't necessary for `u8` slices encoded with an `opaque::Encoder`,
332
- // because each `u8` is emitted as-is. Therefore, we can use a more efficient implementation. This
333
- // specialization applies to encoding `Vec<u8>`s, etc., since they call `encode` on their slices.
330
+ // Specializations for contiguous byte sequences follow. The default implementations for slices
331
+ // encode and decode each element individually. This isn't necessary for `u8` slices when using
332
+ // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding.
333
+ // Therefore, we can use more efficient implementations that process the entire sequence at once.
334
+
335
+ // Specialize encoding byte slices. This specialization also applies to encoding `Vec<u8>`s, etc.,
336
+ // since the default implementations call `encode` on their slices internally.
334
337
impl serialize:: Encodable < Encoder > for [ u8 ] {
335
338
fn encode ( & self , e : & mut Encoder ) -> EncodeResult {
336
339
serialize:: Encoder :: emit_usize ( e, self . len ( ) ) ?;
337
340
e. emit_raw_bytes ( self ) ;
338
341
Ok ( ( ) )
339
342
}
340
343
}
344
+
345
+ // Specialize decoding `Vec<u8>`. This specialization also applies to decoding `Box<[u8]>`s, etc.,
346
+ // since the default implementations call `decode` to produce a `Vec<u8>` internally.
347
+ impl < ' a > serialize:: Decodable < Decoder < ' a > > for Vec < u8 > {
348
+ fn decode ( d : & mut Decoder < ' a > ) -> Result < Self , String > {
349
+ let len = serialize:: Decoder :: read_usize ( d) ?;
350
+
351
+ let mut v = Vec :: with_capacity ( len) ;
352
+ let buf = & mut v. spare_capacity_mut ( ) [ ..len] ;
353
+ d. read_raw_bytes ( buf) ?;
354
+
355
+ unsafe {
356
+ v. set_len ( len) ;
357
+ }
358
+
359
+ Ok ( v)
360
+ }
361
+ }
0 commit comments