1 //! Support code for encoding and decoding types.
4 Core encoding and decoding interfaces.
8 use std
::cell
::{Cell, RefCell}
;
9 use std
::marker
::PhantomData
;
18 fn emit_unit(&mut self) -> Result
<(), Self::Error
>;
19 fn emit_usize(&mut self, v
: usize) -> Result
<(), Self::Error
>;
20 fn emit_u128(&mut self, v
: u128
) -> Result
<(), Self::Error
>;
21 fn emit_u64(&mut self, v
: u64) -> Result
<(), Self::Error
>;
22 fn emit_u32(&mut self, v
: u32) -> Result
<(), Self::Error
>;
23 fn emit_u16(&mut self, v
: u16) -> Result
<(), Self::Error
>;
24 fn emit_u8(&mut self, v
: u8) -> Result
<(), Self::Error
>;
25 fn emit_isize(&mut self, v
: isize) -> Result
<(), Self::Error
>;
26 fn emit_i128(&mut self, v
: i128
) -> Result
<(), Self::Error
>;
27 fn emit_i64(&mut self, v
: i64) -> Result
<(), Self::Error
>;
28 fn emit_i32(&mut self, v
: i32) -> Result
<(), Self::Error
>;
29 fn emit_i16(&mut self, v
: i16) -> Result
<(), Self::Error
>;
30 fn emit_i8(&mut self, v
: i8) -> Result
<(), Self::Error
>;
31 fn emit_bool(&mut self, v
: bool
) -> Result
<(), Self::Error
>;
32 fn emit_f64(&mut self, v
: f64) -> Result
<(), Self::Error
>;
33 fn emit_f32(&mut self, v
: f32) -> Result
<(), Self::Error
>;
34 fn emit_char(&mut self, v
: char) -> Result
<(), Self::Error
>;
35 fn emit_str(&mut self, v
: &str) -> Result
<(), Self::Error
>;
36 fn emit_raw_bytes(&mut self, s
: &[u8]) -> Result
<(), Self::Error
>;
40 fn emit_enum
<F
>(&mut self, f
: F
) -> Result
<(), Self::Error
>
42 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
47 fn emit_enum_variant
<F
>(
53 ) -> Result
<(), Self::Error
>
55 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
57 self.emit_usize(v_id
)?
;
62 fn emit_enum_variant_arg
<F
>(&mut self, _first
: bool
, f
: F
) -> Result
<(), Self::Error
>
64 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
70 fn emit_struct
<F
>(&mut self, _no_fields
: bool
, f
: F
) -> Result
<(), Self::Error
>
72 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
78 fn emit_struct_field
<F
>(&mut self, _f_name
: &str, _first
: bool
, f
: F
) -> Result
<(), Self::Error
>
80 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
86 fn emit_tuple
<F
>(&mut self, _len
: usize, f
: F
) -> Result
<(), Self::Error
>
88 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
94 fn emit_tuple_arg
<F
>(&mut self, _idx
: usize, f
: F
) -> Result
<(), Self::Error
>
96 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
101 // Specialized types:
102 fn emit_option
<F
>(&mut self, f
: F
) -> Result
<(), Self::Error
>
104 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
110 fn emit_option_none(&mut self) -> Result
<(), Self::Error
> {
111 self.emit_enum_variant("None", 0, 0, |_
| Ok(()))
114 fn emit_option_some
<F
>(&mut self, f
: F
) -> Result
<(), Self::Error
>
116 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
118 self.emit_enum_variant("Some", 1, 1, f
)
121 fn emit_seq
<F
>(&mut self, len
: usize, f
: F
) -> Result
<(), Self::Error
>
123 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
125 self.emit_usize(len
)?
;
130 fn emit_seq_elt
<F
>(&mut self, _idx
: usize, f
: F
) -> Result
<(), Self::Error
>
132 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
137 fn emit_map
<F
>(&mut self, len
: usize, f
: F
) -> Result
<(), Self::Error
>
139 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
141 self.emit_usize(len
)?
;
146 fn emit_map_elt_key
<F
>(&mut self, _idx
: usize, f
: F
) -> Result
<(), Self::Error
>
148 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
154 fn emit_map_elt_val
<F
>(&mut self, f
: F
) -> Result
<(), Self::Error
>
156 F
: FnOnce(&mut Self) -> Result
<(), Self::Error
>,
166 fn read_nil(&mut self) -> Result
<(), Self::Error
>;
167 fn read_usize(&mut self) -> Result
<usize, Self::Error
>;
168 fn read_u128(&mut self) -> Result
<u128
, Self::Error
>;
169 fn read_u64(&mut self) -> Result
<u64, Self::Error
>;
170 fn read_u32(&mut self) -> Result
<u32, Self::Error
>;
171 fn read_u16(&mut self) -> Result
<u16, Self::Error
>;
172 fn read_u8(&mut self) -> Result
<u8, Self::Error
>;
173 fn read_isize(&mut self) -> Result
<isize, Self::Error
>;
174 fn read_i128(&mut self) -> Result
<i128
, Self::Error
>;
175 fn read_i64(&mut self) -> Result
<i64, Self::Error
>;
176 fn read_i32(&mut self) -> Result
<i32, Self::Error
>;
177 fn read_i16(&mut self) -> Result
<i16, Self::Error
>;
178 fn read_i8(&mut self) -> Result
<i8, Self::Error
>;
179 fn read_bool(&mut self) -> Result
<bool
, Self::Error
>;
180 fn read_f64(&mut self) -> Result
<f64, Self::Error
>;
181 fn read_f32(&mut self) -> Result
<f32, Self::Error
>;
182 fn read_char(&mut self) -> Result
<char, Self::Error
>;
183 fn read_str(&mut self) -> Result
<Cow
<'_
, str>, Self::Error
>;
184 fn read_raw_bytes_into(&mut self, s
: &mut [u8]) -> Result
<(), Self::Error
>;
188 fn read_enum
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
190 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
196 fn read_enum_variant
<T
, F
>(&mut self, _names
: &[&str], mut f
: F
) -> Result
<T
, Self::Error
>
198 F
: FnMut(&mut Self, usize) -> Result
<T
, Self::Error
>,
200 let disr
= self.read_usize()?
;
205 fn read_enum_variant_arg
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
207 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
213 fn read_struct
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
215 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
221 fn read_struct_field
<T
, F
>(&mut self, _f_name
: &str, f
: F
) -> Result
<T
, Self::Error
>
223 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
229 fn read_tuple
<T
, F
>(&mut self, _len
: usize, f
: F
) -> Result
<T
, Self::Error
>
231 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
237 fn read_tuple_arg
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
239 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
244 // Specialized types:
245 fn read_option
<T
, F
>(&mut self, mut f
: F
) -> Result
<T
, Self::Error
>
247 F
: FnMut(&mut Self, bool
) -> Result
<T
, Self::Error
>,
249 self.read_enum(move |this
| {
250 this
.read_enum_variant(&["None", "Some"], move |this
, idx
| match idx
{
253 _
=> Err(this
.error("read_option: expected 0 for None or 1 for Some")),
258 fn read_seq
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
260 F
: FnOnce(&mut Self, usize) -> Result
<T
, Self::Error
>,
262 let len
= self.read_usize()?
;
267 fn read_seq_elt
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
269 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
274 fn read_map
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
276 F
: FnOnce(&mut Self, usize) -> Result
<T
, Self::Error
>,
278 let len
= self.read_usize()?
;
283 fn read_map_elt_key
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
285 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
291 fn read_map_elt_val
<T
, F
>(&mut self, f
: F
) -> Result
<T
, Self::Error
>
293 F
: FnOnce(&mut Self) -> Result
<T
, Self::Error
>,
299 fn error(&mut self, err
: &str) -> Self::Error
;
302 /// Trait for types that can be serialized
304 /// This can be implemented using the `Encodable`, `TyEncodable` and
305 /// `MetadataEncodable` macros.
307 /// * `Encodable` should be used in crates that don't depend on
309 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
310 /// `rustc_metadata::rmeta::Lazy`.
311 /// * `TyEncodable` should be used for types that are only serialized in crate
312 /// metadata or the incremental cache. This is most types in `rustc_middle`.
313 pub trait Encodable
<S
: Encoder
> {
314 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
>;
317 /// Trait for types that can be deserialized
319 /// This can be implemented using the `Decodable`, `TyDecodable` and
320 /// `MetadataDecodable` macros.
322 /// * `Decodable` should be used in crates that don't depend on
324 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
325 /// `rustc_metadata::rmeta::Lazy`.
326 /// * `TyDecodable` should be used for types that are only serialized in crate
327 /// metadata or the incremental cache. This is most types in `rustc_middle`.
328 pub trait Decodable
<D
: Decoder
>: Sized
{
329 fn decode(d
: &mut D
) -> Result
<Self, D
::Error
>;
332 macro_rules
! direct_serialize_impls
{
333 ($
($ty
:ident $emit_method
:ident $read_method
:ident
),*) => {
335 impl<S
: Encoder
> Encodable
<S
> for $ty
{
336 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
337 s
.$
emit_method(*self)
341 impl<D
: Decoder
> Decodable
<D
> for $ty
{
342 fn decode(d
: &mut D
) -> Result
<$ty
, D
::Error
> {
350 direct_serialize_impls
! {
351 usize emit_usize read_usize
,
353 u16 emit_u16 read_u16
,
354 u32 emit_u32 read_u32
,
355 u64 emit_u64 read_u64
,
356 u128 emit_u128 read_u128
,
357 isize emit_isize read_isize
,
359 i16 emit_i16 read_i16
,
360 i32 emit_i32 read_i32
,
361 i64 emit_i64 read_i64
,
362 i128 emit_i128 read_i128
,
363 f32 emit_f32 read_f32
,
364 f64 emit_f64 read_f64
,
365 bool emit_bool read_bool
,
366 char emit_char read_char
369 impl<S
: Encoder
> Encodable
<S
> for ::std
::num
::NonZeroU32
{
370 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
371 s
.emit_u32(self.get())
375 impl<D
: Decoder
> Decodable
<D
> for ::std
::num
::NonZeroU32
{
376 fn decode(d
: &mut D
) -> Result
<Self, D
::Error
> {
377 d
.read_u32().map(|d
| ::std
::num
::NonZeroU32
::new(d
).unwrap())
381 impl<S
: Encoder
> Encodable
<S
> for str {
382 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
387 impl<S
: Encoder
> Encodable
<S
> for &str {
388 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
393 impl<S
: Encoder
> Encodable
<S
> for String
{
394 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
395 s
.emit_str(&self[..])
399 impl<D
: Decoder
> Decodable
<D
> for String
{
400 fn decode(d
: &mut D
) -> Result
<String
, D
::Error
> {
401 Ok(d
.read_str()?
.into_owned())
405 impl<S
: Encoder
> Encodable
<S
> for () {
406 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
411 impl<D
: Decoder
> Decodable
<D
> for () {
412 fn decode(d
: &mut D
) -> Result
<(), D
::Error
> {
417 impl<S
: Encoder
, T
> Encodable
<S
> for PhantomData
<T
> {
418 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
423 impl<D
: Decoder
, T
> Decodable
<D
> for PhantomData
<T
> {
424 fn decode(d
: &mut D
) -> Result
<PhantomData
<T
>, D
::Error
> {
430 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for Box
<[T
]> {
431 fn decode(d
: &mut D
) -> Result
<Box
<[T
]>, D
::Error
> {
432 let v
: Vec
<T
> = Decodable
::decode(d
)?
;
433 Ok(v
.into_boxed_slice())
437 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Rc
<T
> {
438 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
443 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for Rc
<T
> {
444 fn decode(d
: &mut D
) -> Result
<Rc
<T
>, D
::Error
> {
445 Ok(Rc
::new(Decodable
::decode(d
)?
))
449 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for [T
] {
450 default fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
451 s
.emit_seq(self.len(), |s
| {
452 for (i
, e
) in self.iter().enumerate() {
453 s
.emit_seq_elt(i
, |s
| e
.encode(s
))?
460 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Vec
<T
> {
461 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
462 let slice
: &[T
] = self;
467 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for Vec
<T
> {
468 default fn decode(d
: &mut D
) -> Result
<Vec
<T
>, D
::Error
> {
469 d
.read_seq(|d
, len
| {
470 let mut v
= Vec
::with_capacity(len
);
472 v
.push(d
.read_seq_elt(|d
| Decodable
::decode(d
))?
);
479 impl<S
: Encoder
, T
: Encodable
<S
>, const N
: usize> Encodable
<S
> for [T
; N
] {
480 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
481 let slice
: &[T
] = self;
486 impl<D
: Decoder
, const N
: usize> Decodable
<D
> for [u8; N
] {
487 fn decode(d
: &mut D
) -> Result
<[u8; N
], D
::Error
> {
488 d
.read_seq(|d
, len
| {
490 let mut v
= [0u8; N
];
492 v
[i
] = d
.read_seq_elt(|d
| Decodable
::decode(d
))?
;
499 impl<'a
, S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Cow
<'a
, [T
]>
501 [T
]: ToOwned
<Owned
= Vec
<T
>>,
503 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
504 let slice
: &[T
] = self;
509 impl<D
: Decoder
, T
: Decodable
<D
> + ToOwned
> Decodable
<D
> for Cow
<'
static, [T
]>
511 [T
]: ToOwned
<Owned
= Vec
<T
>>,
513 fn decode(d
: &mut D
) -> Result
<Cow
<'
static, [T
]>, D
::Error
> {
514 let v
: Vec
<T
> = Decodable
::decode(d
)?
;
519 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Option
<T
> {
520 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
521 s
.emit_option(|s
| match *self {
522 None
=> s
.emit_option_none(),
523 Some(ref v
) => s
.emit_option_some(|s
| v
.encode(s
)),
528 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for Option
<T
> {
529 fn decode(d
: &mut D
) -> Result
<Option
<T
>, D
::Error
> {
530 d
.read_option(|d
, b
| if b { Ok(Some(Decodable::decode(d)?)) }
else { Ok(None) }
)
534 impl<S
: Encoder
, T1
: Encodable
<S
>, T2
: Encodable
<S
>> Encodable
<S
> for Result
<T1
, T2
> {
535 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
536 s
.emit_enum(|s
| match *self {
538 s
.emit_enum_variant("Ok", 0, 1, |s
| s
.emit_enum_variant_arg(true, |s
| v
.encode(s
)))
541 s
.emit_enum_variant("Err", 1, 1, |s
| s
.emit_enum_variant_arg(true, |s
| v
.encode(s
)))
547 impl<D
: Decoder
, T1
: Decodable
<D
>, T2
: Decodable
<D
>> Decodable
<D
> for Result
<T1
, T2
> {
548 fn decode(d
: &mut D
) -> Result
<Result
<T1
, T2
>, D
::Error
> {
550 d
.read_enum_variant(&["Ok", "Err"], |d
, disr
| match disr
{
551 0 => Ok(Ok(d
.read_enum_variant_arg(|d
| T1
::decode(d
))?
)),
552 1 => Ok(Err(d
.read_enum_variant_arg(|d
| T2
::decode(d
))?
)),
555 "Encountered invalid discriminant while \
565 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
568 /// Evaluates to the number of tokens passed to it.
570 /// Logarithmic counting: every one or two recursive expansions, the number of
571 /// tokens to count is divided by two, instead of being reduced by one.
572 /// Therefore, the recursion depth is the binary logarithm of the number of
573 /// tokens to count, and the expanded tree is likewise very small.
576 ($one
:tt
) => (1usize
);
577 ($
($pairs
:tt $_p
:tt
)*) => (count
!($
($pairs
)*) << 1usize
);
578 ($odd
:tt $
($rest
:tt
)*) => (count
!($
($rest
)*) | 1usize
);
583 ( $
($name
:ident
,)+ ) => (
584 impl<D
: Decoder
, $
($name
: Decodable
<D
>),+> Decodable
<D
> for ($
($name
,)+) {
585 #[allow(non_snake_case)]
586 fn decode(d
: &mut D
) -> Result
<($
($name
,)+), D
::Error
> {
587 let len
: usize = count
!($
($name
)+);
588 d
.read_tuple(len
, |d
| {
589 let ret
= ($
(d
.read_tuple_arg(|d
| -> Result
<$name
, D
::Error
> {
596 impl<S
: Encoder
, $
($name
: Encodable
<S
>),+> Encodable
<S
> for ($
($name
,)+) {
597 #[allow(non_snake_case)]
598 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
599 let ($
(ref $name
,)+) = *self;
601 $
(let $name
= $name
; n
+= 1;)+
602 s
.emit_tuple(n
, |s
| {
604 $
(s
.emit_tuple_arg({ i+=1; i-1 }
, |s
| $name
.encode(s
))?
;)+
613 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
615 impl<S
: Encoder
> Encodable
<S
> for path
::Path
{
616 fn encode(&self, e
: &mut S
) -> Result
<(), S
::Error
> {
617 self.to_str().unwrap().encode(e
)
621 impl<S
: Encoder
> Encodable
<S
> for path
::PathBuf
{
622 fn encode(&self, e
: &mut S
) -> Result
<(), S
::Error
> {
623 path
::Path
::encode(self, e
)
627 impl<D
: Decoder
> Decodable
<D
> for path
::PathBuf
{
628 fn decode(d
: &mut D
) -> Result
<path
::PathBuf
, D
::Error
> {
629 let bytes
: String
= Decodable
::decode(d
)?
;
630 Ok(path
::PathBuf
::from(bytes
))
634 impl<S
: Encoder
, T
: Encodable
<S
> + Copy
> Encodable
<S
> for Cell
<T
> {
635 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
640 impl<D
: Decoder
, T
: Decodable
<D
> + Copy
> Decodable
<D
> for Cell
<T
> {
641 fn decode(d
: &mut D
) -> Result
<Cell
<T
>, D
::Error
> {
642 Ok(Cell
::new(Decodable
::decode(d
)?
))
647 // Should use `try_borrow`, returning an
648 // `encoder.error("attempting to Encode borrowed RefCell")`
649 // from `encode` when `try_borrow` returns `None`.
651 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for RefCell
<T
> {
652 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
653 self.borrow().encode(s
)
657 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for RefCell
<T
> {
658 fn decode(d
: &mut D
) -> Result
<RefCell
<T
>, D
::Error
> {
659 Ok(RefCell
::new(Decodable
::decode(d
)?
))
663 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Arc
<T
> {
664 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
669 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for Arc
<T
> {
670 fn decode(d
: &mut D
) -> Result
<Arc
<T
>, D
::Error
> {
671 Ok(Arc
::new(Decodable
::decode(d
)?
))
675 impl<S
: Encoder
, T
: ?Sized
+ Encodable
<S
>> Encodable
<S
> for Box
<T
> {
676 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
680 impl<D
: Decoder
, T
: Decodable
<D
>> Decodable
<D
> for Box
<T
> {
681 fn decode(d
: &mut D
) -> Result
<Box
<T
>, D
::Error
> {
682 Ok(Box
::new(Decodable
::decode(d
)?
))