]> git.lizzy.rs Git - rust.git/blob - src/libserialize/serialize.rs
auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw
[rust.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::path;
18 use std::rc::Rc;
19 use std::slice;
20
21 pub trait Encoder {
22     // Primitive types:
23     fn emit_nil(&mut self);
24     fn emit_uint(&mut self, v: uint);
25     fn emit_u64(&mut self, v: u64);
26     fn emit_u32(&mut self, v: u32);
27     fn emit_u16(&mut self, v: u16);
28     fn emit_u8(&mut self, v: u8);
29     fn emit_int(&mut self, v: int);
30     fn emit_i64(&mut self, v: i64);
31     fn emit_i32(&mut self, v: i32);
32     fn emit_i16(&mut self, v: i16);
33     fn emit_i8(&mut self, v: i8);
34     fn emit_bool(&mut self, v: bool);
35     fn emit_f64(&mut self, v: f64);
36     fn emit_f32(&mut self, v: f32);
37     fn emit_char(&mut self, v: char);
38     fn emit_str(&mut self, v: &str);
39
40     // Compound types:
41     fn emit_enum(&mut self, name: &str, f: |&mut Self|);
42
43     fn emit_enum_variant(&mut self,
44                          v_name: &str,
45                          v_id: uint,
46                          len: uint,
47                          f: |&mut Self|);
48     fn emit_enum_variant_arg(&mut self, a_idx: uint, f: |&mut Self|);
49
50     fn emit_enum_struct_variant(&mut self,
51                                 v_name: &str,
52                                 v_id: uint,
53                                 len: uint,
54                                 f: |&mut Self|);
55     fn emit_enum_struct_variant_field(&mut self,
56                                       f_name: &str,
57                                       f_idx: uint,
58                                       f: |&mut Self|);
59
60     fn emit_struct(&mut self, name: &str, len: uint, f: |&mut Self|);
61     fn emit_struct_field(&mut self,
62                          f_name: &str,
63                          f_idx: uint,
64                          f: |&mut Self|);
65
66     fn emit_tuple(&mut self, len: uint, f: |&mut Self|);
67     fn emit_tuple_arg(&mut self, idx: uint, f: |&mut Self|);
68
69     fn emit_tuple_struct(&mut self, name: &str, len: uint, f: |&mut Self|);
70     fn emit_tuple_struct_arg(&mut self, f_idx: uint, f: |&mut Self|);
71
72     // Specialized types:
73     fn emit_option(&mut self, f: |&mut Self|);
74     fn emit_option_none(&mut self);
75     fn emit_option_some(&mut self, f: |&mut Self|);
76
77     fn emit_seq(&mut self, len: uint, f: |this: &mut Self|);
78     fn emit_seq_elt(&mut self, idx: uint, f: |this: &mut Self|);
79
80     fn emit_map(&mut self, len: uint, f: |&mut Self|);
81     fn emit_map_elt_key(&mut self, idx: uint, f: |&mut Self|);
82     fn emit_map_elt_val(&mut self, idx: uint, f: |&mut Self|);
83 }
84
85 pub trait Decoder {
86     // Primitive types:
87     fn read_nil(&mut self) -> ();
88     fn read_uint(&mut self) -> uint;
89     fn read_u64(&mut self) -> u64;
90     fn read_u32(&mut self) -> u32;
91     fn read_u16(&mut self) -> u16;
92     fn read_u8(&mut self) -> u8;
93     fn read_int(&mut self) -> int;
94     fn read_i64(&mut self) -> i64;
95     fn read_i32(&mut self) -> i32;
96     fn read_i16(&mut self) -> i16;
97     fn read_i8(&mut self) -> i8;
98     fn read_bool(&mut self) -> bool;
99     fn read_f64(&mut self) -> f64;
100     fn read_f32(&mut self) -> f32;
101     fn read_char(&mut self) -> char;
102     fn read_str(&mut self) -> ~str;
103
104     // Compound types:
105     fn read_enum<T>(&mut self, name: &str, f: |&mut Self| -> T) -> T;
106
107     fn read_enum_variant<T>(&mut self,
108                             names: &[&str],
109                             f: |&mut Self, uint| -> T)
110                             -> T;
111     fn read_enum_variant_arg<T>(&mut self,
112                                 a_idx: uint,
113                                 f: |&mut Self| -> T)
114                                 -> T;
115
116     fn read_enum_struct_variant<T>(&mut self,
117                                    names: &[&str],
118                                    f: |&mut Self, uint| -> T)
119                                    -> T;
120     fn read_enum_struct_variant_field<T>(&mut self,
121                                          &f_name: &str,
122                                          f_idx: uint,
123                                          f: |&mut Self| -> T)
124                                          -> T;
125
126     fn read_struct<T>(&mut self, s_name: &str, len: uint, f: |&mut Self| -> T)
127                       -> T;
128     fn read_struct_field<T>(&mut self,
129                             f_name: &str,
130                             f_idx: uint,
131                             f: |&mut Self| -> T)
132                             -> T;
133
134     fn read_tuple<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
135     fn read_tuple_arg<T>(&mut self, a_idx: uint, f: |&mut Self| -> T) -> T;
136
137     fn read_tuple_struct<T>(&mut self,
138                             s_name: &str,
139                             f: |&mut Self, uint| -> T)
140                             -> T;
141     fn read_tuple_struct_arg<T>(&mut self,
142                                 a_idx: uint,
143                                 f: |&mut Self| -> T)
144                                 -> T;
145
146     // Specialized types:
147     fn read_option<T>(&mut self, f: |&mut Self, bool| -> T) -> T;
148
149     fn read_seq<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
150     fn read_seq_elt<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
151
152     fn read_map<T>(&mut self, f: |&mut Self, uint| -> T) -> T;
153     fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
154     fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Self| -> T) -> T;
155 }
156
157 pub trait Encodable<S:Encoder> {
158     fn encode(&self, s: &mut S);
159 }
160
161 pub trait Decodable<D:Decoder> {
162     fn decode(d: &mut D) -> Self;
163 }
164
165 impl<S:Encoder> Encodable<S> for uint {
166     fn encode(&self, s: &mut S) {
167         s.emit_uint(*self)
168     }
169 }
170
171 impl<D:Decoder> Decodable<D> for uint {
172     fn decode(d: &mut D) -> uint {
173         d.read_uint()
174     }
175 }
176
177 impl<S:Encoder> Encodable<S> for u8 {
178     fn encode(&self, s: &mut S) {
179         s.emit_u8(*self)
180     }
181 }
182
183 impl<D:Decoder> Decodable<D> for u8 {
184     fn decode(d: &mut D) -> u8 {
185         d.read_u8()
186     }
187 }
188
189 impl<S:Encoder> Encodable<S> for u16 {
190     fn encode(&self, s: &mut S) {
191         s.emit_u16(*self)
192     }
193 }
194
195 impl<D:Decoder> Decodable<D> for u16 {
196     fn decode(d: &mut D) -> u16 {
197         d.read_u16()
198     }
199 }
200
201 impl<S:Encoder> Encodable<S> for u32 {
202     fn encode(&self, s: &mut S) {
203         s.emit_u32(*self)
204     }
205 }
206
207 impl<D:Decoder> Decodable<D> for u32 {
208     fn decode(d: &mut D) -> u32 {
209         d.read_u32()
210     }
211 }
212
213 impl<S:Encoder> Encodable<S> for u64 {
214     fn encode(&self, s: &mut S) {
215         s.emit_u64(*self)
216     }
217 }
218
219 impl<D:Decoder> Decodable<D> for u64 {
220     fn decode(d: &mut D) -> u64 {
221         d.read_u64()
222     }
223 }
224
225 impl<S:Encoder> Encodable<S> for int {
226     fn encode(&self, s: &mut S) {
227         s.emit_int(*self)
228     }
229 }
230
231 impl<D:Decoder> Decodable<D> for int {
232     fn decode(d: &mut D) -> int {
233         d.read_int()
234     }
235 }
236
237 impl<S:Encoder> Encodable<S> for i8 {
238     fn encode(&self, s: &mut S) {
239         s.emit_i8(*self)
240     }
241 }
242
243 impl<D:Decoder> Decodable<D> for i8 {
244     fn decode(d: &mut D) -> i8 {
245         d.read_i8()
246     }
247 }
248
249 impl<S:Encoder> Encodable<S> for i16 {
250     fn encode(&self, s: &mut S) {
251         s.emit_i16(*self)
252     }
253 }
254
255 impl<D:Decoder> Decodable<D> for i16 {
256     fn decode(d: &mut D) -> i16 {
257         d.read_i16()
258     }
259 }
260
261 impl<S:Encoder> Encodable<S> for i32 {
262     fn encode(&self, s: &mut S) {
263         s.emit_i32(*self)
264     }
265 }
266
267 impl<D:Decoder> Decodable<D> for i32 {
268     fn decode(d: &mut D) -> i32 {
269         d.read_i32()
270     }
271 }
272
273 impl<S:Encoder> Encodable<S> for i64 {
274     fn encode(&self, s: &mut S) {
275         s.emit_i64(*self)
276     }
277 }
278
279 impl<D:Decoder> Decodable<D> for i64 {
280     fn decode(d: &mut D) -> i64 {
281         d.read_i64()
282     }
283 }
284
285 impl<'a, S:Encoder> Encodable<S> for &'a str {
286     fn encode(&self, s: &mut S) {
287         s.emit_str(*self)
288     }
289 }
290
291 impl<S:Encoder> Encodable<S> for ~str {
292     fn encode(&self, s: &mut S) {
293         s.emit_str(*self)
294     }
295 }
296
297 impl<D:Decoder> Decodable<D> for ~str {
298     fn decode(d: &mut D) -> ~str {
299         d.read_str()
300     }
301 }
302
303 impl<S:Encoder> Encodable<S> for f32 {
304     fn encode(&self, s: &mut S) {
305         s.emit_f32(*self)
306     }
307 }
308
309 impl<D:Decoder> Decodable<D> for f32 {
310     fn decode(d: &mut D) -> f32 {
311         d.read_f32()
312     }
313 }
314
315 impl<S:Encoder> Encodable<S> for f64 {
316     fn encode(&self, s: &mut S) {
317         s.emit_f64(*self)
318     }
319 }
320
321 impl<D:Decoder> Decodable<D> for f64 {
322     fn decode(d: &mut D) -> f64 {
323         d.read_f64()
324     }
325 }
326
327 impl<S:Encoder> Encodable<S> for bool {
328     fn encode(&self, s: &mut S) {
329         s.emit_bool(*self)
330     }
331 }
332
333 impl<D:Decoder> Decodable<D> for bool {
334     fn decode(d: &mut D) -> bool {
335         d.read_bool()
336     }
337 }
338
339 impl<S:Encoder> Encodable<S> for char {
340     fn encode(&self, s: &mut S) {
341         s.emit_char(*self)
342     }
343 }
344
345 impl<D:Decoder> Decodable<D> for char {
346     fn decode(d: &mut D) -> char {
347         d.read_char()
348     }
349 }
350
351 impl<S:Encoder> Encodable<S> for () {
352     fn encode(&self, s: &mut S) {
353         s.emit_nil()
354     }
355 }
356
357 impl<D:Decoder> Decodable<D> for () {
358     fn decode(d: &mut D) -> () {
359         d.read_nil()
360     }
361 }
362
363 impl<'a, S:Encoder,T:Encodable<S>> Encodable<S> for &'a T {
364     fn encode(&self, s: &mut S) {
365         (**self).encode(s)
366     }
367 }
368
369 impl<S:Encoder,T:Encodable<S>> Encodable<S> for ~T {
370     fn encode(&self, s: &mut S) {
371         (**self).encode(s)
372     }
373 }
374
375 impl<D:Decoder,T:Decodable<D>> Decodable<D> for ~T {
376     fn decode(d: &mut D) -> ~T {
377         ~Decodable::decode(d)
378     }
379 }
380
381 impl<S:Encoder,T:Encodable<S>> Encodable<S> for @T {
382     fn encode(&self, s: &mut S) {
383         (**self).encode(s)
384     }
385 }
386
387 impl<S:Encoder,T:Encodable<S>> Encodable<S> for Rc<T> {
388     #[inline]
389     fn encode(&self, s: &mut S) {
390         (**self).encode(s)
391     }
392 }
393
394 impl<D:Decoder,T:Decodable<D>> Decodable<D> for Rc<T> {
395     #[inline]
396     fn decode(d: &mut D) -> Rc<T> {
397         Rc::new(Decodable::decode(d))
398     }
399 }
400
401 impl<D:Decoder,T:Decodable<D> + 'static> Decodable<D> for @T {
402     fn decode(d: &mut D) -> @T {
403         @Decodable::decode(d)
404     }
405 }
406
407 impl<'a, S:Encoder,T:Encodable<S>> Encodable<S> for &'a [T] {
408     fn encode(&self, s: &mut S) {
409         s.emit_seq(self.len(), |s| {
410             for (i, e) in self.iter().enumerate() {
411                 s.emit_seq_elt(i, |s| e.encode(s))
412             }
413         })
414     }
415 }
416
417 impl<S:Encoder,T:Encodable<S>> Encodable<S> for ~[T] {
418     fn encode(&self, s: &mut S) {
419         s.emit_seq(self.len(), |s| {
420             for (i, e) in self.iter().enumerate() {
421                 s.emit_seq_elt(i, |s| e.encode(s))
422             }
423         })
424     }
425 }
426
427 impl<D:Decoder,T:Decodable<D>> Decodable<D> for ~[T] {
428     fn decode(d: &mut D) -> ~[T] {
429         d.read_seq(|d, len| {
430             slice::from_fn(len, |i| {
431                 d.read_seq_elt(i, |d| Decodable::decode(d))
432             })
433         })
434     }
435 }
436
437 impl<S:Encoder,T:Encodable<S>> Encodable<S> for Vec<T> {
438     fn encode(&self, s: &mut S) {
439         s.emit_seq(self.len(), |s| {
440             for (i, e) in self.iter().enumerate() {
441                 s.emit_seq_elt(i, |s| e.encode(s))
442             }
443         })
444     }
445 }
446
447 impl<D:Decoder,T:Decodable<D>> Decodable<D> for Vec<T> {
448     fn decode(d: &mut D) -> Vec<T> {
449         d.read_seq(|d, len| {
450             Vec::from_fn(len, |i| {
451                 d.read_seq_elt(i, |d| Decodable::decode(d))
452             })
453         })
454     }
455 }
456
457 impl<S:Encoder,T:Encodable<S>> Encodable<S> for Option<T> {
458     fn encode(&self, s: &mut S) {
459         s.emit_option(|s| {
460             match *self {
461                 None => s.emit_option_none(),
462                 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
463             }
464         })
465     }
466 }
467
468 impl<D:Decoder,T:Decodable<D>> Decodable<D> for Option<T> {
469     fn decode(d: &mut D) -> Option<T> {
470         d.read_option(|d, b| {
471             if b {
472                 Some(Decodable::decode(d))
473             } else {
474                 None
475             }
476         })
477     }
478 }
479
480 macro_rules! peel(($name:ident, $($other:ident,)*) => (tuple!($($other,)*)))
481
482 macro_rules! tuple (
483     () => ();
484     ( $($name:ident,)+ ) => (
485         impl<D:Decoder,$($name:Decodable<D>),*> Decodable<D> for ($($name,)*) {
486             #[allow(uppercase_variables)]
487             fn decode(d: &mut D) -> ($($name,)*) {
488                 d.read_tuple(|d, amt| {
489                     let mut i = 0;
490                     let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> $name {
491                         Decodable::decode(d)
492                     }),)*);
493                     assert!(amt == i,
494                             "expected tuple of length `{}`, found tuple \
495                              of length `{}`", i, amt);
496                     return ret;
497                 })
498             }
499         }
500         impl<S:Encoder,$($name:Encodable<S>),*> Encodable<S> for ($($name,)*) {
501             #[allow(uppercase_variables)]
502             fn encode(&self, s: &mut S) {
503                 let ($(ref $name,)*) = *self;
504                 let mut n = 0;
505                 $(let $name = $name; n += 1;)*
506                 s.emit_tuple(n, |s| {
507                     let mut i = 0;
508                     $(s.emit_seq_elt({ i+=1; i-1 }, |s| $name.encode(s));)*
509                 })
510             }
511         }
512         peel!($($name,)*)
513     )
514 )
515
516 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
517
518 impl<E: Encoder> Encodable<E> for path::posix::Path {
519     fn encode(&self, e: &mut E) {
520         self.as_vec().encode(e)
521     }
522 }
523
524 impl<D: Decoder> Decodable<D> for path::posix::Path {
525     fn decode(d: &mut D) -> path::posix::Path {
526         let bytes: ~[u8] = Decodable::decode(d);
527         path::posix::Path::new(bytes)
528     }
529 }
530
531 impl<E: Encoder> Encodable<E> for path::windows::Path {
532     fn encode(&self, e: &mut E) {
533         self.as_vec().encode(e)
534     }
535 }
536
537 impl<D: Decoder> Decodable<D> for path::windows::Path {
538     fn decode(d: &mut D) -> path::windows::Path {
539         let bytes: ~[u8] = Decodable::decode(d);
540         path::windows::Path::new(bytes)
541     }
542 }
543
544 // ___________________________________________________________________________
545 // Helper routines
546 //
547 // In some cases, these should eventually be coded as traits.
548
549 pub trait EncoderHelpers {
550     fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut Self, v: &T|);
551 }
552
553 impl<S:Encoder> EncoderHelpers for S {
554     fn emit_from_vec<T>(&mut self, v: &[T], f: |&mut S, &T|) {
555         self.emit_seq(v.len(), |this| {
556             for (i, e) in v.iter().enumerate() {
557                 this.emit_seq_elt(i, |this| {
558                     f(this, e)
559                 })
560             }
561         })
562     }
563 }
564
565 pub trait DecoderHelpers {
566     fn read_to_vec<T>(&mut self, f: |&mut Self| -> T) -> ~[T];
567 }
568
569 impl<D:Decoder> DecoderHelpers for D {
570     fn read_to_vec<T>(&mut self, f: |&mut D| -> T) -> ~[T] {
571         self.read_seq(|this, len| {
572             slice::from_fn(len, |i| {
573                 this.read_seq_elt(i, |this| f(this))
574             })
575         })
576     }
577 }