1 //! Support code for encoding and decoding types.
4 Core encoding and decoding interfaces.
7 use std::alloc::Allocator;
9 use std::cell::{Cell, RefCell};
10 use std::marker::PhantomData;
15 /// A note about error handling.
17 /// Encoders may be fallible, but in practice failure is rare and there are so
18 /// many nested calls that typical Rust error handling (via `Result` and `?`)
19 /// is pervasive and has non-trivial cost. Instead, impls of this trait must
20 /// implement a delayed error handling strategy. If a failure occurs, they
21 /// should record this internally, and all subsequent encoding operations can
22 /// be processed or ignored, whichever is appropriate. Then they should provide
23 /// a `finish` method that finishes up encoding. If the encoder is fallible,
24 /// `finish` should return a `Result` that indicates success or failure.
27 fn emit_usize(&mut self, v: usize);
28 fn emit_u128(&mut self, v: u128);
29 fn emit_u64(&mut self, v: u64);
30 fn emit_u32(&mut self, v: u32);
31 fn emit_u16(&mut self, v: u16);
32 fn emit_u8(&mut self, v: u8);
33 fn emit_isize(&mut self, v: isize);
34 fn emit_i128(&mut self, v: i128);
35 fn emit_i64(&mut self, v: i64);
36 fn emit_i32(&mut self, v: i32);
37 fn emit_i16(&mut self, v: i16);
38 fn emit_i8(&mut self, v: i8);
39 fn emit_bool(&mut self, v: bool);
40 fn emit_f64(&mut self, v: f64);
41 fn emit_f32(&mut self, v: f32);
42 fn emit_char(&mut self, v: char);
43 fn emit_str(&mut self, v: &str);
44 fn emit_raw_bytes(&mut self, s: &[u8]);
46 // Convenience for the derive macro:
47 fn emit_enum_variant<F>(&mut self, v_id: usize, f: F)
51 self.emit_usize(v_id);
55 // We put the field index in a const generic to allow the emit_usize to be
56 // compiled into a more efficient form. In practice, the variant index is
57 // known at compile-time, and that knowledge allows much more efficient
58 // codegen than we'd otherwise get. LLVM isn't always able to make the
59 // optimization that would otherwise be necessary here, likely due to the
60 // multiple levels of inlining and const-prop that are needed.
62 fn emit_fieldless_enum_variant<const ID: usize>(&mut self) {
67 // Note: all the methods in this trait are infallible, which may be surprising.
68 // They used to be fallible (i.e. return a `Result`) but many of the impls just
69 // panicked when something went wrong, and for the cases that didn't the
70 // top-level invocation would also just panic on failure. Switching to
71 // infallibility made things faster and lots of code a little simpler and more
75 fn read_usize(&mut self) -> usize;
76 fn read_u128(&mut self) -> u128;
77 fn read_u64(&mut self) -> u64;
78 fn read_u32(&mut self) -> u32;
79 fn read_u16(&mut self) -> u16;
80 fn read_u8(&mut self) -> u8;
81 fn read_isize(&mut self) -> isize;
82 fn read_i128(&mut self) -> i128;
83 fn read_i64(&mut self) -> i64;
84 fn read_i32(&mut self) -> i32;
85 fn read_i16(&mut self) -> i16;
86 fn read_i8(&mut self) -> i8;
87 fn read_bool(&mut self) -> bool;
88 fn read_f64(&mut self) -> f64;
89 fn read_f32(&mut self) -> f32;
90 fn read_char(&mut self) -> char;
91 fn read_str(&mut self) -> &str;
92 fn read_raw_bytes(&mut self, len: usize) -> &[u8];
95 /// Trait for types that can be serialized
97 /// This can be implemented using the `Encodable`, `TyEncodable` and
98 /// `MetadataEncodable` macros.
100 /// * `Encodable` should be used in crates that don't depend on
102 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
103 /// `rustc_metadata::rmeta::Lazy`.
104 /// * `TyEncodable` should be used for types that are only serialized in crate
105 /// metadata or the incremental cache. This is most types in `rustc_middle`.
106 pub trait Encodable<S: Encoder> {
107 fn encode(&self, s: &mut S);
110 /// Trait for types that can be deserialized
112 /// This can be implemented using the `Decodable`, `TyDecodable` and
113 /// `MetadataDecodable` macros.
115 /// * `Decodable` should be used in crates that don't depend on
117 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
118 /// `rustc_metadata::rmeta::Lazy`.
119 /// * `TyDecodable` should be used for types that are only serialized in crate
120 /// metadata or the incremental cache. This is most types in `rustc_middle`.
121 pub trait Decodable<D: Decoder>: Sized {
122 fn decode(d: &mut D) -> Self;
125 macro_rules! direct_serialize_impls {
126 ($($ty:ident $emit_method:ident $read_method:ident),*) => {
128 impl<S: Encoder> Encodable<S> for $ty {
129 fn encode(&self, s: &mut S) {
130 s.$emit_method(*self);
134 impl<D: Decoder> Decodable<D> for $ty {
135 fn decode(d: &mut D) -> $ty {
143 direct_serialize_impls! {
144 usize emit_usize read_usize,
146 u16 emit_u16 read_u16,
147 u32 emit_u32 read_u32,
148 u64 emit_u64 read_u64,
149 u128 emit_u128 read_u128,
151 isize emit_isize read_isize,
153 i16 emit_i16 read_i16,
154 i32 emit_i32 read_i32,
155 i64 emit_i64 read_i64,
156 i128 emit_i128 read_i128,
158 f32 emit_f32 read_f32,
159 f64 emit_f64 read_f64,
160 bool emit_bool read_bool,
161 char emit_char read_char
164 impl<S: Encoder, T: ?Sized> Encodable<S> for &T
168 fn encode(&self, s: &mut S) {
173 impl<S: Encoder> Encodable<S> for ! {
174 fn encode(&self, _s: &mut S) {
179 impl<D: Decoder> Decodable<D> for ! {
180 fn decode(_d: &mut D) -> ! {
185 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
186 fn encode(&self, s: &mut S) {
187 s.emit_u32(self.get());
191 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
192 fn decode(d: &mut D) -> Self {
193 ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
197 impl<S: Encoder> Encodable<S> for str {
198 fn encode(&self, s: &mut S) {
203 impl<S: Encoder> Encodable<S> for String {
204 fn encode(&self, s: &mut S) {
205 s.emit_str(&self[..]);
209 impl<D: Decoder> Decodable<D> for String {
210 fn decode(d: &mut D) -> String {
211 d.read_str().to_owned()
215 impl<S: Encoder> Encodable<S> for () {
216 fn encode(&self, _s: &mut S) {}
219 impl<D: Decoder> Decodable<D> for () {
220 fn decode(_: &mut D) -> () {}
223 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
224 fn encode(&self, _s: &mut S) {}
227 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
228 fn decode(_: &mut D) -> PhantomData<T> {
233 impl<D: Decoder, A: Allocator + Default, T: Decodable<D>> Decodable<D> for Box<[T], A> {
234 fn decode(d: &mut D) -> Box<[T], A> {
235 let v: Vec<T, A> = Decodable::decode(d);
240 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
241 fn encode(&self, s: &mut S) {
246 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
247 fn decode(d: &mut D) -> Rc<T> {
248 Rc::new(Decodable::decode(d))
252 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
253 default fn encode(&self, s: &mut S) {
254 s.emit_usize(self.len());
255 for e in self.iter() {
261 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
262 fn encode(&self, s: &mut S) {
263 let slice: &[T] = self;
268 impl<D: Decoder, T: Decodable<D>, A: Allocator + Default> Decodable<D> for Vec<T, A> {
269 default fn decode(d: &mut D) -> Vec<T, A> {
270 let len = d.read_usize();
271 let allocator = A::default();
272 // SAFETY: we set the capacity in advance, only write elements, and
273 // only set the length at the end once the writing has succeeded.
274 let mut vec = Vec::with_capacity_in(len, allocator);
276 let ptr: *mut T = vec.as_mut_ptr();
278 std::ptr::write(ptr.add(i), Decodable::decode(d));
286 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
287 fn encode(&self, s: &mut S) {
288 let slice: &[T] = self;
293 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
294 fn decode(d: &mut D) -> [u8; N] {
295 let len = d.read_usize();
297 let mut v = [0u8; N];
299 v[i] = Decodable::decode(d);
305 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
307 [T]: ToOwned<Owned = Vec<T>>,
309 fn encode(&self, s: &mut S) {
310 let slice: &[T] = self;
315 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
317 [T]: ToOwned<Owned = Vec<T>>,
319 fn decode(d: &mut D) -> Cow<'static, [T]> {
320 let v: Vec<T> = Decodable::decode(d);
325 impl<'a, S: Encoder> Encodable<S> for Cow<'a, str> {
326 fn encode(&self, s: &mut S) {
327 let val: &str = self;
332 impl<'a, D: Decoder> Decodable<D> for Cow<'a, str> {
333 fn decode(d: &mut D) -> Cow<'static, str> {
334 let v: String = Decodable::decode(d);
339 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
340 fn encode(&self, s: &mut S) {
342 None => s.emit_enum_variant(0, |_| {}),
343 Some(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
348 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
349 fn decode(d: &mut D) -> Option<T> {
350 match d.read_usize() {
352 1 => Some(Decodable::decode(d)),
353 _ => panic!("Encountered invalid discriminant while decoding `Option`."),
358 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
359 fn encode(&self, s: &mut S) {
361 Ok(ref v) => s.emit_enum_variant(0, |s| v.encode(s)),
362 Err(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
367 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
368 fn decode(d: &mut D) -> Result<T1, T2> {
369 match d.read_usize() {
370 0 => Ok(T1::decode(d)),
371 1 => Err(T2::decode(d)),
372 _ => panic!("Encountered invalid discriminant while decoding `Result`."),
378 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
383 ( $($name:ident,)+ ) => (
384 impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
385 fn decode(d: &mut D) -> ($($name,)+) {
386 ($({ let element: $name = Decodable::decode(d); element },)+)
389 impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
390 #[allow(non_snake_case)]
391 fn encode(&self, s: &mut S) {
392 let ($(ref $name,)+) = *self;
400 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
402 impl<S: Encoder> Encodable<S> for path::Path {
403 fn encode(&self, e: &mut S) {
404 self.to_str().unwrap().encode(e);
408 impl<S: Encoder> Encodable<S> for path::PathBuf {
409 fn encode(&self, e: &mut S) {
410 path::Path::encode(self, e);
414 impl<D: Decoder> Decodable<D> for path::PathBuf {
415 fn decode(d: &mut D) -> path::PathBuf {
416 let bytes: String = Decodable::decode(d);
417 path::PathBuf::from(bytes)
421 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
422 fn encode(&self, s: &mut S) {
423 self.get().encode(s);
427 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
428 fn decode(d: &mut D) -> Cell<T> {
429 Cell::new(Decodable::decode(d))
434 // Should use `try_borrow`, returning an
435 // `encoder.error("attempting to Encode borrowed RefCell")`
436 // from `encode` when `try_borrow` returns `None`.
438 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
439 fn encode(&self, s: &mut S) {
440 self.borrow().encode(s);
444 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
445 fn decode(d: &mut D) -> RefCell<T> {
446 RefCell::new(Decodable::decode(d))
450 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
451 fn encode(&self, s: &mut S) {
456 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
457 fn decode(d: &mut D) -> Arc<T> {
458 Arc::new(Decodable::decode(d))
462 impl<S: Encoder, T: ?Sized + Encodable<S>, A: Allocator + Default> Encodable<S> for Box<T, A> {
463 fn encode(&self, s: &mut S) {
468 impl<D: Decoder, A: Allocator + Default, T: Decodable<D>> Decodable<D> for Box<T, A> {
469 fn decode(d: &mut D) -> Box<T, A> {
470 let allocator = A::default();
471 Box::new_in(Decodable::decode(d), allocator)