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 ! {
370 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
375 impl<D: Decoder> Decodable<D> for ! {
376 fn decode(_d: &mut D) -> Result<!, D::Error> {
381 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
382 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
383 s.emit_u32(self.get())
387 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
388 fn decode(d: &mut D) -> Result<Self, D::Error> {
389 d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
393 impl<S: Encoder> Encodable<S> for str {
394 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
399 impl<S: Encoder> Encodable<S> for &str {
400 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
405 impl<S: Encoder> Encodable<S> for String {
406 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
407 s.emit_str(&self[..])
411 impl<D: Decoder> Decodable<D> for String {
412 fn decode(d: &mut D) -> Result<String, D::Error> {
413 Ok(d.read_str()?.into_owned())
417 impl<S: Encoder> Encodable<S> for () {
418 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
423 impl<D: Decoder> Decodable<D> for () {
424 fn decode(d: &mut D) -> Result<(), D::Error> {
429 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
430 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
435 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
436 fn decode(d: &mut D) -> Result<PhantomData<T>, D::Error> {
442 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<[T]> {
443 fn decode(d: &mut D) -> Result<Box<[T]>, D::Error> {
444 let v: Vec<T> = Decodable::decode(d)?;
445 Ok(v.into_boxed_slice())
449 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
450 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
455 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
456 fn decode(d: &mut D) -> Result<Rc<T>, D::Error> {
457 Ok(Rc::new(Decodable::decode(d)?))
461 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
462 default fn encode(&self, s: &mut S) -> Result<(), S::Error> {
463 s.emit_seq(self.len(), |s| {
464 for (i, e) in self.iter().enumerate() {
465 s.emit_seq_elt(i, |s| e.encode(s))?
472 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
473 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
474 let slice: &[T] = self;
479 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Vec<T> {
480 default fn decode(d: &mut D) -> Result<Vec<T>, D::Error> {
481 d.read_seq(|d, len| {
482 let mut v = Vec::with_capacity(len);
484 v.push(d.read_seq_elt(|d| Decodable::decode(d))?);
491 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
492 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
493 let slice: &[T] = self;
498 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
499 fn decode(d: &mut D) -> Result<[u8; N], D::Error> {
500 d.read_seq(|d, len| {
502 let mut v = [0u8; N];
504 v[i] = d.read_seq_elt(|d| Decodable::decode(d))?;
511 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
513 [T]: ToOwned<Owned = Vec<T>>,
515 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
516 let slice: &[T] = self;
521 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
523 [T]: ToOwned<Owned = Vec<T>>,
525 fn decode(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
526 let v: Vec<T> = Decodable::decode(d)?;
531 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
532 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
533 s.emit_option(|s| match *self {
534 None => s.emit_option_none(),
535 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
540 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
541 fn decode(d: &mut D) -> Result<Option<T>, D::Error> {
542 d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
546 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
547 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
548 s.emit_enum(|s| match *self {
550 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
553 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
559 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
560 fn decode(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
562 d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
563 0 => Ok(Ok(d.read_enum_variant_arg(|d| T1::decode(d))?)),
564 1 => Ok(Err(d.read_enum_variant_arg(|d| T2::decode(d))?)),
567 "Encountered invalid discriminant while \
577 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
580 /// Evaluates to the number of tokens passed to it.
582 /// Logarithmic counting: every one or two recursive expansions, the number of
583 /// tokens to count is divided by two, instead of being reduced by one.
584 /// Therefore, the recursion depth is the binary logarithm of the number of
585 /// tokens to count, and the expanded tree is likewise very small.
588 ($one:tt) => (1usize);
589 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
590 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
595 ( $($name:ident,)+ ) => (
596 impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
597 #[allow(non_snake_case)]
598 fn decode(d: &mut D) -> Result<($($name,)+), D::Error> {
599 let len: usize = count!($($name)+);
600 d.read_tuple(len, |d| {
601 let ret = ($(d.read_tuple_arg(|d| -> Result<$name, D::Error> {
608 impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
609 #[allow(non_snake_case)]
610 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
611 let ($(ref $name,)+) = *self;
613 $(let $name = $name; n += 1;)+
614 s.emit_tuple(n, |s| {
616 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
625 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
627 impl<S: Encoder> Encodable<S> for path::Path {
628 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
629 self.to_str().unwrap().encode(e)
633 impl<S: Encoder> Encodable<S> for path::PathBuf {
634 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
635 path::Path::encode(self, e)
639 impl<D: Decoder> Decodable<D> for path::PathBuf {
640 fn decode(d: &mut D) -> Result<path::PathBuf, D::Error> {
641 let bytes: String = Decodable::decode(d)?;
642 Ok(path::PathBuf::from(bytes))
646 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
647 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
652 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
653 fn decode(d: &mut D) -> Result<Cell<T>, D::Error> {
654 Ok(Cell::new(Decodable::decode(d)?))
659 // Should use `try_borrow`, returning an
660 // `encoder.error("attempting to Encode borrowed RefCell")`
661 // from `encode` when `try_borrow` returns `None`.
663 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
664 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
665 self.borrow().encode(s)
669 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
670 fn decode(d: &mut D) -> Result<RefCell<T>, D::Error> {
671 Ok(RefCell::new(Decodable::decode(d)?))
675 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
676 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
681 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
682 fn decode(d: &mut D) -> Result<Arc<T>, D::Error> {
683 Ok(Arc::new(Decodable::decode(d)?))
687 impl<S: Encoder, T: ?Sized + Encodable<S>> Encodable<S> for Box<T> {
688 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
692 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<T> {
693 fn decode(d: &mut D) -> Result<Box<T>, D::Error> {
694 Ok(Box::new(Decodable::decode(d)?))