]> git.proxmox.com Git - rustc.git/blame - src/libserialize/serialize.rs
New upstream version 1.42.0+dfsg1
[rustc.git] / src / libserialize / serialize.rs
CommitLineData
1a4d82fc
JJ
1//! Support code for encoding and decoding types.
2
3/*
4Core encoding and decoding interfaces.
5*/
6
416331ca 7use std::any;
c30ab7b3 8use std::borrow::Cow;
dfeec247 9use std::cell::{Cell, RefCell};
0bf4aa26 10use std::marker::PhantomData;
c34b1796 11use std::path;
1a4d82fc 12use std::rc::Rc;
1a4d82fc
JJ
13use std::sync::Arc;
14
15pub trait Encoder {
16 type Error;
17
18 // Primitive types:
b7449926 19 fn emit_unit(&mut self) -> Result<(), Self::Error>;
9e0c209e 20 fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
32a655c1 21 fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
1a4d82fc
JJ
22 fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
23 fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
24 fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
25 fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
9e0c209e 26 fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
32a655c1 27 fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
1a4d82fc
JJ
28 fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
29 fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
30 fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
31 fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
32 fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
33 fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
34 fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
35 fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
36 fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
37
38 // Compound types:
9e0c209e 39 fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
dfeec247
XL
40 where
41 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
42 {
43 f(self)
44 }
45
dfeec247
XL
46 fn emit_enum_variant<F>(
47 &mut self,
48 _v_name: &str,
49 v_id: usize,
50 _len: usize,
51 f: F,
52 ) -> Result<(), Self::Error>
53 where
54 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
55 {
56 self.emit_usize(v_id)?;
57 f(self)
58 }
1a4d82fc 59
b7449926 60 fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
61 where
62 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
63 {
64 f(self)
65 }
66
dfeec247
XL
67 fn emit_enum_struct_variant<F>(
68 &mut self,
69 v_name: &str,
70 v_id: usize,
71 len: usize,
72 f: F,
73 ) -> Result<(), Self::Error>
74 where
75 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
76 {
77 self.emit_enum_variant(v_name, v_id, len, f)
78 }
b7449926 79
dfeec247
XL
80 fn emit_enum_struct_variant_field<F>(
81 &mut self,
82 _f_name: &str,
83 f_idx: usize,
84 f: F,
85 ) -> Result<(), Self::Error>
86 where
87 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
88 {
89 self.emit_enum_variant_arg(f_idx, f)
90 }
1a4d82fc 91
b7449926 92 fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
93 where
94 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
95 {
96 f(self)
97 }
98
dfeec247
XL
99 fn emit_struct_field<F>(
100 &mut self,
101 _f_name: &str,
102 _f_idx: usize,
103 f: F,
104 ) -> Result<(), Self::Error>
105 where
106 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
107 {
108 f(self)
109 }
1a4d82fc 110
9e0c209e 111 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
112 where
113 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
114 {
115 f(self)
116 }
117
9e0c209e 118 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
119 where
120 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
121 {
122 f(self)
123 }
1a4d82fc 124
b7449926 125 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
126 where
127 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
128 {
129 self.emit_tuple(len, f)
130 }
b7449926
XL
131
132 fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
133 where
134 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
135 {
136 self.emit_tuple_arg(f_idx, f)
137 }
1a4d82fc
JJ
138
139 // Specialized types:
140 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
dfeec247
XL
141 where
142 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
143 {
144 self.emit_enum("Option", f)
145 }
b7449926
XL
146
147 #[inline]
9e0c209e
SL
148 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
149 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
150 }
b7449926 151
1a4d82fc 152 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
dfeec247
XL
153 where
154 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e 155 {
9e0c209e
SL
156 self.emit_enum_variant("Some", 1, 1, f)
157 }
1a4d82fc 158
c34b1796 159 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
160 where
161 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
162 {
163 self.emit_usize(len)?;
164 f(self)
165 }
b7449926 166
9e0c209e 167 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
168 where
169 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
170 {
171 f(self)
172 }
1a4d82fc 173
c34b1796 174 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
175 where
176 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
9e0c209e
SL
177 {
178 self.emit_usize(len)?;
179 f(self)
180 }
b7449926 181
9e0c209e 182 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
183 where
184 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
185 {
186 f(self)
187 }
188
9e0c209e 189 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
dfeec247
XL
190 where
191 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
b7449926
XL
192 {
193 f(self)
194 }
1a4d82fc
JJ
195}
196
197pub trait Decoder {
198 type Error;
199
200 // Primitive types:
201 fn read_nil(&mut self) -> Result<(), Self::Error>;
9e0c209e 202 fn read_usize(&mut self) -> Result<usize, Self::Error>;
32a655c1 203 fn read_u128(&mut self) -> Result<u128, Self::Error>;
1a4d82fc
JJ
204 fn read_u64(&mut self) -> Result<u64, Self::Error>;
205 fn read_u32(&mut self) -> Result<u32, Self::Error>;
206 fn read_u16(&mut self) -> Result<u16, Self::Error>;
207 fn read_u8(&mut self) -> Result<u8, Self::Error>;
9e0c209e 208 fn read_isize(&mut self) -> Result<isize, Self::Error>;
32a655c1 209 fn read_i128(&mut self) -> Result<i128, Self::Error>;
1a4d82fc
JJ
210 fn read_i64(&mut self) -> Result<i64, Self::Error>;
211 fn read_i32(&mut self) -> Result<i32, Self::Error>;
212 fn read_i16(&mut self) -> Result<i16, Self::Error>;
213 fn read_i8(&mut self) -> Result<i8, Self::Error>;
214 fn read_bool(&mut self) -> Result<bool, Self::Error>;
215 fn read_f64(&mut self) -> Result<f64, Self::Error>;
216 fn read_f32(&mut self) -> Result<f32, Self::Error>;
217 fn read_char(&mut self) -> Result<char, Self::Error>;
9fa01778 218 fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error>;
1a4d82fc
JJ
219
220 // Compound types:
9e0c209e 221 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
dfeec247
XL
222 where
223 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
224 {
225 f(self)
226 }
1a4d82fc 227
b7449926 228 fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
dfeec247
XL
229 where
230 F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
9e0c209e
SL
231 {
232 let disr = self.read_usize()?;
233 f(self, disr)
234 }
1a4d82fc 235
b7449926 236 fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
237 where
238 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
239 {
240 f(self)
241 }
242
243 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
dfeec247
XL
244 where
245 F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
9e0c209e
SL
246 {
247 self.read_enum_variant(names, f)
248 }
b7449926 249
dfeec247
XL
250 fn read_enum_struct_variant_field<T, F>(
251 &mut self,
252 _f_name: &str,
253 f_idx: usize,
254 f: F,
255 ) -> Result<T, Self::Error>
256 where
257 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
9e0c209e
SL
258 {
259 self.read_enum_variant_arg(f_idx, f)
260 }
1a4d82fc 261
b7449926 262 fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
263 where
264 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
265 {
266 f(self)
267 }
268
dfeec247
XL
269 fn read_struct_field<T, F>(
270 &mut self,
271 _f_name: &str,
272 _f_idx: usize,
273 f: F,
274 ) -> Result<T, Self::Error>
275 where
276 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
277 {
278 f(self)
279 }
1a4d82fc 280
9e0c209e 281 fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
282 where
283 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
284 {
285 f(self)
286 }
1a4d82fc 287
b7449926 288 fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
289 where
290 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
291 {
292 f(self)
293 }
294
295 fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
296 where
297 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
9e0c209e
SL
298 {
299 self.read_tuple(len, f)
300 }
b7449926
XL
301
302 fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
303 where
304 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
9e0c209e
SL
305 {
306 self.read_tuple_arg(a_idx, f)
307 }
1a4d82fc
JJ
308
309 // Specialized types:
9e0c209e 310 fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
dfeec247
XL
311 where
312 F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
9e0c209e
SL
313 {
314 self.read_enum("Option", move |this| {
dfeec247
XL
315 this.read_enum_variant(&["None", "Some"], move |this, idx| match idx {
316 0 => f(this, false),
317 1 => f(this, true),
318 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
9e0c209e
SL
319 })
320 })
321 }
1a4d82fc
JJ
322
323 fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
dfeec247
XL
324 where
325 F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
9e0c209e
SL
326 {
327 let len = self.read_usize()?;
328 f(self, len)
329 }
b7449926 330
9e0c209e 331 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
332 where
333 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
334 {
335 f(self)
336 }
1a4d82fc
JJ
337
338 fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
dfeec247
XL
339 where
340 F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
9e0c209e
SL
341 {
342 let len = self.read_usize()?;
343 f(self, len)
344 }
b7449926
XL
345
346 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
347 where
348 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
349 {
350 f(self)
351 }
352
353 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
dfeec247
XL
354 where
355 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
b7449926
XL
356 {
357 f(self)
358 }
1a4d82fc
JJ
359
360 // Failure
361 fn error(&mut self, err: &str) -> Self::Error;
362}
363
364pub trait Encodable {
365 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
366}
367
e9174d1e 368pub trait Decodable: Sized {
1a4d82fc
JJ
369 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
370}
371
c34b1796 372impl Encodable for usize {
1a4d82fc 373 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
9e0c209e 374 s.emit_usize(*self)
1a4d82fc
JJ
375 }
376}
377
c34b1796
AL
378impl Decodable for usize {
379 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
9e0c209e 380 d.read_usize()
1a4d82fc
JJ
381 }
382}
383
384impl Encodable for u8 {
385 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
386 s.emit_u8(*self)
387 }
388}
389
390impl Decodable for u8 {
391 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
392 d.read_u8()
393 }
394}
395
396impl Encodable for u16 {
397 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
398 s.emit_u16(*self)
399 }
400}
401
402impl Decodable for u16 {
403 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
404 d.read_u16()
405 }
406}
407
408impl Encodable for u32 {
409 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
410 s.emit_u32(*self)
411 }
412}
413
414impl Decodable for u32 {
415 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
416 d.read_u32()
417 }
418}
419
b7449926
XL
420impl Encodable for ::std::num::NonZeroU32 {
421 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
422 s.emit_u32(self.get())
423 }
424}
425
426impl Decodable for ::std::num::NonZeroU32 {
427 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
428 d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
429 }
430}
431
1a4d82fc
JJ
432impl Encodable for u64 {
433 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
434 s.emit_u64(*self)
435 }
436}
437
438impl Decodable for u64 {
439 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
440 d.read_u64()
441 }
442}
443
32a655c1
SL
444impl Encodable for u128 {
445 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
446 s.emit_u128(*self)
447 }
448}
449
32a655c1
SL
450impl Decodable for u128 {
451 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
452 d.read_u128()
453 }
454}
455
c34b1796 456impl Encodable for isize {
1a4d82fc 457 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
9e0c209e 458 s.emit_isize(*self)
1a4d82fc
JJ
459 }
460}
461
c34b1796
AL
462impl Decodable for isize {
463 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
9e0c209e 464 d.read_isize()
1a4d82fc
JJ
465 }
466}
467
468impl Encodable for i8 {
469 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
470 s.emit_i8(*self)
471 }
472}
473
474impl Decodable for i8 {
475 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
476 d.read_i8()
477 }
478}
479
480impl Encodable for i16 {
481 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
482 s.emit_i16(*self)
483 }
484}
485
486impl Decodable for i16 {
487 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
488 d.read_i16()
489 }
490}
491
492impl Encodable for i32 {
493 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
494 s.emit_i32(*self)
495 }
496}
497
498impl Decodable for i32 {
499 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
500 d.read_i32()
501 }
502}
503
504impl Encodable for i64 {
505 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
506 s.emit_i64(*self)
507 }
508}
509
510impl Decodable for i64 {
511 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
512 d.read_i64()
513 }
514}
515
32a655c1
SL
516impl Encodable for i128 {
517 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
518 s.emit_i128(*self)
519 }
520}
521
32a655c1
SL
522impl Decodable for i128 {
523 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
524 d.read_i128()
525 }
526}
527
1a4d82fc
JJ
528impl Encodable for str {
529 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
530 s.emit_str(self)
531 }
532}
533
534impl Encodable for String {
535 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
85aaf69f 536 s.emit_str(&self[..])
1a4d82fc
JJ
537 }
538}
539
540impl Decodable for String {
541 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
c30ab7b3 542 Ok(d.read_str()?.into_owned())
1a4d82fc
JJ
543 }
544}
545
546impl Encodable for f32 {
547 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
548 s.emit_f32(*self)
549 }
550}
551
552impl Decodable for f32 {
553 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
554 d.read_f32()
555 }
556}
557
558impl Encodable for f64 {
559 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
560 s.emit_f64(*self)
561 }
562}
563
564impl Decodable for f64 {
565 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
566 d.read_f64()
567 }
568}
569
570impl Encodable for bool {
571 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
572 s.emit_bool(*self)
573 }
574}
575
576impl Decodable for bool {
577 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
578 d.read_bool()
579 }
580}
581
582impl Encodable for char {
583 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
584 s.emit_char(*self)
585 }
586}
587
588impl Decodable for char {
589 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
590 d.read_char()
591 }
592}
593
594impl Encodable for () {
595 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
b7449926 596 s.emit_unit()
1a4d82fc
JJ
597 }
598}
599
600impl Decodable for () {
601 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
602 d.read_nil()
603 }
604}
605
0bf4aa26
XL
606impl<T> Encodable for PhantomData<T> {
607 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
608 s.emit_unit()
609 }
610}
611
612impl<T> Decodable for PhantomData<T> {
613 fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
614 d.read_nil()?;
615 Ok(PhantomData)
616 }
617}
618
1a4d82fc
JJ
619impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
620 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
621 (**self).encode(s)
622 }
623}
624
625impl<T: ?Sized + Encodable> Encodable for Box<T> {
626 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
627 (**self).encode(s)
628 }
629}
630
dfeec247 631impl<T: Decodable> Decodable for Box<T> {
1a4d82fc 632 fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
54a0048b 633 Ok(box Decodable::decode(d)?)
1a4d82fc
JJ
634 }
635}
636
dfeec247 637impl<T: Decodable> Decodable for Box<[T]> {
1a4d82fc 638 fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
54a0048b 639 let v: Vec<T> = Decodable::decode(d)?;
1a4d82fc
JJ
640 Ok(v.into_boxed_slice())
641 }
642}
643
dfeec247 644impl<T: Encodable> Encodable for Rc<T> {
1a4d82fc
JJ
645 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
646 (**self).encode(s)
647 }
648}
649
dfeec247 650impl<T: Decodable> Decodable for Rc<T> {
1a4d82fc 651 fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
54a0048b 652 Ok(Rc::new(Decodable::decode(d)?))
1a4d82fc
JJ
653 }
654}
655
dfeec247 656impl<T: Encodable> Encodable for [T] {
1a4d82fc
JJ
657 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
658 s.emit_seq(self.len(), |s| {
659 for (i, e) in self.iter().enumerate() {
54a0048b 660 s.emit_seq_elt(i, |s| e.encode(s))?
1a4d82fc
JJ
661 }
662 Ok(())
663 })
664 }
665}
666
dfeec247 667impl<T: Encodable> Encodable for Vec<T> {
1a4d82fc
JJ
668 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
669 s.emit_seq(self.len(), |s| {
670 for (i, e) in self.iter().enumerate() {
54a0048b 671 s.emit_seq_elt(i, |s| e.encode(s))?
1a4d82fc
JJ
672 }
673 Ok(())
674 })
675 }
676}
677
dfeec247 678impl<T: Decodable> Decodable for Vec<T> {
1a4d82fc
JJ
679 fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
680 d.read_seq(|d, len| {
681 let mut v = Vec::with_capacity(len);
85aaf69f 682 for i in 0..len {
54a0048b 683 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
1a4d82fc
JJ
684 }
685 Ok(v)
686 })
687 }
688}
689
dfeec247
XL
690impl<'a, T: Encodable> Encodable for Cow<'a, [T]>
691where
692 [T]: ToOwned<Owned = Vec<T>>,
693{
8bb4bdeb
XL
694 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
695 s.emit_seq(self.len(), |s| {
696 for (i, e) in self.iter().enumerate() {
697 s.emit_seq_elt(i, |s| e.encode(s))?
698 }
699 Ok(())
700 })
701 }
702}
703
dfeec247
XL
704impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]>
705where
706 [T]: ToOwned<Owned = Vec<T>>,
8bb4bdeb
XL
707{
708 fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
709 d.read_seq(|d, len| {
710 let mut v = Vec::with_capacity(len);
711 for i in 0..len {
712 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
713 }
714 Ok(Cow::Owned(v))
715 })
716 }
717}
718
dfeec247 719impl<T: Encodable> Encodable for Option<T> {
1a4d82fc 720 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
dfeec247
XL
721 s.emit_option(|s| match *self {
722 None => s.emit_option_none(),
723 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
1a4d82fc
JJ
724 })
725 }
726}
727
dfeec247 728impl<T: Decodable> Decodable for Option<T> {
1a4d82fc 729 fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
dfeec247 730 d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
ff7c6d11
XL
731 }
732}
733
734impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
735 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
dfeec247
XL
736 s.emit_enum("Result", |s| match *self {
737 Ok(ref v) => {
738 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
739 }
740 Err(ref v) => {
741 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
ff7c6d11
XL
742 }
743 })
744 }
745}
746
dfeec247 747impl<T1: Decodable, T2: Decodable> Decodable for Result<T1, T2> {
ff7c6d11
XL
748 fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
749 d.read_enum("Result", |d| {
dfeec247
XL
750 d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
751 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)),
752 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)),
753 _ => {
754 panic!(
755 "Encountered invalid discriminant while \
756 decoding `Result`."
757 );
ff7c6d11
XL
758 }
759 })
760 })
1a4d82fc
JJ
761 }
762}
763
764macro_rules! peel {
765 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
766}
767
dc9dc135
XL
768/// Evaluates to the number of tokens passed to it.
769///
770/// Logarithmic counting: every one or two recursive expansions, the number of
771/// tokens to count is divided by two, instead of being reduced by one.
772/// Therefore, the recursion depth is the binary logarithm of the number of
773/// tokens to count, and the expanded tree is likewise very small.
774macro_rules! count {
775 () => (0usize);
776 ($one:tt) => (1usize);
777 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
778 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
1a4d82fc
JJ
779}
780
781macro_rules! tuple {
782 () => ();
783 ( $($name:ident,)+ ) => (
dc9dc135 784 impl<$($name:Decodable),+> Decodable for ($($name,)+) {
1a4d82fc 785 #[allow(non_snake_case)]
dc9dc135
XL
786 fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)+), D::Error> {
787 let len: usize = count!($($name)+);
1a4d82fc
JJ
788 d.read_tuple(len, |d| {
789 let mut i = 0;
b7449926 790 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
1a4d82fc 791 Decodable::decode(d)
dc9dc135 792 })?,)+);
e9174d1e 793 Ok(ret)
1a4d82fc
JJ
794 })
795 }
796 }
dc9dc135 797 impl<$($name:Encodable),+> Encodable for ($($name,)+) {
1a4d82fc
JJ
798 #[allow(non_snake_case)]
799 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
dc9dc135 800 let ($(ref $name,)+) = *self;
1a4d82fc 801 let mut n = 0;
dc9dc135 802 $(let $name = $name; n += 1;)+
1a4d82fc
JJ
803 s.emit_tuple(n, |s| {
804 let mut i = 0;
dc9dc135 805 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
1a4d82fc
JJ
806 Ok(())
807 })
808 }
809 }
dc9dc135 810 peel! { $($name,)+ }
1a4d82fc
JJ
811 )
812}
813
814tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
815
48663c56 816impl Encodable for path::Path {
c34b1796
AL
817 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
818 self.to_str().unwrap().encode(e)
819 }
820}
821
48663c56
XL
822impl Encodable for path::PathBuf {
823 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
824 path::Path::encode(self, e)
825 }
826}
827
c34b1796
AL
828impl Decodable for path::PathBuf {
829 fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
54a0048b 830 let bytes: String = Decodable::decode(d)?;
c34b1796
AL
831 Ok(path::PathBuf::from(bytes))
832 }
833}
834
1a4d82fc
JJ
835impl<T: Encodable + Copy> Encodable for Cell<T> {
836 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
837 self.get().encode(s)
838 }
839}
840
841impl<T: Decodable + Copy> Decodable for Cell<T> {
842 fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
54a0048b 843 Ok(Cell::new(Decodable::decode(d)?))
1a4d82fc
JJ
844 }
845}
846
847// FIXME: #15036
848// Should use `try_borrow`, returning a
849// `encoder.error("attempting to Encode borrowed RefCell")`
850// from `encode` when `try_borrow` returns `None`.
851
852impl<T: Encodable> Encodable for RefCell<T> {
853 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
854 self.borrow().encode(s)
855 }
856}
857
858impl<T: Decodable> Decodable for RefCell<T> {
859 fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
54a0048b 860 Ok(RefCell::new(Decodable::decode(d)?))
1a4d82fc
JJ
861 }
862}
863
dfeec247 864impl<T: Encodable> Encodable for Arc<T> {
1a4d82fc
JJ
865 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
866 (**self).encode(s)
867 }
868}
869
dfeec247 870impl<T: Decodable> Decodable for Arc<T> {
1a4d82fc 871 fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
54a0048b 872 Ok(Arc::new(Decodable::decode(d)?))
1a4d82fc
JJ
873 }
874}
875
876// ___________________________________________________________________________
9e0c209e 877// Specialization-based interface for multi-dispatch Encodable/Decodable.
1a4d82fc 878
9e0c209e
SL
879/// Implement this trait on your `{Encodable,Decodable}::Error` types
880/// to override the default panic behavior for missing specializations.
881pub trait SpecializationError {
9fa01778 882 /// Creates an error for a missing method specialization.
9e0c209e
SL
883 /// Defaults to panicking with type, trait & method names.
884 /// `S` is the encoder/decoder state type,
885 /// `T` is the type being encoded/decoded, and
886 /// the arguments are the names of the trait
3b2f2976 887 /// and method that should've been overridden.
b7449926 888 fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
1a4d82fc
JJ
889}
890
9e0c209e 891impl<E> SpecializationError for E {
b7449926 892 default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
dfeec247
XL
893 panic!(
894 "missing specialization: `<{} as {}<{}>>::{}` not overridden",
895 any::type_name::<S>(),
896 trait_name,
897 any::type_name::<T>(),
898 method_name
899 );
1a4d82fc
JJ
900 }
901}
902
9e0c209e
SL
903/// Implement this trait on encoders, with `T` being the type
904/// you want to encode (employing `UseSpecializedEncodable`),
905/// using a strategy specific to the encoder.
906pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
907 /// Encode the value in a manner specific to this encoder state.
908 fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
1a4d82fc
JJ
909}
910
9e0c209e
SL
911impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
912 default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
913 value.default_encode(self)
914 }
915}
916
917/// Implement this trait on decoders, with `T` being the type
918/// you want to decode (employing `UseSpecializedDecodable`),
919/// using a strategy specific to the decoder.
920pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
921 /// Decode a value in a manner specific to this decoder state.
922 fn specialized_decode(&mut self) -> Result<T, Self::Error>;
923}
924
925impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
926 default fn specialized_decode(&mut self) -> Result<T, D::Error> {
927 T::default_decode(self)
928 }
929}
930
931/// Implement this trait on your type to get an `Encodable`
932/// implementation which goes through `SpecializedEncoder`.
933pub trait UseSpecializedEncodable {
934 /// Defaults to returning an error (see `SpecializationError`).
935 fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
936 Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
937 }
938}
939
940impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
941 default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
942 E::specialized_encode(e, self)
943 }
944}
945
946/// Implement this trait on your type to get an `Decodable`
947/// implementation which goes through `SpecializedDecoder`.
948pub trait UseSpecializedDecodable: Sized {
949 /// Defaults to returning an error (see `SpecializationError`).
950 fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
951 Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
1a4d82fc
JJ
952 }
953}
9e0c209e
SL
954
955impl<T: UseSpecializedDecodable> Decodable for T {
956 default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
957 D::specialized_decode(d)
958 }
959}
960
961// Can't avoid specialization for &T and Box<T> impls,
962// as proxy impls on them are blankets that conflict
963// with the Encodable and Decodable impls above,
964// which only have `default` on their methods
965// for this exact reason.
966// May be fixable in a simpler fashion via the
967// more complex lattice model for specialization.
968impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {}
969impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {}
970impl<T: Decodable> UseSpecializedDecodable for Box<T> {}
48663c56
XL
971impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {}
972impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}