-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
deserialize.rs
1022 lines (932 loc) · 29.8 KB
/
deserialize.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
use std::{
borrow::Cow,
collections::HashMap,
future::Future,
hash::{BuildHasher, Hash},
marker::PhantomData,
pin::Pin,
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};
use crate::{
Array, CowBytes, CowStr, IntoStatic, Map, MerdeError, StackInfo, Value, WithLifetime,
NEXT_FUTURE,
};
#[derive(Debug)]
pub enum Event<'s> {
I64(i64),
U64(u64),
Float(f64),
Str(CowStr<'s>),
Bytes(CowBytes<'s>),
Bool(bool),
Null,
MapStart,
MapEnd,
ArrayStart(ArrayStart),
ArrayEnd,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum EventType {
I64,
U64,
Float,
Str,
Bytes,
Bool,
Null,
MapStart,
MapEnd,
ArrayStart,
ArrayEnd,
}
impl From<&Event<'_>> for EventType {
fn from(event: &Event<'_>) -> Self {
match event {
Event::I64(_) => EventType::I64,
Event::U64(_) => EventType::U64,
Event::Float(_) => EventType::Float,
Event::Str(_) => EventType::Str,
Event::Bytes(_) => EventType::Bytes,
Event::Bool(_) => EventType::Bool,
Event::Null => EventType::Null,
Event::MapStart => EventType::MapStart,
Event::MapEnd => EventType::MapEnd,
Event::ArrayStart(_) => EventType::ArrayStart,
Event::ArrayEnd => EventType::ArrayEnd,
}
}
}
#[derive(Debug)]
pub struct ArrayStart {
pub size_hint: Option<usize>,
}
impl<'s> Event<'s> {
pub fn into_i64(self) -> Result<i64, MerdeError<'static>> {
match self {
Event::I64(i) => Ok(i),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::I64],
}),
}
}
pub fn into_u64(self) -> Result<u64, MerdeError<'static>> {
match self {
Event::U64(u) => Ok(u),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::U64],
}),
}
}
pub fn into_f64(self) -> Result<f64, MerdeError<'static>> {
match self {
Event::Float(f) => Ok(f),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::Float],
}),
}
}
pub fn into_str(self) -> Result<CowStr<'s>, MerdeError<'static>> {
match self {
Event::Str(s) => Ok(s),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::Str],
}),
}
}
pub fn into_bytes(self) -> Result<CowBytes<'s>, MerdeError<'static>> {
match self {
Event::Bytes(b) => Ok(b),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::Bytes],
}),
}
}
pub fn into_bool(self) -> Result<bool, MerdeError<'static>> {
match self {
Event::Bool(b) => Ok(b),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::Bool],
}),
}
}
pub fn into_null(self) -> Result<(), MerdeError<'static>> {
match self {
Event::Null => Ok(()),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::Null],
}),
}
}
pub fn into_map_start(self) -> Result<(), MerdeError<'static>> {
match self {
Event::MapStart => Ok(()),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::MapStart],
}),
}
}
pub fn into_map_end(self) -> Result<(), MerdeError<'static>> {
match self {
Event::MapEnd => Ok(()),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::MapEnd],
}),
}
}
pub fn into_array_start(self) -> Result<ArrayStart, MerdeError<'static>> {
match self {
Event::ArrayStart(array_start) => Ok(array_start),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::ArrayStart],
}),
}
}
pub fn into_array_end(self) -> Result<(), MerdeError<'static>> {
match self {
Event::ArrayEnd => Ok(()),
_ => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&self),
expected: &[EventType::ArrayEnd],
}),
}
}
}
pub trait Deserializer<'s>: std::fmt::Debug {
type Error<'es>: From<MerdeError<'es>>;
/// Get the next event from the deserializer.
#[doc(hidden)]
fn next(&mut self) -> Result<Event<'s>, Self::Error<'s>>;
/// Deserialize a value of type `T`.
#[doc(hidden)]
#[allow(async_fn_in_trait)]
async fn t<T: Deserialize<'s>>(&mut self) -> Result<T, Self::Error<'s>> {
self.t_starting_with(None).await
}
/// Deserialize a value of type `T`, using the given event as the first event.
#[doc(hidden)]
#[allow(async_fn_in_trait)]
async fn t_starting_with<T: Deserialize<'s>>(
&mut self,
starter: Option<Event<'s>>,
) -> Result<T, Self::Error<'s>>;
/// Return a boxed version of `Self::t_starting_with`, useful to avoid
/// future sizes becoming infinite, for example when deserializing Value,
/// etc.
#[doc(hidden)]
fn t_starting_with_boxed<'d, T: Deserialize<'s> + 'd>(
&'d mut self,
starter: Option<Event<'s>>,
) -> Pin<Box<dyn Future<Output = Result<T, Self::Error<'s>>> + 'd>>
where
's: 'd,
{
// TODO: cache in a thread-local, or, more simply, in a deserialization context?
let stack_info = StackInfo::get();
let fut = self.t_starting_with(starter);
Box::pin(async move {
// TODO: 8K is not one-size-fits-all
if stack_info.left() < 8 * 1024 {
// this is probably not actually on the stack because we're in a boxed future
let mut result: Option<Result<T, Self::Error<'s>>> = None;
// first turn it into a trait object
let background_fut: Pin<Box<dyn Future<Output = ()>>> = Box::pin(async {
result = Some(fut.await);
});
let background_fut: Pin<Box<dyn Future<Output = ()> + 'static>> = unsafe {
// # Safety: this isn't actually 'static, it's "valid for the synchronous
// call to deserialize".
// todo: make sure that this is actually the case by handling panics and
// clearing thread-locals.
std::mem::transmute(background_fut)
};
NEXT_FUTURE.with_borrow_mut(|next_future| *next_future = Some(background_fut));
ReturnPendingOnce::new().await;
result.unwrap()
} else {
fut.await
}
})
}
fn deserialize<T: Deserialize<'s>>(&mut self) -> Result<T, Self::Error<'s>> {
let vtable = RawWakerVTable::new(|_| todo!(), |_| {}, |_| {}, |_| {});
let vtable = Box::leak(Box::new(vtable));
let w = unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), vtable)) };
let mut cx = Context::from_waker(&w);
let first_fut = self.t_starting_with(None);
let mut first_fut = std::pin::pin!(first_fut);
match first_fut.as_mut().poll(&mut cx) {
Poll::Ready(res) => res,
_ => {
// oh boy. okay.
let mut stack = vec![];
'crimes: loop {
let mut fut = NEXT_FUTURE
.with_borrow_mut(|next_fut| next_fut.take())
.expect("NEXT_FUTURE must've been set before returning Poll::Pending");
match Pin::new(&mut fut).poll(&mut cx) {
Poll::Ready(_) => break 'crimes,
Poll::Pending => {
stack.push(fut);
}
}
}
while let Some(mut fut) = stack.pop() {
match Pin::new(&mut fut).poll(&mut cx) {
Poll::Ready(_) => {
// cool let's keep going
}
Poll::Pending => {
unreachable!("I'm sorry you really only get to ask for more stack once")
}
}
}
match first_fut.poll(&mut cx) {
Poll::Ready(res) => res,
Poll::Pending => {
unreachable!("Like I said, you really only get to ask for more stack once")
}
}
}
}
}
/// Deserialize a value of type `T` and return its static variant
/// e.g. (CowStr<'static>, etc.)
fn deserialize_owned<T>(&mut self) -> Result<T, Self::Error<'s>>
where
T: 'static,
T: WithLifetime<'s>,
<T as WithLifetime<'s>>::Lifetimed: Deserialize<'s> + IntoStatic<Output = T>,
{
self.deserialize()
.map(|t: <T as WithLifetime<'s>>::Lifetimed| t.into_static())
}
}
/// Allows filling in a field of a struct while deserializing.
///
/// Enforces some type safety at runtime, by carrying lifetimes
/// around and making sure that at least the type_name matches.
/// There's a non-zero chance I messed something up and this is
/// actually badly UB though. I should ask miri.
pub struct FieldSlot<'s, 'borrow> {
option: &'borrow mut Option<()>,
type_name_of_option_field: &'static str,
_phantom: PhantomData<&'s ()>,
}
impl<'s, 'borrow> FieldSlot<'s, 'borrow> {
/// Construct a new `FieldSlot`, ready to be filled
#[inline(always)]
pub fn new<T: 's>(option: &'borrow mut Option<T>, type_name_of_slot: &'static str) -> Self {
Self {
option: unsafe { std::mem::transmute::<&mut Option<T>, &mut Option<()>>(option) },
type_name_of_option_field: type_name_of_slot,
_phantom: PhantomData,
}
}
/// Fill this field with a value.
pub fn fill<T: 's>(self, value: T) {
let type_name_of_option_value = std::any::type_name::<Option<T>>();
assert_eq!(self.type_name_of_option_field, type_name_of_option_value);
let option_ref =
unsafe { std::mem::transmute::<&mut Option<()>, &mut Option<T>>(self.option) };
option_ref.replace(value);
}
}
/// Opinions you have about deserialization: should unknown fields
/// be allowed, etc.
///
/// These are opinions _for a specific type_, not for the whole
/// deserialization tree. They cannot be set from the outside, they
/// can only be used to control the behavior of code generated via
/// `merde::derive!`.
pub trait DeserOpinions {
/// Should `{ a: 1, b: 2 }` be rejected when encountering b,
/// if we are deserializing `struct Foo { a: i32 }`?
fn deny_unknown_fields(&self) -> bool;
/// If we encounter `{ "jazzBand": 1 }`, should we try to find a field
/// named "jazzBand" on the struct we're deserializing, or should we
/// map it to something else, like "jazz_band"?
fn map_key_name<'s>(&self, key: CowStr<'s>) -> CowStr<'s>;
/// If we encounter `{ a: 1 }`, but we are deserializing `struct Foo { a: i32, b: i32 }`,
/// `fill_default` will be called with `key = "b"` and decide what to do.
///
/// Note that this is called with the field name, not whatever name we found in the
/// "document" — if `map_key_name` mapped "jazzBand" to "jazz_band", then this is
/// called with "jazz_band".
#[allow(clippy::needless_lifetimes)]
fn default_field_value<'s, 'borrow>(&self, key: &'borrow str, slot: FieldSlot<'s, 'borrow>);
}
/// merde's default opinions for deserialization: allow unknown fields, don't fill in default values
/// and keep key names as-is.
pub struct DefaultDeserOpinions;
impl DeserOpinions for DefaultDeserOpinions {
#[inline(always)]
fn deny_unknown_fields(&self) -> bool {
// by default, allow unknown fields
false
}
#[inline(always)]
#[allow(clippy::needless_lifetimes)]
fn default_field_value<'s, 'borrow>(&self, _key: &'borrow str, _slot: FieldSlot<'s, 'borrow>) {
// by default, don't fill in default values for any fields
// (they will just error out)
}
#[inline(always)]
fn map_key_name<'s>(&self, key: CowStr<'s>) -> CowStr<'s> {
// by default, keep key names as-is
key
}
}
pub trait Deserialize<'s>: Sized {
#[allow(async_fn_in_trait)]
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized;
fn from_option(value: Option<Self>, field_name: CowStr<'s>) -> Result<Self, MerdeError<'s>> {
match value {
Some(value) => Ok(value),
None => Err(MerdeError::MissingProperty(field_name)),
}
}
}
pub trait DeserializeOwned: Sized {
fn deserialize_owned<'s, D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized;
}
impl<T> DeserializeOwned for T
where
T: for<'s> WithLifetime<'s> + 'static,
for<'s> <T as WithLifetime<'s>>::Lifetimed: Deserialize<'s> + IntoStatic<Output = T>,
{
fn deserialize_owned<'s, D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.deserialize_owned()
}
}
impl<'s> Deserialize<'s> for i64 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: i64 = match de.next()? {
Event::I64(i) => i,
Event::U64(u) => u.try_into().map_err(|_| MerdeError::OutOfRange)?,
Event::Float(f) => f as _,
ev => {
return Err(MerdeError::UnexpectedEvent {
got: EventType::from(&ev),
expected: &[EventType::I64, EventType::U64, EventType::Float],
}
.into())
}
};
Ok(v)
}
}
impl<'s> Deserialize<'s> for u64 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: u64 = match de.next()? {
Event::U64(u) => u,
Event::I64(i) => i.try_into().map_err(|_| MerdeError::OutOfRange)?,
Event::Float(f) => f as u64,
ev => {
return Err(MerdeError::UnexpectedEvent {
got: EventType::from(&ev),
expected: &[EventType::U64, EventType::I64, EventType::Float],
}
.into())
}
};
Ok(v)
}
}
impl<'s> Deserialize<'s> for i32 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: i64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for u32 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: u64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for i16 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: i64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for u16 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: u64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for i8 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: i64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for u8 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: u64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for isize {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: i64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for usize {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: u64 = de.t().await?;
v.try_into().map_err(|_| MerdeError::OutOfRange.into())
}
}
impl<'s> Deserialize<'s> for bool {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
Ok(de.next()?.into_bool()?)
}
}
impl<'s> Deserialize<'s> for f64 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: f64 = match de.next()? {
Event::Float(f) => f,
Event::I64(i) => i as f64,
Event::U64(u) => u as f64,
ev => {
return Err(MerdeError::UnexpectedEvent {
got: EventType::from(&ev),
expected: &[EventType::Float, EventType::I64, EventType::U64],
}
.into())
}
};
Ok(v)
}
}
impl<'s> Deserialize<'s> for f32 {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let v: f64 = de.t().await?;
Ok(v as f32)
}
}
impl<'s> Deserialize<'s> for String {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let cow: CowStr<'s> = de.t().await?;
Ok(cow.to_string())
}
}
impl<'s> Deserialize<'s> for CowStr<'s> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
Ok(de.next()?.into_str()?)
}
}
impl<'s> Deserialize<'s> for Cow<'s, str> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let cow: CowStr<'s> = de.t().await?;
Ok(match cow {
CowStr::Borrowed(s) => Cow::Borrowed(s),
CowStr::Owned(s) => Cow::Owned(s.to_string()),
})
}
}
impl<'s, T: Deserialize<'s>> Deserialize<'s> for Option<T> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
match de.next()? {
Event::Null => Ok(None),
ev => {
let value = de.t_starting_with(Some(ev)).await?;
Ok(Some(value))
}
}
}
fn from_option(value: Option<Self>, _field_name: CowStr<'s>) -> Result<Self, MerdeError<'s>> {
match value {
Some(value) => Ok(value),
None => Ok(None),
}
}
}
impl<'s, T: Deserialize<'s>> Deserialize<'s> for Vec<T> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let array_start = de.next()?.into_array_start()?;
let mut vec = if let Some(size) = array_start.size_hint {
Vec::with_capacity(size)
} else {
Vec::new()
};
loop {
match de.next()? {
Event::ArrayEnd => {
#[cfg(debug_assertions)]
{
println!("Stack trace:");
let backtrace = std::backtrace::Backtrace::capture();
println!("{}", backtrace);
}
break;
}
ev => {
let item: T = de.t_starting_with(Some(ev)).await?;
vec.push(item);
}
}
}
Ok(vec)
}
}
impl<'s, K, V, S> Deserialize<'s> for HashMap<K, V, S>
where
K: Deserialize<'s> + Eq + Hash,
V: Deserialize<'s>,
S: Default + BuildHasher + 's,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_map_start()?;
let mut map = HashMap::<K, V, S>::default();
loop {
match de.next()? {
Event::MapEnd => break,
ev => {
let key: K = de.t_starting_with(Some(ev)).await?;
let value: V = de.t().await?;
map.insert(key, value);
}
}
}
Ok(map)
}
}
impl<'s> Deserialize<'s> for Map<'s> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_map_start()?;
let mut map = Map::new();
loop {
match de.next()? {
Event::MapEnd => break,
Event::Str(key) => {
let value: Value<'s> = de.t().await?;
map.insert(key, value);
}
ev => {
return Err(MerdeError::UnexpectedEvent {
got: EventType::from(&ev),
expected: &[EventType::Str, EventType::MapEnd],
}
.into())
}
}
}
Ok(map)
}
}
impl<'s> Deserialize<'s> for Array<'s> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
let array_start = de.next()?.into_array_start()?;
let mut array = if let Some(size) = array_start.size_hint {
Array::with_capacity(size)
} else {
Array::new()
};
loop {
match de.next()? {
Event::ArrayEnd => break,
ev => {
let item: Value<'s> = de.t_starting_with(Some(ev)).await?;
array.push(item);
}
}
}
Ok(array)
}
}
impl<'s> Deserialize<'s> for Value<'s> {
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
match de.next()? {
Event::I64(i) => Ok(Value::I64(i)),
Event::U64(u) => Ok(Value::U64(u)),
Event::Float(f) => Ok(Value::Float(f.into())),
Event::Str(s) => Ok(Value::Str(s)),
Event::Bytes(b) => Ok(Value::Bytes(b)),
Event::Bool(b) => Ok(Value::Bool(b)),
Event::Null => Ok(Value::Null),
Event::MapStart => {
let mut map = Map::new();
loop {
match de.next()? {
Event::MapEnd => break,
Event::Str(key) => {
let value: Value = de.t_starting_with_boxed(None).await?;
map.insert(key, value);
}
ev => {
return Err(MerdeError::UnexpectedEvent {
got: EventType::from(&ev),
expected: &[EventType::Str, EventType::MapEnd],
}
.into())
}
}
}
Ok(Value::Map(map))
}
Event::ArrayStart(_) => {
let mut vec = Array::new();
loop {
match de.next()? {
Event::ArrayEnd => break,
ev => {
let item: Value = de.t_starting_with_boxed(Some(ev)).await?;
vec.push(item);
}
}
}
Ok(Value::Array(vec))
}
ev => Err(MerdeError::UnexpectedEvent {
got: EventType::from(&ev),
expected: &[
EventType::I64,
EventType::U64,
EventType::Float,
EventType::Str,
EventType::Bytes,
EventType::Bool,
EventType::Null,
EventType::MapStart,
EventType::ArrayStart,
],
}
.into()),
}
}
}
impl<'s, T1> Deserialize<'s> for (T1,)
where
T1: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1,))
}
}
impl<'s, T1, T2> Deserialize<'s> for (T1, T2)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2))
}
}
impl<'s, T1, T2, T3> Deserialize<'s> for (T1, T2, T3)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
T3: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
let t3 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2, t3))
}
}
impl<'s, T1, T2, T3, T4> Deserialize<'s> for (T1, T2, T3, T4)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
T3: Deserialize<'s>,
T4: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
let t3 = de.t().await?;
let t4 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2, t3, t4))
}
}
impl<'s, T1, T2, T3, T4, T5> Deserialize<'s> for (T1, T2, T3, T4, T5)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
T3: Deserialize<'s>,
T4: Deserialize<'s>,
T5: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
let t3 = de.t().await?;
let t4 = de.t().await?;
let t5 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2, t3, t4, t5))
}
}
impl<'s, T1, T2, T3, T4, T5, T6> Deserialize<'s> for (T1, T2, T3, T4, T5, T6)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
T3: Deserialize<'s>,
T4: Deserialize<'s>,
T5: Deserialize<'s>,
T6: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
let t3 = de.t().await?;
let t4 = de.t().await?;
let t5 = de.t().await?;
let t6 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2, t3, t4, t5, t6))
}
}
impl<'s, T1, T2, T3, T4, T5, T6, T7> Deserialize<'s> for (T1, T2, T3, T4, T5, T6, T7)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
T3: Deserialize<'s>,
T4: Deserialize<'s>,
T5: Deserialize<'s>,
T6: Deserialize<'s>,
T7: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
let t3 = de.t().await?;
let t4 = de.t().await?;
let t5 = de.t().await?;
let t6 = de.t().await?;
let t7 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2, t3, t4, t5, t6, t7))
}
}
impl<'s, T1, T2, T3, T4, T5, T6, T7, T8> Deserialize<'s> for (T1, T2, T3, T4, T5, T6, T7, T8)
where
T1: Deserialize<'s>,
T2: Deserialize<'s>,
T3: Deserialize<'s>,
T4: Deserialize<'s>,
T5: Deserialize<'s>,
T6: Deserialize<'s>,
T7: Deserialize<'s>,
T8: Deserialize<'s>,
{
async fn deserialize<D>(de: &mut D) -> Result<Self, D::Error<'s>>
where
D: Deserializer<'s> + ?Sized,
{
de.next()?.into_array_start()?;
let t1 = de.t().await?;
let t2 = de.t().await?;
let t3 = de.t().await?;
let t4 = de.t().await?;
let t5 = de.t().await?;
let t6 = de.t().await?;
let t7 = de.t().await?;
let t8 = de.t().await?;
de.next()?.into_array_end()?;
Ok((t1, t2, t3, t4, t5, t6, t7, t8))
}
}
struct ReturnPendingOnce {
polled: bool,