]> git.proxmox.com Git - rustc.git/blob - src/libserialize/serialize.rs
New upstream version 1.16.0+dfsg1
[rustc.git] / src / libserialize / serialize.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Support code for encoding and decoding types.
12
13 /*
14 Core encoding and decoding interfaces.
15 */
16
17 use std::borrow::Cow;
18 use std::intrinsics;
19 use std::path;
20 use std::rc::Rc;
21 use std::cell::{Cell, RefCell};
22 use std::sync::Arc;
23 use rustc_i128::{i128, u128};
24
25 pub trait Encoder {
26 type Error;
27
28 // Primitive types:
29 fn emit_nil(&mut self) -> Result<(), Self::Error>;
30 fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
31 fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
32 fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
33 fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
34 fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
35 fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
36 fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
37 fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
38 fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
39 fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
40 fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
41 fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
42 fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
43 fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
44 fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
45 fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
46 fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
47
48 // Compound types:
49 fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
50 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
51
52 fn emit_enum_variant<F>(&mut self, _v_name: &str,
53 v_id: usize,
54 _len: usize,
55 f: F) -> Result<(), Self::Error>
56 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
57 {
58 self.emit_usize(v_id)?;
59 f(self)
60 }
61 fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F)
62 -> Result<(), Self::Error>
63 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
64
65 fn emit_enum_struct_variant<F>(&mut self, v_name: &str,
66 v_id: usize,
67 len: usize,
68 f: F) -> Result<(), Self::Error>
69 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
70 {
71 self.emit_enum_variant(v_name, v_id, len, f)
72 }
73 fn emit_enum_struct_variant_field<F>(&mut self,
74 _f_name: &str,
75 f_idx: usize,
76 f: F) -> Result<(), Self::Error>
77 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
78 {
79 self.emit_enum_variant_arg(f_idx, f)
80 }
81
82 fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F)
83 -> Result<(), Self::Error>
84 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
85 fn emit_struct_field<F>(&mut self, _f_name: &str, _f_idx: usize, f: F)
86 -> Result<(), Self::Error>
87 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
88
89 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
90 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
91 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
92 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
93
94 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F)
95 -> Result<(), Self::Error>
96 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
97 {
98 self.emit_tuple(len, f)
99 }
100 fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F)
101 -> Result<(), Self::Error>
102 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
103 {
104 self.emit_tuple_arg(f_idx, f)
105 }
106
107 // Specialized types:
108 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
109 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
110 {
111 self.emit_enum("Option", f)
112 }
113 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
114 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
115 }
116 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
117 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
118 {
119
120 self.emit_enum_variant("Some", 1, 1, f)
121 }
122
123 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
124 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
125 {
126 self.emit_usize(len)?;
127 f(self)
128 }
129 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
130 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
131
132 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
133 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
134 {
135 self.emit_usize(len)?;
136 f(self)
137 }
138 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
139 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
140 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
141 where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
142 }
143
144 pub trait Decoder {
145 type Error;
146
147 // Primitive types:
148 fn read_nil(&mut self) -> Result<(), Self::Error>;
149 fn read_usize(&mut self) -> Result<usize, Self::Error>;
150 fn read_u128(&mut self) -> Result<u128, Self::Error>;
151 fn read_u64(&mut self) -> Result<u64, Self::Error>;
152 fn read_u32(&mut self) -> Result<u32, Self::Error>;
153 fn read_u16(&mut self) -> Result<u16, Self::Error>;
154 fn read_u8(&mut self) -> Result<u8, Self::Error>;
155 fn read_isize(&mut self) -> Result<isize, Self::Error>;
156 fn read_i128(&mut self) -> Result<i128, Self::Error>;
157 fn read_i64(&mut self) -> Result<i64, Self::Error>;
158 fn read_i32(&mut self) -> Result<i32, Self::Error>;
159 fn read_i16(&mut self) -> Result<i16, Self::Error>;
160 fn read_i8(&mut self) -> Result<i8, Self::Error>;
161 fn read_bool(&mut self) -> Result<bool, Self::Error>;
162 fn read_f64(&mut self) -> Result<f64, Self::Error>;
163 fn read_f32(&mut self) -> Result<f32, Self::Error>;
164 fn read_char(&mut self) -> Result<char, Self::Error>;
165 fn read_str(&mut self) -> Result<Cow<str>, Self::Error>;
166
167 // Compound types:
168 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
169 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
170
171 fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F)
172 -> Result<T, Self::Error>
173 where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
174 {
175 let disr = self.read_usize()?;
176 f(self, disr)
177 }
178 fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F)
179 -> Result<T, Self::Error>
180 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
181
182 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F)
183 -> Result<T, Self::Error>
184 where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
185 {
186 self.read_enum_variant(names, f)
187 }
188 fn read_enum_struct_variant_field<T, F>(&mut self,
189 _f_name: &str,
190 f_idx: usize,
191 f: F)
192 -> Result<T, Self::Error>
193 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
194 {
195 self.read_enum_variant_arg(f_idx, f)
196 }
197
198 fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F)
199 -> Result<T, Self::Error>
200 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
201 fn read_struct_field<T, F>(&mut self,
202 _f_name: &str,
203 _f_idx: usize,
204 f: F)
205 -> Result<T, Self::Error>
206 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
207
208 fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
209 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
210 fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F)
211 -> Result<T, Self::Error>
212 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
213
214 fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F)
215 -> Result<T, Self::Error>
216 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
217 {
218 self.read_tuple(len, f)
219 }
220 fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F)
221 -> Result<T, Self::Error>
222 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
223 {
224 self.read_tuple_arg(a_idx, f)
225 }
226
227 // Specialized types:
228 fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
229 where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>
230 {
231 self.read_enum("Option", move |this| {
232 this.read_enum_variant(&["None", "Some"], move |this, idx| {
233 match idx {
234 0 => f(this, false),
235 1 => f(this, true),
236 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
237 }
238 })
239 })
240 }
241
242 fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
243 where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
244 {
245 let len = self.read_usize()?;
246 f(self, len)
247 }
248 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
249 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
250
251 fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
252 where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
253 {
254 let len = self.read_usize()?;
255 f(self, len)
256 }
257 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F)
258 -> Result<T, Self::Error>
259 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
260 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F)
261 -> Result<T, Self::Error>
262 where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
263
264 // Failure
265 fn error(&mut self, err: &str) -> Self::Error;
266 }
267
268 pub trait Encodable {
269 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
270 }
271
272 pub trait Decodable: Sized {
273 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
274 }
275
276 impl Encodable for usize {
277 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
278 s.emit_usize(*self)
279 }
280 }
281
282 impl Decodable for usize {
283 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
284 d.read_usize()
285 }
286 }
287
288 impl Encodable for u8 {
289 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
290 s.emit_u8(*self)
291 }
292 }
293
294 impl Decodable for u8 {
295 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
296 d.read_u8()
297 }
298 }
299
300 impl Encodable for u16 {
301 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
302 s.emit_u16(*self)
303 }
304 }
305
306 impl Decodable for u16 {
307 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
308 d.read_u16()
309 }
310 }
311
312 impl Encodable for u32 {
313 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
314 s.emit_u32(*self)
315 }
316 }
317
318 impl Decodable for u32 {
319 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
320 d.read_u32()
321 }
322 }
323
324 impl Encodable for u64 {
325 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
326 s.emit_u64(*self)
327 }
328 }
329
330 impl Decodable for u64 {
331 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
332 d.read_u64()
333 }
334 }
335
336 #[cfg(not(stage0))]
337 impl Encodable for u128 {
338 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
339 s.emit_u128(*self)
340 }
341 }
342
343 #[cfg(not(stage0))]
344 impl Decodable for u128 {
345 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
346 d.read_u128()
347 }
348 }
349
350 impl Encodable for isize {
351 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
352 s.emit_isize(*self)
353 }
354 }
355
356 impl Decodable for isize {
357 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
358 d.read_isize()
359 }
360 }
361
362 impl Encodable for i8 {
363 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
364 s.emit_i8(*self)
365 }
366 }
367
368 impl Decodable for i8 {
369 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
370 d.read_i8()
371 }
372 }
373
374 impl Encodable for i16 {
375 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
376 s.emit_i16(*self)
377 }
378 }
379
380 impl Decodable for i16 {
381 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
382 d.read_i16()
383 }
384 }
385
386 impl Encodable for i32 {
387 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
388 s.emit_i32(*self)
389 }
390 }
391
392 impl Decodable for i32 {
393 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
394 d.read_i32()
395 }
396 }
397
398 impl Encodable for i64 {
399 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
400 s.emit_i64(*self)
401 }
402 }
403
404 impl Decodable for i64 {
405 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
406 d.read_i64()
407 }
408 }
409
410 #[cfg(not(stage0))]
411 impl Encodable for i128 {
412 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
413 s.emit_i128(*self)
414 }
415 }
416
417 #[cfg(not(stage0))]
418 impl Decodable for i128 {
419 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
420 d.read_i128()
421 }
422 }
423
424 impl Encodable for str {
425 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
426 s.emit_str(self)
427 }
428 }
429
430 impl Encodable for String {
431 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
432 s.emit_str(&self[..])
433 }
434 }
435
436 impl Decodable for String {
437 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
438 Ok(d.read_str()?.into_owned())
439 }
440 }
441
442 impl Encodable for f32 {
443 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
444 s.emit_f32(*self)
445 }
446 }
447
448 impl Decodable for f32 {
449 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
450 d.read_f32()
451 }
452 }
453
454 impl Encodable for f64 {
455 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
456 s.emit_f64(*self)
457 }
458 }
459
460 impl Decodable for f64 {
461 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
462 d.read_f64()
463 }
464 }
465
466 impl Encodable for bool {
467 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
468 s.emit_bool(*self)
469 }
470 }
471
472 impl Decodable for bool {
473 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
474 d.read_bool()
475 }
476 }
477
478 impl Encodable for char {
479 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
480 s.emit_char(*self)
481 }
482 }
483
484 impl Decodable for char {
485 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
486 d.read_char()
487 }
488 }
489
490 impl Encodable for () {
491 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
492 s.emit_nil()
493 }
494 }
495
496 impl Decodable for () {
497 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
498 d.read_nil()
499 }
500 }
501
502 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
503 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
504 (**self).encode(s)
505 }
506 }
507
508 impl<T: ?Sized + Encodable> Encodable for Box<T> {
509 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
510 (**self).encode(s)
511 }
512 }
513
514 impl< T: Decodable> Decodable for Box<T> {
515 fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
516 Ok(box Decodable::decode(d)?)
517 }
518 }
519
520 impl< T: Decodable> Decodable for Box<[T]> {
521 fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
522 let v: Vec<T> = Decodable::decode(d)?;
523 Ok(v.into_boxed_slice())
524 }
525 }
526
527 impl<T:Encodable> Encodable for Rc<T> {
528 #[inline]
529 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
530 (**self).encode(s)
531 }
532 }
533
534 impl<T:Decodable> Decodable for Rc<T> {
535 #[inline]
536 fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
537 Ok(Rc::new(Decodable::decode(d)?))
538 }
539 }
540
541 impl<T:Encodable> Encodable for [T] {
542 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
543 s.emit_seq(self.len(), |s| {
544 for (i, e) in self.iter().enumerate() {
545 s.emit_seq_elt(i, |s| e.encode(s))?
546 }
547 Ok(())
548 })
549 }
550 }
551
552 impl<T:Encodable> Encodable for Vec<T> {
553 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
554 s.emit_seq(self.len(), |s| {
555 for (i, e) in self.iter().enumerate() {
556 s.emit_seq_elt(i, |s| e.encode(s))?
557 }
558 Ok(())
559 })
560 }
561 }
562
563 impl<T:Decodable> Decodable for Vec<T> {
564 fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
565 d.read_seq(|d, len| {
566 let mut v = Vec::with_capacity(len);
567 for i in 0..len {
568 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
569 }
570 Ok(v)
571 })
572 }
573 }
574
575 impl<T:Encodable> Encodable for Option<T> {
576 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
577 s.emit_option(|s| {
578 match *self {
579 None => s.emit_option_none(),
580 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
581 }
582 })
583 }
584 }
585
586 impl<T:Decodable> Decodable for Option<T> {
587 fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
588 d.read_option(|d, b| {
589 if b {
590 Ok(Some(Decodable::decode(d)?))
591 } else {
592 Ok(None)
593 }
594 })
595 }
596 }
597
598 macro_rules! peel {
599 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
600 }
601
602 /// Evaluates to the number of identifiers passed to it, for example: `count_idents!(a, b, c) == 3
603 macro_rules! count_idents {
604 () => { 0 };
605 ($_i:ident, $($rest:ident,)*) => { 1 + count_idents!($($rest,)*) }
606 }
607
608 macro_rules! tuple {
609 () => ();
610 ( $($name:ident,)+ ) => (
611 impl<$($name:Decodable),*> Decodable for ($($name,)*) {
612 #[allow(non_snake_case)]
613 fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)*), D::Error> {
614 let len: usize = count_idents!($($name,)*);
615 d.read_tuple(len, |d| {
616 let mut i = 0;
617 let ret = ($(d.read_tuple_arg({ i+=1; i-1 },
618 |d| -> Result<$name,D::Error> {
619 Decodable::decode(d)
620 })?,)*);
621 Ok(ret)
622 })
623 }
624 }
625 impl<$($name:Encodable),*> Encodable for ($($name,)*) {
626 #[allow(non_snake_case)]
627 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
628 let ($(ref $name,)*) = *self;
629 let mut n = 0;
630 $(let $name = $name; n += 1;)*
631 s.emit_tuple(n, |s| {
632 let mut i = 0;
633 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)*
634 Ok(())
635 })
636 }
637 }
638 peel! { $($name,)* }
639 )
640 }
641
642 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
643
644 impl Encodable for path::PathBuf {
645 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
646 self.to_str().unwrap().encode(e)
647 }
648 }
649
650 impl Decodable for path::PathBuf {
651 fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
652 let bytes: String = Decodable::decode(d)?;
653 Ok(path::PathBuf::from(bytes))
654 }
655 }
656
657 impl<T: Encodable + Copy> Encodable for Cell<T> {
658 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
659 self.get().encode(s)
660 }
661 }
662
663 impl<T: Decodable + Copy> Decodable for Cell<T> {
664 fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
665 Ok(Cell::new(Decodable::decode(d)?))
666 }
667 }
668
669 // FIXME: #15036
670 // Should use `try_borrow`, returning a
671 // `encoder.error("attempting to Encode borrowed RefCell")`
672 // from `encode` when `try_borrow` returns `None`.
673
674 impl<T: Encodable> Encodable for RefCell<T> {
675 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
676 self.borrow().encode(s)
677 }
678 }
679
680 impl<T: Decodable> Decodable for RefCell<T> {
681 fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
682 Ok(RefCell::new(Decodable::decode(d)?))
683 }
684 }
685
686 impl<T:Encodable> Encodable for Arc<T> {
687 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
688 (**self).encode(s)
689 }
690 }
691
692 impl<T:Decodable+Send+Sync> Decodable for Arc<T> {
693 fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
694 Ok(Arc::new(Decodable::decode(d)?))
695 }
696 }
697
698 // ___________________________________________________________________________
699 // Specialization-based interface for multi-dispatch Encodable/Decodable.
700
701 /// Implement this trait on your `{Encodable,Decodable}::Error` types
702 /// to override the default panic behavior for missing specializations.
703 pub trait SpecializationError {
704 /// Create an error for a missing method specialization.
705 /// Defaults to panicking with type, trait & method names.
706 /// `S` is the encoder/decoder state type,
707 /// `T` is the type being encoded/decoded, and
708 /// the arguments are the names of the trait
709 /// and method that should've been overriden.
710 fn not_found<S, T: ?Sized>(trait_name: &'static str,
711 method_name: &'static str) -> Self;
712 }
713
714 impl<E> SpecializationError for E {
715 default fn not_found<S, T: ?Sized>(trait_name: &'static str,
716 method_name: &'static str) -> E {
717 panic!("missing specializaiton: `<{} as {}<{}>>::{}` not overriden",
718 unsafe { intrinsics::type_name::<S>() },
719 trait_name,
720 unsafe { intrinsics::type_name::<T>() },
721 method_name);
722 }
723 }
724
725 /// Implement this trait on encoders, with `T` being the type
726 /// you want to encode (employing `UseSpecializedEncodable`),
727 /// using a strategy specific to the encoder.
728 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
729 /// Encode the value in a manner specific to this encoder state.
730 fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
731 }
732
733 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
734 default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
735 value.default_encode(self)
736 }
737 }
738
739 /// Implement this trait on decoders, with `T` being the type
740 /// you want to decode (employing `UseSpecializedDecodable`),
741 /// using a strategy specific to the decoder.
742 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
743 /// Decode a value in a manner specific to this decoder state.
744 fn specialized_decode(&mut self) -> Result<T, Self::Error>;
745 }
746
747 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
748 default fn specialized_decode(&mut self) -> Result<T, D::Error> {
749 T::default_decode(self)
750 }
751 }
752
753 /// Implement this trait on your type to get an `Encodable`
754 /// implementation which goes through `SpecializedEncoder`.
755 pub trait UseSpecializedEncodable {
756 /// Defaults to returning an error (see `SpecializationError`).
757 fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
758 Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
759 }
760 }
761
762 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
763 default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
764 E::specialized_encode(e, self)
765 }
766 }
767
768 /// Implement this trait on your type to get an `Decodable`
769 /// implementation which goes through `SpecializedDecoder`.
770 pub trait UseSpecializedDecodable: Sized {
771 /// Defaults to returning an error (see `SpecializationError`).
772 fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
773 Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
774 }
775 }
776
777 impl<T: UseSpecializedDecodable> Decodable for T {
778 default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
779 D::specialized_decode(d)
780 }
781 }
782
783 // Can't avoid specialization for &T and Box<T> impls,
784 // as proxy impls on them are blankets that conflict
785 // with the Encodable and Decodable impls above,
786 // which only have `default` on their methods
787 // for this exact reason.
788 // May be fixable in a simpler fashion via the
789 // more complex lattice model for specialization.
790 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {}
791 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {}
792 impl<T: Decodable> UseSpecializedDecodable for Box<T> {}