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