This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathserialize.rs
1671 lines (1507 loc) · 58.2 KB
/
serialize.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Support code for encoding and decoding types.
//!
//! In order to allow extensibility in both what types can be encoded and how
//! they are encoded, encoding and decoding are split into two part each. An
//! implementation of the Encodable trait knows how to turn a specific type into
//! a generic form, and then uses an implementation of the Encoder trait to turn
//! this into concrete output (such as a JSON string). Decoder and Decodable do
//! the same for decoding.
/*
Core encoding and decoding interfaces.
*/
use std::cell::{Cell, RefCell};
use std::ffi::OsString;
use std::path;
use std::rc::Rc;
use std::sync::Arc;
use std::marker::PhantomData;
use std::borrow::Cow;
use cap_capacity;
/// Trait for writing out an encoding when serializing.
///
/// This trait provides methods to encode basic types and generic forms of
/// collections. Implementations of `Encodable` use it to perform the actual
/// encoding of a type.
///
/// It is unspecified what is done with the encoding - it could be stored in a
/// variable, or written directly to a file, for example.
///
/// Encoders can expect to only have a single "root" method call made on this
/// trait. Non-trivial types will call one of the collection-emitting methods,
/// passing a function that may call other methods on the trait, but once the
/// collection-emitting method has returned, encoding should be complete.
pub trait Encoder {
/// The error type for method results.
type Error;
// Primitive types:
/// Emit a nil value.
///
/// For example, this might be stored as the null keyword in JSON.
fn emit_nil(&mut self) -> Result<(), Self::Error>;
/// Emit a usize value.
fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
/// Emit a u64 value.
fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
/// Emit a u32 value.
fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
/// Emit a u16 value.
fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
/// Emit a u8 value.
fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
/// Emit a isize value.
fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
/// Emit a i64 value.
fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
/// Emit a i32 value.
fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
/// Emit a i16 value.
fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
/// Emit a i8 value.
fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
/// Emit a bool value.
///
/// For example, this might be stored as the true and false keywords in
/// JSON.
fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
/// Emit a f64 value.
fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
/// Emit a f32 value.
fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
/// Emit a char value.
///
/// Note that strings should be emitted using `emit_str`, not as a sequence
/// of `emit_char` calls.
fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
/// Emit a string value.
fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
// Compound types:
/// Emit an enumeration value.
///
/// * `name` indicates the enumeration type name.
/// * `f` is a function that will call `emit_enum_variant` or
/// `emit_enum_struct_variant` as appropriate to write the actual value.
fn emit_enum<F>(&mut self, name: &str, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a enumeration variant value with no or unnamed data.
///
/// This should only be called from a function passed to `emit_enum`.
/// Variants with named data should use `emit_enum_struct_variant`.
///
/// * `v_name` is the variant name
/// * `v_id` is the numeric identifier for the variant.
/// * `len` is the number of data items associated with the variant.
/// * `f` is a function that will call `emit_enum_variant_arg` for each data
/// item. It may not be called if len is 0.
///
/// # Examples
///
/// ```
/// use rustc_serialize::Encodable;
/// use rustc_serialize::Encoder;
///
/// enum Message {
/// Quit,
/// ChangeColor(i32, i32, i32),
/// }
///
/// impl Encodable for Message {
/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
/// s.emit_enum("Message", |s| {
/// match *self {
/// Message::Quit => {
/// s.emit_enum_variant("Quit", 0, 0, |s| Ok(()))
/// }
/// Message::ChangeColor(r, g, b) => {
/// s.emit_enum_variant("ChangeColor", 1, 3, |s| {
/// try!(s.emit_enum_variant_arg(0, |s| {
/// s.emit_i32(r)
/// }));
/// try!(s.emit_enum_variant_arg(1, |s| {
/// s.emit_i32(g)
/// }));
/// try!(s.emit_enum_variant_arg(2, |s| {
/// s.emit_i32(b)
/// }));
/// Ok(())
/// })
/// }
/// }
/// })
/// }
/// }
/// ```
fn emit_enum_variant<F>(&mut self, v_name: &str,
v_id: usize,
len: usize,
f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit an unnamed data item for an enumeration variant.
///
/// This should only be called from a function passed to
/// `emit_enum_variant`.
///
/// * `a_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// Note that variant data items must be emitted in order - starting with
/// index `0` and finishing with index `len-1`.
fn emit_enum_variant_arg<F>(&mut self, a_idx: usize, f: F)
-> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a enumeration variant value with no or named data.
///
/// This should only be called from a function passed to `emit_enum`.
/// Variants with unnamed data should use `emit_enum_variant`.
///
/// * `v_name` is the variant name.
/// * `v_id` is the numeric identifier for the variant.
/// * `len` is the number of data items associated with the variant.
/// * `f` is a function that will call `emit_enum_struct_variant_field` for
/// each data item. It may not be called if `len` is `0`.
///
/// # Examples
///
/// ```
/// use rustc_serialize::Encodable;
/// use rustc_serialize::Encoder;
///
/// enum Message {
/// Quit,
/// Move { x: i32, y: i32 },
/// }
///
/// impl Encodable for Message {
/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
/// s.emit_enum("Message", |s| {
/// match *self {
/// Message::Quit => {
/// s.emit_enum_struct_variant("Quit", 0, 0, |s| Ok(()))
/// }
/// Message::Move { x: x, y: y } => {
/// s.emit_enum_struct_variant("Move", 1, 2, |s| {
/// try!(s.emit_enum_struct_variant_field("x", 0, |s| {
/// s.emit_i32(x)
/// }));
/// try!(s.emit_enum_struct_variant_field("y", 1, |s| {
/// s.emit_i32(y)
/// }));
/// Ok(())
/// })
/// }
/// }
/// })
/// }
/// }
/// ```
fn emit_enum_struct_variant<F>(&mut self, v_name: &str,
v_id: usize,
len: usize,
f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a named data item for an enumeration variant.
///
/// This should only be called from a function passed to
/// `emit_enum_struct_variant`.
///
/// * `f_name` is the name of the data item field.
/// * `f_idx` is its (zero-based) index.
/// * `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// Note that fields must be emitted in order - starting with index `0` and
/// finishing with index `len-1`.
fn emit_enum_struct_variant_field<F>(&mut self,
f_name: &str,
f_idx: usize,
f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a struct value.
///
/// * `name` is the name of the struct.
/// * `len` is the number of members.
/// * `f` is a function that calls `emit_struct_field` for each member.
///
/// # Examples
///
/// ```
/// use rustc_serialize::Encodable;
/// use rustc_serialize::Encoder;
///
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// impl Encodable for Point {
/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
/// s.emit_struct("Point", 2, |s| {
/// try!(s.emit_struct_field("x", 0, |s| {
/// s.emit_i32(self.x)
/// }));
/// try!(s.emit_struct_field("y", 1, |s| {
/// s.emit_i32(self.y)
/// }));
/// Ok(())
/// })
/// }
/// }
/// ```
fn emit_struct<F>(&mut self, name: &str, len: usize, f: F)
-> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a field item for a struct.
///
/// This should only be called from a function passed to `emit_struct`.
///
/// * `f_name` is the name of the data item field.
/// * `f_idx` is its (zero-based) index.
/// * `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// Note that fields must be emitted in order - starting with index `0` and
/// finishing with index `len-1`.
fn emit_struct_field<F>(&mut self, f_name: &str, f_idx: usize, f: F)
-> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a tuple value.
///
/// * `len` is the number of items in the tuple.
/// * `f` is a function that calls `emit_tuple_arg` for each member.
///
/// Note that external `Encodable` implementations should not normally need
/// to use this method directly; it is meant for the use of this module's
/// own implementation of `Encodable` for tuples.
fn emit_tuple<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a data item for a tuple.
///
/// This should only be called from a function passed to `emit_tuple`.
///
/// * `idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// Note that tuple items must be emitted in order - starting with index `0`
/// and finishing with index `len-1`.
fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a tuple struct value.
///
/// * `name` is the name of the tuple struct.
/// * `len` is the number of items in the tuple struct.
/// * `f` is a function that calls `emit_tuple_struct_arg` for each member.
///
/// # Examples
///
/// ```
/// use rustc_serialize::Encodable;
/// use rustc_serialize::Encoder;
///
/// struct Pair(i32,i32);
///
/// impl Encodable for Pair {
/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
/// let Pair(first,second) = *self;
/// s.emit_tuple_struct("Pair", 2, |s| {
/// try!(s.emit_tuple_arg(0, |s| {
/// s.emit_i32(first)
/// }));
/// try!(s.emit_tuple_arg(1, |s| {
/// s.emit_i32(second)
/// }));
/// Ok(())
/// })
/// }
/// }
/// ```
fn emit_tuple_struct<F>(&mut self, name: &str, len: usize, f: F)
-> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a data item for a tuple struct.
///
/// This should only be called from a function passed to
/// `emit_tuple_struct`.
///
/// * `f_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// Note that tuple items must be emitted in order - starting with index `0`
/// and finishing with index `len-1`.
fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F)
-> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
// Specialized types:
/// Emit an optional value.
///
/// `f` is a function that will call either `emit_option_none` or
/// `emit_option_some` as appropriate.
///
/// This method allows encoders to handle `Option<T>` values specially,
/// rather than using the generic enum methods, because many encoding
/// formats have a built-in "optional" concept.
///
/// Note that external `Encodable` implementations should not normally need
/// to use this method directly; it is meant for the use of this module's
/// own implementation of `Encodable` for `Option<T>`.
fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit the `None` optional value.
///
/// This should only be called from a function passed to `emit_option`.
fn emit_option_none(&mut self) -> Result<(), Self::Error>;
/// Emit the `Some(x)` optional value.
///
/// `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// This should only be called from a function passed to `emit_option`.
fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit a sequence of values.
///
/// This should be used for both array-like ordered sequences and set-like
/// unordered ones.
///
/// * `len` is the number of values in the sequence.
/// * `f` is a function that will call `emit_seq_elt` for each value in the
/// sequence.
fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit an element in a sequence.
///
/// This should only be called from a function passed to `emit_seq`.
///
/// * `idx` is the (zero-based) index of the value in the sequence.
/// * `f` is a function that will call the appropriate emit method to encode
/// the data object.
///
/// Note that sequence elements must be emitted in order - starting with
/// index `0` and finishing with index `len-1`.
fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit an associative container (map).
///
/// * `len` is the number of entries in the map.
/// * `f` is a function that will call `emit_map_elt_key` and
/// `emit_map_elt_val` for each entry in the map.
///
/// # Examples
///
/// ```
/// use rustc_serialize::Encodable;
/// use rustc_serialize::Encoder;
///
/// struct SimpleMap<K,V> {
/// entries: Vec<(K,V)>,
/// }
///
/// impl<K:Encodable,V:Encodable> Encodable for SimpleMap<K,V> {
/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
/// s.emit_map(self.entries.len(), |s| {
/// for (i, e) in self.entries.iter().enumerate() {
/// let (ref k, ref v) = *e;
/// try!(s.emit_map_elt_key(i, |s| k.encode(s)));
/// try!(s.emit_map_elt_val(i, |s| v.encode(s)));
/// }
/// Ok(())
/// })
/// }
/// }
/// ```
fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit the key for an entry in a map.
///
/// This should only be called from a function passed to `emit_map`.
///
/// * `idx` is the (zero-based) index of the entry in the map
/// * `f` is a function that will call the appropriate emit method to encode
/// the key.
///
/// Note that map entries must be emitted in order - starting with index `0`
/// and finishing with index `len-1` - and for each entry, the key should be
/// emitted followed immediately by the value.
fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
/// Emit the value for an entry in a map.
///
/// This should only be called from a function passed to `emit_map`.
///
/// * `idx` is the (zero-based) index of the entry in the map
/// * `f` is a function that will call the appropriate emit method to encode
/// the value.
///
/// Note that map entries must be emitted in order - starting with index `0`
/// and finishing with index `len-1` - and for each entry, the key should be
/// emitted followed immediately by the value.
fn emit_map_elt_val<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
}
/// Trait for reading in an encoding for deserialization.
///
/// This trait provides methods to decode basic types and generic forms of
/// collections. Implementations of `Decodable` use it to perform the actual
/// decoding of a type.
///
/// Note that, as is typical with deserialization, the design of this API
/// assumes you know in advance the form of the data you are decoding (ie: what
/// type is encoded).
///
/// Decoders can expect to only have a single "root" method call made on this
/// trait. Non-trivial types will call one of the collection-reading methods,
/// passing a function that may call other methods on the trait, but once the
/// collection-reading method has returned, decoding should be complete.
pub trait Decoder {
/// The error type for method results.
type Error;
// Primitive types:
/// Read a nil value.
fn read_nil(&mut self) -> Result<(), Self::Error>;
/// Read a usize value.
fn read_usize(&mut self) -> Result<usize, Self::Error>;
/// Read a u64 value.
fn read_u64(&mut self) -> Result<u64, Self::Error>;
/// Read a u32 value.
fn read_u32(&mut self) -> Result<u32, Self::Error>;
/// Read a u16 value.
fn read_u16(&mut self) -> Result<u16, Self::Error>;
/// Read a u8 value.
fn read_u8(&mut self) -> Result<u8, Self::Error>;
/// Read a isize value.
fn read_isize(&mut self) -> Result<isize, Self::Error>;
/// Read a i64 value.
fn read_i64(&mut self) -> Result<i64, Self::Error>;
/// Read a i32 value.
fn read_i32(&mut self) -> Result<i32, Self::Error>;
/// Read a i16 value.
fn read_i16(&mut self) -> Result<i16, Self::Error>;
/// Read a i8 value.
fn read_i8(&mut self) -> Result<i8, Self::Error>;
/// Read a bool value.
fn read_bool(&mut self) -> Result<bool, Self::Error>;
/// Read a f64 value.
fn read_f64(&mut self) -> Result<f64, Self::Error>;
/// Read a f32 value.
fn read_f32(&mut self) -> Result<f32, Self::Error>;
/// Read a char value.
fn read_char(&mut self) -> Result<char, Self::Error>;
/// Read a string value.
fn read_str(&mut self) -> Result<String, Self::Error>;
// Compound types:
/// Read an enumeration value.
///
/// * `name` indicates the enumeration type name. It may be used to
/// sanity-check the data being read.
/// * `f` is a function that will call `read_enum_variant` (or
/// `read_enum_struct_variant`) to read the actual value.
fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read an enumeration value.
///
/// * `names` is a list of the enumeration variant names.
/// * `f` is a function that will call `read_enum_variant_arg` or
/// `read_enum_struct_variant_field` as appropriate to read the
/// associated values. It will be passed the index into `names` for the
/// variant that is encoded.
fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F)
-> Result<T, Self::Error>
where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>;
/// Read an unnamed data item for an enumeration variant.
///
/// This should only be called from a function passed to `read_enum_variant`
/// or `read_enum_struct_variant`, and only when the index provided to that
/// function indicates that the variant has associated unnamed data. It
/// should be called once for each associated data item.
///
/// * `a_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate read method to deocde
/// the data object.
///
/// Note that variant data items must be read in order - starting with index
/// `0` and finishing with index `len-1`. Implementations may use `a_idx`,
/// the call order or both to select the correct data to decode.
fn read_enum_variant_arg<T, F>(&mut self, a_idx: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read an enumeration value.
///
/// This is identical to `read_enum_variant`, and is only provided for
/// symmetry with the `Encoder` API.
fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F)
-> Result<T, Self::Error>
where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>;
/// Read a named data item for an enumeration variant.
///
/// This should only be called from a function passed to `read_enum_variant`
/// or `read_enum_struct_variant`, and only when the index provided to that
/// function indicates that the variant has associated named data. It should
/// be called once for each associated field.
///
/// * `f_name` is the name of the field.
/// * `f_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate read method to deocde
/// the data object.
///
/// Note that fields must be read in order - starting with index `0` and
/// finishing with index `len-1`. Implementations may use `f_idx`, `f_name`,
/// the call order or any combination to choose the correct data to decode,
/// and may (but are not required to) return an error if these are
/// inconsistent.
fn read_enum_struct_variant_field<T, F>(&mut self,
f_name: &str,
f_idx: usize,
f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read an struct value.
///
/// * `s_name` indicates the struct type name. It may be used to
/// sanity-check the data being read.
/// * `len` indicates the number of fields in the struct.
/// * `f` is a function that will call `read_struct_field` for each field in
/// the struct.
fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read a field for a struct value.
///
/// This should only be called from a function passed to `read_struct`. It
/// should be called once for each associated field.
///
/// * `f_name` is the name of the field.
/// * `f_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate read method to deocde
/// the data object.
///
/// Note that fields must be read in order - starting with index `0` and
/// finishing with index `len-1`. Implementations may use `f_idx`, `f_name`,
/// the call order or any combination to choose the correct data to decode,
/// and may (but are not required to) return an error if these are
/// inconsistent.
fn read_struct_field<T, F>(&mut self,
f_name: &str,
f_idx: usize,
f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read a tuple value.
///
/// * `len` is the number of items in the tuple.
/// * `f` is a function that will call `read_tuple_arg` for each item in the
/// tuple.
///
/// Note that external `Decodable` implementations should not normally need
/// to use this method directly; it is meant for the use of this module's
/// own implementation of `Decodable` for tuples.
fn read_tuple<T, F>(&mut self, len: usize, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read a data item for a tuple.
///
/// This should only be called from a function passed to `read_tuple`.
///
/// * `a_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate read method to encode
/// the data object.
///
/// Note that tuple items must be read in order - starting with index `0`
/// and finishing with index `len-1`.
fn read_tuple_arg<T, F>(&mut self, a_idx: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read a tuple struct value.
///
/// * `s_name` is the name of the tuple struct.
/// * `len` is the number of items in the tuple struct.
/// * `f` is a function that calls `read_tuple_struct_arg` for each member.
fn read_tuple_struct<T, F>(&mut self, s_name: &str, len: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read a data item for a tuple struct.
///
/// This should only be called from a function passed to
/// `read_tuple_struct`.
///
/// * `a_idx` is the (zero-based) index of the data item.
/// * `f` is a function that will call the appropriate read method to encode
/// the data object.
///
/// Note that tuple struct items must be read in order - starting with index
/// `0` and finishing with index `len-1`.
fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
// Specialized types:
/// Read an optional value.
///
/// `f` is a function that will will be passed be passed `false` if the
/// value is unset, and `true` if it is set. If the function is passed
/// `true`, it will call the appropriate read methods to read the associated
/// data type.
///
/// This method allows decoders to handle `Option<T>` values specially,
/// rather than using the generic enum methods, because many encoding
/// formats have a built-in "optional" concept.
///
/// Note that external `Decodable` implementations should not normally need
/// to use this method directly; it is meant for the use of this module's
/// own implementation of `Decodable` for `Option<T>`.
fn read_option<T, F>(&mut self, f: F) -> Result<T, Self::Error>
where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>;
/// Read a sequence of values.
///
/// This should be used for both array-like ordered sequences and set-like
/// unordered ones.
///
/// * `f` is a function that will be passed the length of the sequence, and
/// will call `read_seq_elt` for each value in the sequence.
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>;
/// Read an element in the sequence.
///
/// This should only be called from a function passed to `read_seq`.
///
/// * `idx` is the (zero-based) index of the value in the sequence.
/// * `f` is a function that will call the appropriate read method to decode
/// the data object.
///
/// Note that sequence elements must be read in order - starting with index
/// `0` and finishing with index `len-1`.
fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read an associative container (map).
///
/// * `f` is a function that will be passed the number of entries in the
/// map, and will call `read_map_elt_key` and `read_map_elt_val` to decode
/// each entry.
fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>;
/// Read the key for an entry in a map.
///
/// This should only be called from a function passed to `read_map`.
///
/// * `idx` is the (zero-based) index of the entry in the map
/// * `f` is a function that will call the appropriate read method to decode
/// the key.
///
/// Note that map entries must be read in order - starting with index `0`
/// and finishing with index `len-1` - and for each entry, the key should be
/// read followed immediately by the value.
fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
/// Read the value for an entry in a map.
///
/// This should only be called from a function passed to `read_map`.
///
/// * `idx` is the (zero-based) index of the entry in the map
/// * `f` is a function that will call the appropriate read method to decode
/// the value.
///
/// Note that map entries must be read in order - starting with index `0`
/// and finishing with index `len-1` - and for each entry, the key should be
/// read followed immediately by the value.
fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F)
-> Result<T, Self::Error>
where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
// Failure
/// Record a decoding error.
///
/// This allows `Decodable` implementations to report an error using a
/// `Decoder` implementation's error type when inconsistent data is read.
/// For example, when reading a fixed-length array and the wrong length is
/// given by `read_seq`.
fn error(&mut self, err: &str) -> Self::Error;
}
/// Trait for serializing a type.
///
/// This can be implemented for custom data types to allow them to be encoded
/// with `Encoder` implementations. Most of Rust's built-in or standard data
/// types (like `i32` and `Vec<T>`) have `Encodable` implementations provided by
/// this module.
///
/// Note that, in general, you should let the compiler implement this for you by
/// using the `derive(RustcEncodable)` attribute.
///
/// # Examples
///
/// ```rust
/// extern crate rustc_serialize;
///
/// #[derive(RustcEncodable)]
/// struct Point {
/// x: i32,
/// y: i32,
/// }
/// # fn main() {}
/// ```
///
/// This generates code equivalent to:
///
/// ```rust
/// extern crate rustc_serialize;
/// use rustc_serialize::Encodable;
/// use rustc_serialize::Encoder;
///
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// impl Encodable for Point {
/// fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
/// s.emit_struct("Point", 2, |s| {
/// try!(s.emit_struct_field("x", 0, |s| {
/// s.emit_i32(self.x)
/// }));
/// try!(s.emit_struct_field("y", 1, |s| {
/// s.emit_i32(self.y)
/// }));
/// Ok(())
/// })
/// }
/// }
/// # fn main() {}
/// ```
pub trait Encodable {
/// Serialize a value using an `Encoder`.
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
}
/// Trait for deserializing a type.
///
/// This can be implemented for custom data types to allow them to be decoded
/// with `Decoder` implementations. Most of Rust's built-in or standard data
/// types (like `i32` and `Vec<T>`) have `Decodable` implementations provided by
/// this module.
///
/// Note that, in general, you should let the compiler implement this for you by
/// using the `derive(RustcDecodable)` attribute.
///
/// # Examples
///
/// ```rust
/// extern crate rustc_serialize;
///
/// #[derive(RustcDecodable)]
/// struct Point {
/// x: i32,
/// y: i32,
/// }
/// # fn main() {}
/// ```
///
/// This generates code equivalent to:
///
/// ```rust
/// extern crate rustc_serialize;
/// use rustc_serialize::Decodable;
/// use rustc_serialize::Decoder;
///
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// impl Decodable for Point {
/// fn decode<D: Decoder>(d: &mut D) -> Result<Point, D::Error> {
/// d.read_struct("Point", 2, |d| {
/// let x = try!(d.read_struct_field("x", 0, |d| { d.read_i32() }));
/// let y = try!(d.read_struct_field("y", 1, |d| { d.read_i32() }));
/// Ok(Point{ x: x, y: y })
/// })
/// }
/// }
/// # fn main() {}
/// ```
pub trait Decodable: Sized {
/// Deserialize a value using a `Decoder`.
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
}
impl Encodable for usize {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_usize(*self)
}
}
impl Decodable for usize {
fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
d.read_usize()
}
}
impl Encodable for u8 {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u8(*self)
}
}
impl Decodable for u8 {
fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
d.read_u8()
}
}
impl Encodable for u16 {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u16(*self)
}
}
impl Decodable for u16 {
fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
d.read_u16()
}
}
impl Encodable for u32 {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u32(*self)
}
}
impl Decodable for u32 {
fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
d.read_u32()
}
}
impl Encodable for u64 {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u64(*self)
}
}
impl Decodable for u64 {
fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
d.read_u64()
}
}
impl Encodable for isize {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_isize(*self)
}
}
impl Decodable for isize {
fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
d.read_isize()
}
}
impl Encodable for i8 {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_i8(*self)
}
}
impl Decodable for i8 {
fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
d.read_i8()
}
}
impl Encodable for i16 {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_i16(*self)
}
}
impl Decodable for i16 {
fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
d.read_i16()
}