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_usize(&mut self, v: usize) -> Result<(), Self::Error>;
19 fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
20 fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
21 fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
22 fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
23 fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
24 fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
25 fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
26 fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
27 fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
28 fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
29 fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
30 fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
31 fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
32 fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
33 fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
34 fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
35 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error>;
37 // Convenience for the derive macro:
38 fn emit_enum_variant<F>(&mut self, v_id: usize, f: F) -> Result<(), Self::Error>
40 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
42 self.emit_usize(v_id)?;
46 // We put the field index in a const generic to allow the emit_usize to be
47 // compiled into a more efficient form. In practice, the variant index is
48 // known at compile-time, and that knowledge allows much more efficient
49 // codegen than we'd otherwise get. LLVM isn't always able to make the
50 // optimization that would otherwise be necessary here, likely due to the
51 // multiple levels of inlining and const-prop that are needed.
53 fn emit_fieldless_enum_variant<const ID: usize>(&mut self) -> Result<(), Self::Error> {
58 // Note: all the methods in this trait are infallible, which may be surprising.
59 // They used to be fallible (i.e. return a `Result`) but many of the impls just
60 // panicked when something went wrong, and for the cases that didn't the
61 // top-level invocation would also just panic on failure. Switching to
62 // infallibility made things faster and lots of code a little simpler and more
66 fn read_usize(&mut self) -> usize;
67 fn read_u128(&mut self) -> u128;
68 fn read_u64(&mut self) -> u64;
69 fn read_u32(&mut self) -> u32;
70 fn read_u16(&mut self) -> u16;
71 fn read_u8(&mut self) -> u8;
72 fn read_isize(&mut self) -> isize;
73 fn read_i128(&mut self) -> i128;
74 fn read_i64(&mut self) -> i64;
75 fn read_i32(&mut self) -> i32;
76 fn read_i16(&mut self) -> i16;
77 fn read_i8(&mut self) -> i8;
78 fn read_bool(&mut self) -> bool;
79 fn read_f64(&mut self) -> f64;
80 fn read_f32(&mut self) -> f32;
81 fn read_char(&mut self) -> char;
82 fn read_str(&mut self) -> &str;
83 fn read_raw_bytes(&mut self, len: usize) -> &[u8];
86 /// Trait for types that can be serialized
88 /// This can be implemented using the `Encodable`, `TyEncodable` and
89 /// `MetadataEncodable` macros.
91 /// * `Encodable` should be used in crates that don't depend on
93 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
94 /// `rustc_metadata::rmeta::Lazy`.
95 /// * `TyEncodable` should be used for types that are only serialized in crate
96 /// metadata or the incremental cache. This is most types in `rustc_middle`.
97 pub trait Encodable<S: Encoder> {
98 fn encode(&self, s: &mut S) -> Result<(), S::Error>;
101 /// Trait for types that can be deserialized
103 /// This can be implemented using the `Decodable`, `TyDecodable` and
104 /// `MetadataDecodable` macros.
106 /// * `Decodable` should be used in crates that don't depend on
108 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
109 /// `rustc_metadata::rmeta::Lazy`.
110 /// * `TyDecodable` should be used for types that are only serialized in crate
111 /// metadata or the incremental cache. This is most types in `rustc_middle`.
112 pub trait Decodable<D: Decoder>: Sized {
113 fn decode(d: &mut D) -> Self;
116 macro_rules! direct_serialize_impls {
117 ($($ty:ident $emit_method:ident $read_method:ident),*) => {
119 impl<S: Encoder> Encodable<S> for $ty {
120 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
121 s.$emit_method(*self)
125 impl<D: Decoder> Decodable<D> for $ty {
126 fn decode(d: &mut D) -> $ty {
134 direct_serialize_impls! {
135 usize emit_usize read_usize,
137 u16 emit_u16 read_u16,
138 u32 emit_u32 read_u32,
139 u64 emit_u64 read_u64,
140 u128 emit_u128 read_u128,
141 isize emit_isize read_isize,
143 i16 emit_i16 read_i16,
144 i32 emit_i32 read_i32,
145 i64 emit_i64 read_i64,
146 i128 emit_i128 read_i128,
147 f32 emit_f32 read_f32,
148 f64 emit_f64 read_f64,
149 bool emit_bool read_bool,
150 char emit_char read_char
153 impl<S: Encoder, T: ?Sized> Encodable<S> for &T
157 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
162 impl<S: Encoder> Encodable<S> for ! {
163 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
168 impl<D: Decoder> Decodable<D> for ! {
169 fn decode(_d: &mut D) -> ! {
174 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
175 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
176 s.emit_u32(self.get())
180 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
181 fn decode(d: &mut D) -> Self {
182 ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
186 impl<S: Encoder> Encodable<S> for str {
187 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
192 impl<S: Encoder> Encodable<S> for String {
193 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
194 s.emit_str(&self[..])
198 impl<D: Decoder> Decodable<D> for String {
199 fn decode(d: &mut D) -> String {
200 d.read_str().to_owned()
204 impl<S: Encoder> Encodable<S> for () {
205 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
210 impl<D: Decoder> Decodable<D> for () {
211 fn decode(_: &mut D) -> () {}
214 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
215 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
220 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
221 fn decode(_: &mut D) -> PhantomData<T> {
226 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<[T]> {
227 fn decode(d: &mut D) -> Box<[T]> {
228 let v: Vec<T> = Decodable::decode(d);
233 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
234 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
239 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
240 fn decode(d: &mut D) -> Rc<T> {
241 Rc::new(Decodable::decode(d))
245 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
246 default fn encode(&self, s: &mut S) -> Result<(), S::Error> {
247 s.emit_usize(self.len())?;
248 for e in self.iter() {
255 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
256 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
257 let slice: &[T] = self;
262 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Vec<T> {
263 default fn decode(d: &mut D) -> Vec<T> {
264 let len = d.read_usize();
265 // SAFETY: we set the capacity in advance, only write elements, and
266 // only set the length at the end once the writing has succeeded.
267 let mut vec = Vec::with_capacity(len);
269 let ptr: *mut T = vec.as_mut_ptr();
271 std::ptr::write(ptr.offset(i as isize), Decodable::decode(d));
279 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
280 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
281 let slice: &[T] = self;
286 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
287 fn decode(d: &mut D) -> [u8; N] {
288 let len = d.read_usize();
290 let mut v = [0u8; N];
292 v[i] = Decodable::decode(d);
298 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
300 [T]: ToOwned<Owned = Vec<T>>,
302 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
303 let slice: &[T] = self;
308 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
310 [T]: ToOwned<Owned = Vec<T>>,
312 fn decode(d: &mut D) -> Cow<'static, [T]> {
313 let v: Vec<T> = Decodable::decode(d);
318 impl<'a, S: Encoder> Encodable<S> for Cow<'a, str> {
319 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
320 let val: &str = self;
325 impl<'a, D: Decoder> Decodable<D> for Cow<'a, str> {
326 fn decode(d: &mut D) -> Cow<'static, str> {
327 let v: String = Decodable::decode(d);
332 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
333 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
335 None => s.emit_enum_variant(0, |_| Ok(())),
336 Some(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
341 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
342 fn decode(d: &mut D) -> Option<T> {
343 match d.read_usize() {
345 1 => Some(Decodable::decode(d)),
346 _ => panic!("Encountered invalid discriminant while decoding `Option`."),
351 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
352 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
354 Ok(ref v) => s.emit_enum_variant(0, |s| v.encode(s)),
355 Err(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
360 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
361 fn decode(d: &mut D) -> Result<T1, T2> {
362 match d.read_usize() {
363 0 => Ok(T1::decode(d)),
364 1 => Err(T2::decode(d)),
365 _ => panic!("Encountered invalid discriminant while decoding `Result`."),
371 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
376 ( $($name:ident,)+ ) => (
377 impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
378 fn decode(d: &mut D) -> ($($name,)+) {
379 ($({ let element: $name = Decodable::decode(d); element },)+)
382 impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
383 #[allow(non_snake_case)]
384 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
385 let ($(ref $name,)+) = *self;
386 $($name.encode(s)?;)+
394 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
396 impl<S: Encoder> Encodable<S> for path::Path {
397 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
398 self.to_str().unwrap().encode(e)
402 impl<S: Encoder> Encodable<S> for path::PathBuf {
403 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
404 path::Path::encode(self, e)
408 impl<D: Decoder> Decodable<D> for path::PathBuf {
409 fn decode(d: &mut D) -> path::PathBuf {
410 let bytes: String = Decodable::decode(d);
411 path::PathBuf::from(bytes)
415 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
416 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
421 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
422 fn decode(d: &mut D) -> Cell<T> {
423 Cell::new(Decodable::decode(d))
428 // Should use `try_borrow`, returning an
429 // `encoder.error("attempting to Encode borrowed RefCell")`
430 // from `encode` when `try_borrow` returns `None`.
432 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
433 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
434 self.borrow().encode(s)
438 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
439 fn decode(d: &mut D) -> RefCell<T> {
440 RefCell::new(Decodable::decode(d))
444 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
445 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
450 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
451 fn decode(d: &mut D) -> Arc<T> {
452 Arc::new(Decodable::decode(d))
456 impl<S: Encoder, T: ?Sized + Encodable<S>> Encodable<S> for Box<T> {
457 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
461 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<T> {
462 fn decode(d: &mut D) -> Box<T> {
463 Box::new(Decodable::decode(d))