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.
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>.)
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]);
49 fn emit_enum_variant
<F
>(&mut self, v_id
: usize, f
: F
)
53 self.emit_usize(v_id
);
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
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>.)
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];
89 /// Trait for types that can be serialized
91 /// This can be implemented using the `Encodable`, `TyEncodable` and
92 /// `MetadataEncodable` macros.
94 /// * `Encodable` should be used in crates that don't depend on
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
);
104 /// Trait for types that can be deserialized
106 /// This can be implemented using the `Decodable`, `TyDecodable` and
107 /// `MetadataDecodable` macros.
109 /// * `Decodable` should be used in crates that don't depend on
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;
119 macro_rules
! direct_serialize_impls
{
120 ($
($ty
:ident $emit_method
:ident $read_method
:ident
),*) => {
122 impl<S
: Encoder
> Encodable
<S
> for $ty
{
123 fn encode(&self, s
: &mut S
) {
124 s
.$
emit_method(*self);
128 impl<D
: Decoder
> Decodable
<D
> for $ty
{
129 fn decode(d
: &mut D
) -> $ty
{
137 direct_serialize_impls
! {
138 usize emit_usize read_usize
,
140 u16 emit_u16 read_u16
,
141 u32 emit_u32 read_u32
,
142 u64 emit_u64 read_u64
,
143 u128 emit_u128 read_u128
,
145 isize emit_isize read_isize
,
147 i16 emit_i16 read_i16
,
148 i32 emit_i32 read_i32
,
149 i64 emit_i64 read_i64
,
150 i128 emit_i128 read_i128
,
152 bool emit_bool read_bool
,
153 char emit_char read_char
156 impl<S
: Encoder
, T
: ?Sized
> Encodable
<S
> for &T
160 fn encode(&self, s
: &mut S
) {
165 impl<S
: Encoder
> Encodable
<S
> for ! {
166 fn encode(&self, _s
: &mut S
) {
171 impl<D
: Decoder
> Decodable
<D
> for ! {
172 fn decode(_d
: &mut D
) -> ! {
177 impl<S
: Encoder
> Encodable
<S
> for ::std
::num
::NonZeroU32
{
178 fn encode(&self, s
: &mut S
) {
179 s
.emit_u32(self.get());
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()
189 impl<S
: Encoder
> Encodable
<S
> for str {
190 fn encode(&self, s
: &mut S
) {
195 impl<S
: Encoder
> Encodable
<S
> for String
{
196 fn encode(&self, s
: &mut S
) {
197 s
.emit_str(&self[..]);
201 impl<D
: Decoder
> Decodable
<D
> for String
{
202 fn decode(d
: &mut D
) -> String
{
203 d
.read_str().to_owned()
207 impl<S
: Encoder
> Encodable
<S
> for () {
208 fn encode(&self, _s
: &mut S
) {}
211 impl<D
: Decoder
> Decodable
<D
> for () {
212 fn decode(_
: &mut D
) -> () {}
215 impl<S
: Encoder
, T
> Encodable
<S
> for PhantomData
<T
> {
216 fn encode(&self, _s
: &mut S
) {}
219 impl<D
: Decoder
, T
> Decodable
<D
> for PhantomData
<T
> {
220 fn decode(_
: &mut D
) -> PhantomData
<T
> {
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
);
232 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Rc
<T
> {
233 fn encode(&self, s
: &mut S
) {
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
))
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() {
253 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Vec
<T
> {
254 fn encode(&self, s
: &mut S
) {
255 let slice
: &[T
] = self;
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
);
268 let ptr
: *mut T
= vec
.as_mut_ptr();
270 std
::ptr
::write(ptr
.add(i
), Decodable
::decode(d
));
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;
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();
289 let mut v
= [0u8; N
];
291 v
[i
] = Decodable
::decode(d
);
297 impl<'a
, S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Cow
<'a
, [T
]>
299 [T
]: ToOwned
<Owned
= Vec
<T
>>,
301 fn encode(&self, s
: &mut S
) {
302 let slice
: &[T
] = self;
307 impl<D
: Decoder
, T
: Decodable
<D
> + ToOwned
> Decodable
<D
> for Cow
<'
static, [T
]>
309 [T
]: ToOwned
<Owned
= Vec
<T
>>,
311 fn decode(d
: &mut D
) -> Cow
<'
static, [T
]> {
312 let v
: Vec
<T
> = Decodable
::decode(d
);
317 impl<'a
, S
: Encoder
> Encodable
<S
> for Cow
<'a
, str> {
318 fn encode(&self, s
: &mut S
) {
319 let val
: &str = self;
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
);
331 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Option
<T
> {
332 fn encode(&self, s
: &mut S
) {
334 None
=> s
.emit_enum_variant(0, |_
| {}
),
335 Some(ref v
) => s
.emit_enum_variant(1, |s
| v
.encode(s
)),
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() {
344 1 => Some(Decodable
::decode(d
)),
345 _
=> panic
!("Encountered invalid discriminant while decoding `Option`."),
350 impl<S
: Encoder
, T1
: Encodable
<S
>, T2
: Encodable
<S
>> Encodable
<S
> for Result
<T1
, T2
> {
351 fn encode(&self, s
: &mut S
) {
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
)),
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`."),
370 ($name
:ident
, $
($other
:ident
,)*) => (tuple
! { $($other,)* }
)
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 }
,)+)
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;
392 tuple
! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
394 impl<S
: Encoder
> Encodable
<S
> for path
::Path
{
395 fn encode(&self, e
: &mut S
) {
396 self.to_str().unwrap().encode(e
);
400 impl<S
: Encoder
> Encodable
<S
> for path
::PathBuf
{
401 fn encode(&self, e
: &mut S
) {
402 path
::Path
::encode(self, e
);
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
)
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
);
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
))
425 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for RefCell
<T
> {
426 fn encode(&self, s
: &mut S
) {
427 self.borrow().encode(s
);
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
))
437 impl<S
: Encoder
, T
: Encodable
<S
>> Encodable
<S
> for Arc
<T
> {
438 fn encode(&self, s
: &mut S
) {
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
))
449 impl<S
: Encoder
, T
: ?Sized
+ Encodable
<S
>, A
: Allocator
+ Default
> Encodable
<S
> for Box
<T
, A
> {
450 fn encode(&self, s
: &mut S
) {
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
)