]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_serialize/src/serialize.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / compiler / rustc_serialize / src / serialize.rs
1 //! Support code for encoding and decoding types.
2
3 /*
4 Core encoding and decoding interfaces.
5 */
6
7 use std::alloc::Allocator;
8 use std::borrow::Cow;
9 use std::cell::{Cell, RefCell};
10 use std::marker::PhantomData;
11 use std::path;
12 use std::rc::Rc;
13 use std::sync::Arc;
14
15 /// A note about error handling.
16 ///
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.
25 ///
26 /// This current does not support `f32` nor `f64`, as they're not needed in any
27 /// serialized data structures. That could be changed, but consider whether it
28 /// really makes sense to store floating-point values at all.
29 /// (If you need it, revert <https://github.com/rust-lang/rust/pull/109984>.)
30 pub trait Encoder {
31 // Primitive types:
32 fn emit_usize(&mut self, v: usize);
33 fn emit_u128(&mut self, v: u128);
34 fn emit_u64(&mut self, v: u64);
35 fn emit_u32(&mut self, v: u32);
36 fn emit_u16(&mut self, v: u16);
37 fn emit_u8(&mut self, v: u8);
38 fn emit_isize(&mut self, v: isize);
39 fn emit_i128(&mut self, v: i128);
40 fn emit_i64(&mut self, v: i64);
41 fn emit_i32(&mut self, v: i32);
42 fn emit_i16(&mut self, v: i16);
43 fn emit_i8(&mut self, v: i8);
44 fn emit_bool(&mut self, v: bool);
45 fn emit_char(&mut self, v: char);
46 fn emit_str(&mut self, v: &str);
47 fn emit_raw_bytes(&mut self, s: &[u8]);
48
49 fn emit_enum_variant<F>(&mut self, v_id: usize, f: F)
50 where
51 F: FnOnce(&mut Self),
52 {
53 self.emit_usize(v_id);
54 f(self);
55 }
56 }
57
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
63 // concise.
64 ///
65 /// This current does not support `f32` nor `f64`, as they're not needed in any
66 /// serialized data structures. That could be changed, but consider whether it
67 /// really makes sense to store floating-point values at all.
68 /// (If you need it, revert <https://github.com/rust-lang/rust/pull/109984>.)
69 pub trait Decoder {
70 // Primitive types:
71 fn read_usize(&mut self) -> usize;
72 fn read_u128(&mut self) -> u128;
73 fn read_u64(&mut self) -> u64;
74 fn read_u32(&mut self) -> u32;
75 fn read_u16(&mut self) -> u16;
76 fn read_u8(&mut self) -> u8;
77 fn read_isize(&mut self) -> isize;
78 fn read_i128(&mut self) -> i128;
79 fn read_i64(&mut self) -> i64;
80 fn read_i32(&mut self) -> i32;
81 fn read_i16(&mut self) -> i16;
82 fn read_i8(&mut self) -> i8;
83 fn read_bool(&mut self) -> bool;
84 fn read_char(&mut self) -> char;
85 fn read_str(&mut self) -> &str;
86 fn read_raw_bytes(&mut self, len: usize) -> &[u8];
87 }
88
89 /// Trait for types that can be serialized
90 ///
91 /// This can be implemented using the `Encodable`, `TyEncodable` and
92 /// `MetadataEncodable` macros.
93 ///
94 /// * `Encodable` should be used in crates that don't depend on
95 /// `rustc_middle`.
96 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
97 /// `rustc_metadata::rmeta::Lazy`.
98 /// * `TyEncodable` should be used for types that are only serialized in crate
99 /// metadata or the incremental cache. This is most types in `rustc_middle`.
100 pub trait Encodable<S: Encoder> {
101 fn encode(&self, s: &mut S);
102 }
103
104 /// Trait for types that can be deserialized
105 ///
106 /// This can be implemented using the `Decodable`, `TyDecodable` and
107 /// `MetadataDecodable` macros.
108 ///
109 /// * `Decodable` should be used in crates that don't depend on
110 /// `rustc_middle`.
111 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
112 /// `rustc_metadata::rmeta::Lazy`.
113 /// * `TyDecodable` should be used for types that are only serialized in crate
114 /// metadata or the incremental cache. This is most types in `rustc_middle`.
115 pub trait Decodable<D: Decoder>: Sized {
116 fn decode(d: &mut D) -> Self;
117 }
118
119 macro_rules! direct_serialize_impls {
120 ($($ty:ident $emit_method:ident $read_method:ident),*) => {
121 $(
122 impl<S: Encoder> Encodable<S> for $ty {
123 fn encode(&self, s: &mut S) {
124 s.$emit_method(*self);
125 }
126 }
127
128 impl<D: Decoder> Decodable<D> for $ty {
129 fn decode(d: &mut D) -> $ty {
130 d.$read_method()
131 }
132 }
133 )*
134 }
135 }
136
137 direct_serialize_impls! {
138 usize emit_usize read_usize,
139 u8 emit_u8 read_u8,
140 u16 emit_u16 read_u16,
141 u32 emit_u32 read_u32,
142 u64 emit_u64 read_u64,
143 u128 emit_u128 read_u128,
144
145 isize emit_isize read_isize,
146 i8 emit_i8 read_i8,
147 i16 emit_i16 read_i16,
148 i32 emit_i32 read_i32,
149 i64 emit_i64 read_i64,
150 i128 emit_i128 read_i128,
151
152 bool emit_bool read_bool,
153 char emit_char read_char
154 }
155
156 impl<S: Encoder, T: ?Sized> Encodable<S> for &T
157 where
158 T: Encodable<S>,
159 {
160 fn encode(&self, s: &mut S) {
161 (**self).encode(s)
162 }
163 }
164
165 impl<S: Encoder> Encodable<S> for ! {
166 fn encode(&self, _s: &mut S) {
167 unreachable!();
168 }
169 }
170
171 impl<D: Decoder> Decodable<D> for ! {
172 fn decode(_d: &mut D) -> ! {
173 unreachable!()
174 }
175 }
176
177 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
178 fn encode(&self, s: &mut S) {
179 s.emit_u32(self.get());
180 }
181 }
182
183 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
184 fn decode(d: &mut D) -> Self {
185 ::std::num::NonZeroU32::new(d.read_u32()).unwrap()
186 }
187 }
188
189 impl<S: Encoder> Encodable<S> for str {
190 fn encode(&self, s: &mut S) {
191 s.emit_str(self);
192 }
193 }
194
195 impl<S: Encoder> Encodable<S> for String {
196 fn encode(&self, s: &mut S) {
197 s.emit_str(&self[..]);
198 }
199 }
200
201 impl<D: Decoder> Decodable<D> for String {
202 fn decode(d: &mut D) -> String {
203 d.read_str().to_owned()
204 }
205 }
206
207 impl<S: Encoder> Encodable<S> for () {
208 fn encode(&self, _s: &mut S) {}
209 }
210
211 impl<D: Decoder> Decodable<D> for () {
212 fn decode(_: &mut D) -> () {}
213 }
214
215 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
216 fn encode(&self, _s: &mut S) {}
217 }
218
219 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
220 fn decode(_: &mut D) -> PhantomData<T> {
221 PhantomData
222 }
223 }
224
225 impl<D: Decoder, A: Allocator + Default, T: Decodable<D>> Decodable<D> for Box<[T], A> {
226 fn decode(d: &mut D) -> Box<[T], A> {
227 let v: Vec<T, A> = Decodable::decode(d);
228 v.into_boxed_slice()
229 }
230 }
231
232 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
233 fn encode(&self, s: &mut S) {
234 (**self).encode(s);
235 }
236 }
237
238 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
239 fn decode(d: &mut D) -> Rc<T> {
240 Rc::new(Decodable::decode(d))
241 }
242 }
243
244 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
245 default fn encode(&self, s: &mut S) {
246 s.emit_usize(self.len());
247 for e in self.iter() {
248 e.encode(s);
249 }
250 }
251 }
252
253 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
254 fn encode(&self, s: &mut S) {
255 let slice: &[T] = self;
256 slice.encode(s);
257 }
258 }
259
260 impl<D: Decoder, T: Decodable<D>, A: Allocator + Default> Decodable<D> for Vec<T, A> {
261 default fn decode(d: &mut D) -> Vec<T, A> {
262 let len = d.read_usize();
263 let allocator = A::default();
264 // SAFETY: we set the capacity in advance, only write elements, and
265 // only set the length at the end once the writing has succeeded.
266 let mut vec = Vec::with_capacity_in(len, allocator);
267 unsafe {
268 let ptr: *mut T = vec.as_mut_ptr();
269 for i in 0..len {
270 std::ptr::write(ptr.add(i), Decodable::decode(d));
271 }
272 vec.set_len(len);
273 }
274 vec
275 }
276 }
277
278 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
279 fn encode(&self, s: &mut S) {
280 let slice: &[T] = self;
281 slice.encode(s);
282 }
283 }
284
285 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
286 fn decode(d: &mut D) -> [u8; N] {
287 let len = d.read_usize();
288 assert!(len == N);
289 let mut v = [0u8; N];
290 for i in 0..len {
291 v[i] = Decodable::decode(d);
292 }
293 v
294 }
295 }
296
297 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
298 where
299 [T]: ToOwned<Owned = Vec<T>>,
300 {
301 fn encode(&self, s: &mut S) {
302 let slice: &[T] = self;
303 slice.encode(s);
304 }
305 }
306
307 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
308 where
309 [T]: ToOwned<Owned = Vec<T>>,
310 {
311 fn decode(d: &mut D) -> Cow<'static, [T]> {
312 let v: Vec<T> = Decodable::decode(d);
313 Cow::Owned(v)
314 }
315 }
316
317 impl<'a, S: Encoder> Encodable<S> for Cow<'a, str> {
318 fn encode(&self, s: &mut S) {
319 let val: &str = self;
320 val.encode(s)
321 }
322 }
323
324 impl<'a, D: Decoder> Decodable<D> for Cow<'a, str> {
325 fn decode(d: &mut D) -> Cow<'static, str> {
326 let v: String = Decodable::decode(d);
327 Cow::Owned(v)
328 }
329 }
330
331 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
332 fn encode(&self, s: &mut S) {
333 match *self {
334 None => s.emit_enum_variant(0, |_| {}),
335 Some(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
336 }
337 }
338 }
339
340 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
341 fn decode(d: &mut D) -> Option<T> {
342 match d.read_usize() {
343 0 => None,
344 1 => Some(Decodable::decode(d)),
345 _ => panic!("Encountered invalid discriminant while decoding `Option`."),
346 }
347 }
348 }
349
350 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
351 fn encode(&self, s: &mut S) {
352 match *self {
353 Ok(ref v) => s.emit_enum_variant(0, |s| v.encode(s)),
354 Err(ref v) => s.emit_enum_variant(1, |s| v.encode(s)),
355 }
356 }
357 }
358
359 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
360 fn decode(d: &mut D) -> Result<T1, T2> {
361 match d.read_usize() {
362 0 => Ok(T1::decode(d)),
363 1 => Err(T2::decode(d)),
364 _ => panic!("Encountered invalid discriminant while decoding `Result`."),
365 }
366 }
367 }
368
369 macro_rules! peel {
370 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
371 }
372
373 macro_rules! tuple {
374 () => ();
375 ( $($name:ident,)+ ) => (
376 impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
377 fn decode(d: &mut D) -> ($($name,)+) {
378 ($({ let element: $name = Decodable::decode(d); element },)+)
379 }
380 }
381 impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
382 #[allow(non_snake_case)]
383 fn encode(&self, s: &mut S) {
384 let ($(ref $name,)+) = *self;
385 $($name.encode(s);)+
386 }
387 }
388 peel! { $($name,)+ }
389 )
390 }
391
392 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
393
394 impl<S: Encoder> Encodable<S> for path::Path {
395 fn encode(&self, e: &mut S) {
396 self.to_str().unwrap().encode(e);
397 }
398 }
399
400 impl<S: Encoder> Encodable<S> for path::PathBuf {
401 fn encode(&self, e: &mut S) {
402 path::Path::encode(self, e);
403 }
404 }
405
406 impl<D: Decoder> Decodable<D> for path::PathBuf {
407 fn decode(d: &mut D) -> path::PathBuf {
408 let bytes: String = Decodable::decode(d);
409 path::PathBuf::from(bytes)
410 }
411 }
412
413 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
414 fn encode(&self, s: &mut S) {
415 self.get().encode(s);
416 }
417 }
418
419 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
420 fn decode(d: &mut D) -> Cell<T> {
421 Cell::new(Decodable::decode(d))
422 }
423 }
424
425 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
426 fn encode(&self, s: &mut S) {
427 self.borrow().encode(s);
428 }
429 }
430
431 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
432 fn decode(d: &mut D) -> RefCell<T> {
433 RefCell::new(Decodable::decode(d))
434 }
435 }
436
437 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
438 fn encode(&self, s: &mut S) {
439 (**self).encode(s);
440 }
441 }
442
443 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
444 fn decode(d: &mut D) -> Arc<T> {
445 Arc::new(Decodable::decode(d))
446 }
447 }
448
449 impl<S: Encoder, T: ?Sized + Encodable<S>, A: Allocator + Default> Encodable<S> for Box<T, A> {
450 fn encode(&self, s: &mut S) {
451 (**self).encode(s)
452 }
453 }
454
455 impl<D: Decoder, A: Allocator + Default, T: Decodable<D>> Decodable<D> for Box<T, A> {
456 fn decode(d: &mut D) -> Box<T, A> {
457 let allocator = A::default();
458 Box::new_in(Decodable::decode(d), allocator)
459 }
460 }