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)?;
61 // We put the field index in a const generic to allow the emit_usize to be
62 // compiled into a more efficient form. In practice, the variant index is
63 // known at compile-time, and that knowledge allows much more efficient
64 // codegen than we'd otherwise get. LLVM isn't always able to make the
65 // optimization that would otherwise be necessary here, likely due to the
66 // multiple levels of inlining and const-prop that are needed.
68 fn emit_fieldless_enum_variant<const ID: usize>(
71 ) -> Result<(), Self::Error> {
76 fn emit_enum_variant_arg<F>(&mut self, _first: bool, f: F) -> Result<(), Self::Error>
78 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
84 fn emit_struct<F>(&mut self, _no_fields: bool, f: F) -> Result<(), Self::Error>
86 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
92 fn emit_struct_field<F>(&mut self, _f_name: &str, _first: bool, f: F) -> Result<(), Self::Error>
94 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
100 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
102 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
108 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
110 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
115 // Specialized types:
116 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
118 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
124 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
125 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
128 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
130 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
132 self.emit_enum_variant("Some", 1, 1, f)
135 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
137 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
139 self.emit_usize(len)?;
144 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
146 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
151 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
153 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
155 self.emit_usize(len)?;
160 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
162 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
168 fn emit_map_elt_val<F>(&mut self, f: F) -> Result<(), Self::Error>
170 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
176 // Note: all the methods in this trait are infallible, which may be surprising.
177 // They used to be fallible (i.e. return a `Result`) but many of the impls just
178 // panicked when something went wrong, and for the cases that didn't the
179 // top-level invocation would also just panic on failure. Switching to
180 // infallibility made things faster and lots of code a little simpler and more
184 fn read_unit(&mut self) -> ();
185 fn read_usize(&mut self) -> usize;
186 fn read_u128(&mut self) -> u128;
187 fn read_u64(&mut self) -> u64;
188 fn read_u32(&mut self) -> u32;
189 fn read_u16(&mut self) -> u16;
190 fn read_u8(&mut self) -> u8;
191 fn read_isize(&mut self) -> isize;
192 fn read_i128(&mut self) -> i128;
193 fn read_i64(&mut self) -> i64;
194 fn read_i32(&mut self) -> i32;
195 fn read_i16(&mut self) -> i16;
196 fn read_i8(&mut self) -> i8;
197 fn read_bool(&mut self) -> bool;
198 fn read_f64(&mut self) -> f64;
199 fn read_f32(&mut self) -> f32;
200 fn read_char(&mut self) -> char;
201 fn read_str(&mut self) -> Cow<'_, str>;
202 fn read_raw_bytes_into(&mut self, s: &mut [u8]);
205 fn read_enum_variant<T, F>(&mut self, mut f: F) -> T
207 F: FnMut(&mut Self, usize) -> T,
209 let disr = self.read_usize();
214 fn read_tuple_arg<T, F>(&mut self, f: F) -> T
216 F: FnOnce(&mut Self) -> T,
221 // Specialized types:
222 fn read_option<T, F>(&mut self, mut f: F) -> T
224 F: FnMut(&mut Self, bool) -> T,
226 self.read_enum_variant(move |this, idx| match idx {
229 _ => panic!("read_option: expected 0 for None or 1 for Some"),
233 fn read_seq<T, F>(&mut self, f: F) -> T
235 F: FnOnce(&mut Self, usize) -> T,
237 let len = self.read_usize();
242 fn read_seq_elt<T, F>(&mut self, f: F) -> T
244 F: FnOnce(&mut Self) -> T,
249 fn read_map<T, F>(&mut self, f: F) -> T
251 F: FnOnce(&mut Self, usize) -> T,
253 let len = self.read_usize();
258 fn read_map_elt_key<T, F>(&mut self, f: F) -> T
260 F: FnOnce(&mut Self) -> T,
266 fn read_map_elt_val<T, F>(&mut self, f: F) -> T
268 F: FnOnce(&mut Self) -> T,
274 /// Trait for types that can be serialized
276 /// This can be implemented using the `Encodable`, `TyEncodable` and
277 /// `MetadataEncodable` macros.
279 /// * `Encodable` should be used in crates that don't depend on
281 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
282 /// `rustc_metadata::rmeta::Lazy`.
283 /// * `TyEncodable` should be used for types that are only serialized in crate
284 /// metadata or the incremental cache. This is most types in `rustc_middle`.
285 pub trait Encodable<S: Encoder> {
286 fn encode(&self, s: &mut S) -> Result<(), S::Error>;
289 /// Trait for types that can be deserialized
291 /// This can be implemented using the `Decodable`, `TyDecodable` and
292 /// `MetadataDecodable` macros.
294 /// * `Decodable` should be used in crates that don't depend on
296 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
297 /// `rustc_metadata::rmeta::Lazy`.
298 /// * `TyDecodable` should be used for types that are only serialized in crate
299 /// metadata or the incremental cache. This is most types in `rustc_middle`.
300 pub trait Decodable<D: Decoder>: Sized {
301 fn decode(d: &mut D) -> Self;
304 macro_rules! direct_serialize_impls {
305 ($($ty:ident $emit_method:ident $read_method:ident),*) => {
307 impl<S: Encoder> Encodable<S> for $ty {
308 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
309 s.$emit_method(*self)
313 impl<D: Decoder> Decodable<D> for $ty {
314 fn decode(d: &mut D) -> $ty {
322 direct_serialize_impls! {
323 usize emit_usize read_usize,
325 u16 emit_u16 read_u16,
326 u32 emit_u32 read_u32,
327 u64 emit_u64 read_u64,
328 u128 emit_u128 read_u128,
329 isize emit_isize read_isize,
331 i16 emit_i16 read_i16,
332 i32 emit_i32 read_i32,
333 i64 emit_i64 read_i64,
334 i128 emit_i128 read_i128,
335 f32 emit_f32 read_f32,
336 f64 emit_f64 read_f64,
337 bool emit_bool read_bool,
338 char emit_char read_char
341 impl<S: Encoder> Encodable<S> for ! {
342 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
347 impl<D: Decoder> Decodable<D> for ! {
348 fn decode(_d: &mut D) -> ! {
353 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
354 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
355 s.emit_u32(self.get())
359 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
360 fn decode(d: &mut D) -> Self {
361 ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
365 impl<S: Encoder> Encodable<S> for str {
366 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
371 impl<S: Encoder> Encodable<S> for &str {
372 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
377 impl<S: Encoder> Encodable<S> for String {
378 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
379 s.emit_str(&self[..])
383 impl<D: Decoder> Decodable<D> for String {
384 fn decode(d: &mut D) -> String {
385 d.read_str().into_owned()
389 impl<S: Encoder> Encodable<S> for () {
390 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
395 impl<D: Decoder> Decodable<D> for () {
396 fn decode(d: &mut D) -> () {
401 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
402 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
407 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
408 fn decode(d: &mut D) -> PhantomData<T> {
414 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<[T]> {
415 fn decode(d: &mut D) -> Box<[T]> {
416 let v: Vec<T> = Decodable::decode(d);
421 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
422 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
427 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
428 fn decode(d: &mut D) -> Rc<T> {
429 Rc::new(Decodable::decode(d))
433 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
434 default fn encode(&self, s: &mut S) -> Result<(), S::Error> {
435 s.emit_seq(self.len(), |s| {
436 for (i, e) in self.iter().enumerate() {
437 s.emit_seq_elt(i, |s| e.encode(s))?
444 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
445 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
446 let slice: &[T] = self;
451 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Vec<T> {
452 default fn decode(d: &mut D) -> Vec<T> {
453 d.read_seq(|d, len| {
454 // SAFETY: we set the capacity in advance, only write elements, and
455 // only set the length at the end once the writing has succeeded.
456 let mut vec = Vec::with_capacity(len);
458 let ptr: *mut T = vec.as_mut_ptr();
461 ptr.offset(i as isize),
462 d.read_seq_elt(|d| Decodable::decode(d)),
472 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
473 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
474 let slice: &[T] = self;
479 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
480 fn decode(d: &mut D) -> [u8; N] {
481 d.read_seq(|d, len| {
483 let mut v = [0u8; N];
485 v[i] = d.read_seq_elt(|d| Decodable::decode(d));
492 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
494 [T]: ToOwned<Owned = Vec<T>>,
496 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
497 let slice: &[T] = self;
502 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
504 [T]: ToOwned<Owned = Vec<T>>,
506 fn decode(d: &mut D) -> Cow<'static, [T]> {
507 let v: Vec<T> = Decodable::decode(d);
512 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
513 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
514 s.emit_option(|s| match *self {
515 None => s.emit_option_none(),
516 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
521 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
522 fn decode(d: &mut D) -> Option<T> {
523 d.read_option(|d, b| if b { Some(Decodable::decode(d)) } else { None })
527 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
528 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
529 s.emit_enum(|s| match *self {
531 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
534 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(true, |s| v.encode(s)))
540 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
541 fn decode(d: &mut D) -> Result<T1, T2> {
542 d.read_enum_variant(|d, disr| match disr {
543 0 => Ok(T1::decode(d)),
544 1 => Err(T2::decode(d)),
545 _ => panic!("Encountered invalid discriminant while decoding `Result`."),
551 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
554 /// Evaluates to the number of tokens passed to it.
556 /// Logarithmic counting: every one or two recursive expansions, the number of
557 /// tokens to count is divided by two, instead of being reduced by one.
558 /// Therefore, the recursion depth is the binary logarithm of the number of
559 /// tokens to count, and the expanded tree is likewise very small.
562 ($one:tt) => (1usize);
563 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
564 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
569 ( $($name:ident,)+ ) => (
570 impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
571 #[allow(non_snake_case)]
572 fn decode(d: &mut D) -> ($($name,)+) {
573 ($(d.read_tuple_arg(|d| -> $name {
578 impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
579 #[allow(non_snake_case)]
580 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
581 let ($(ref $name,)+) = *self;
582 let len: usize = count!($($name)+);
583 s.emit_tuple(len, |s| {
585 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
594 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
596 impl<S: Encoder> Encodable<S> for path::Path {
597 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
598 self.to_str().unwrap().encode(e)
602 impl<S: Encoder> Encodable<S> for path::PathBuf {
603 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
604 path::Path::encode(self, e)
608 impl<D: Decoder> Decodable<D> for path::PathBuf {
609 fn decode(d: &mut D) -> path::PathBuf {
610 let bytes: String = Decodable::decode(d);
611 path::PathBuf::from(bytes)
615 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
616 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
621 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
622 fn decode(d: &mut D) -> Cell<T> {
623 Cell::new(Decodable::decode(d))
628 // Should use `try_borrow`, returning an
629 // `encoder.error("attempting to Encode borrowed RefCell")`
630 // from `encode` when `try_borrow` returns `None`.
632 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
633 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
634 self.borrow().encode(s)
638 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
639 fn decode(d: &mut D) -> RefCell<T> {
640 RefCell::new(Decodable::decode(d))
644 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
645 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
650 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
651 fn decode(d: &mut D) -> Arc<T> {
652 Arc::new(Decodable::decode(d))
656 impl<S: Encoder, T: ?Sized + Encodable<S>> Encodable<S> for Box<T> {
657 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
661 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<T> {
662 fn decode(d: &mut D) -> Box<T> {
663 Box::new(Decodable::decode(d))