forked from ch-robinson/dotnet-avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryDeserializerBuilder.cs
2342 lines (2043 loc) · 90.2 KB
/
BinaryDeserializerBuilder.cs
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
using Chr.Avro.Abstract;
using Chr.Avro.Resolution;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Xml;
namespace Chr.Avro.Serialization
{
/// <summary>
/// Builds Avro deserializers for .NET types.
/// </summary>
public interface IBinaryDeserializerBuilder
{
/// <summary>
/// Builds a delegate that reads a serialized object from a stream.
/// </summary>
/// <typeparam name="T">
/// The type of object to be deserialized. If the type is a class or a struct, it must have
/// a parameterless public constructor.
/// </typeparam>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// An optional delegate cache. The cache can be used to provide custom implementations for
/// particular type-schema pairs, and it will also be populated as the delegate is built.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
Func<Stream, T> BuildDelegate<T>(Schema schema, IDictionary<(Type, Schema), Delegate> cache = null);
/// <summary>
/// Builds a binary deserializer.
/// </summary>
/// <typeparam name="T">
/// The type of object to be deserialized. If the type is a class or a struct, it must have
/// a parameterless public constructor.
/// </typeparam>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
IBinaryDeserializer<T> BuildDeserializer<T>(Schema schema);
}
/// <summary>
/// Builds Avro deserializers for specific type-schema combinations. Used by
/// <see cref="BinaryDeserializerBuilder" /> to break apart deserializer building logic.
/// </summary>
public interface IBinaryDeserializerBuilderCase
{
/// <summary>
/// Builds a deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache. If a delegate is cached for a specific type-schema pair, that delegate
/// will be returned for all subsequent occurrences of the pair.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object. Since
/// this is not a typed method, the general <see cref="Delegate" /> type is used.
/// </returns>
Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache);
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
bool IsMatch(Schema schema);
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
bool IsMatch(TypeResolution resolution);
}
/// <summary>
/// A deserializer builder configured with a reasonable set of default cases.
/// </summary>
public class BinaryDeserializerBuilder : IBinaryDeserializerBuilder
{
/// <summary>
/// A list of cases that the build methods will attempt to apply. If the first case does
/// not match, the next case will be tested, and so on.
/// </summary>
protected readonly IReadOnlyCollection<IBinaryDeserializerBuilderCase> Cases;
/// <summary>
/// A resolver to obtain type information from.
/// </summary>
protected readonly ITypeResolver Resolver;
/// <summary>
/// Creates a new deserializer builder.
/// </summary>
/// <param name="cases">
/// An optional collection of cases. If no case collection is provided, the default set will
/// be used.
/// </param>
/// <param name="codec">
/// A codec implementation that generated deserializers will use for read operations. If
/// no codec is provided, <see cref="BinaryCodec" /> will be used.
/// </param>
/// <param name="resolver">
/// A resolver to obtain type information from.
/// </param>
public BinaryDeserializerBuilder(IReadOnlyCollection<IBinaryDeserializerBuilderCase> cases = null, IBinaryCodec codec = null, ITypeResolver resolver = null)
{
Resolver = resolver ?? new DataContractResolver();
if (codec == null)
{
codec = new BinaryCodec();
}
Cases = cases ?? new List<IBinaryDeserializerBuilderCase>()
{
// logical types:
new DecimalDeserializerBuilderCase(codec),
new DurationDeserializerBuilderCase(codec),
new TimestampDeserializerBuilderCase(codec),
// primitives:
new BooleanDeserializerBuilderCase(codec),
new BytesDeserializerBuilderCase(codec),
new DoubleDeserializerBuilderCase(codec),
new FixedDeserializerBuilderCase(codec),
new FloatDeserializerBuilderCase(codec),
new IntegerDeserializerBuilderCase(codec),
new NullDeserializerBuilderCase(),
new StringDeserializerBuilderCase(codec),
// collections:
new ArrayDeserializerBuilderCase(codec, this),
new MapDeserializerBuilderCase(codec, this),
// enums:
new EnumDeserializerBuilderCase(codec),
// records:
new RecordDeserializerBuilderCase(this),
// unions:
new UnionDeserializerBuilderCase(codec, this)
};
}
/// <summary>
/// Builds a delegate that reads a serialized object from a stream.
/// </summary>
/// <typeparam name="T">
/// The type of object to be deserialized. If the type is a class or a struct, it must have
/// a parameterless public constructor.
/// </typeparam>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// An optional delegate cache. The cache can be used to provide custom implementations for
/// particular type-schema pairs, and it will also be populated as the delegate is built.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="UnsupportedSchemaException">
/// Thrown when the deserializer builder is unable to build a delegate for the schema.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when the deserializer builder is unable to build a delegate for the type.
/// </exception>
public virtual Func<Stream, T> BuildDelegate<T>(Schema schema, IDictionary<(Type, Schema), Delegate> cache = null)
{
if (cache == null)
{
cache = new Dictionary<(Type, Schema), Delegate>();
}
var resolution = Resolver.ResolveType(typeof(T));
if (cache.TryGetValue((resolution.Type, schema), out var existing))
{
return existing as Func<Stream, T>;
}
var candidates = Cases.Where(c => c.IsMatch(schema));
if (candidates.Count() == 0)
{
throw new UnsupportedSchemaException(schema, $"No deserializer builder case matched {schema.GetType().Name}.");
}
var match = candidates.FirstOrDefault(c => c.IsMatch(resolution));
if (match == null)
{
throw new UnsupportedTypeException(resolution.Type, $"No deserializer builder case matched {resolution.GetType().Name}.");
}
return match.BuildDelegate(resolution, schema, cache) as Func<Stream, T>;
}
/// <summary>
/// Builds a binary deserializer.
/// </summary>
/// <typeparam name="T">
/// The type of object to be deserialized. If the type is a class or a struct, it must have
/// a parameterless public constructor.
/// </typeparam>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <exception cref="UnsupportedSchemaException">
/// Thrown when the deserializer builder is unable to build a deserializer for the schema.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when the deserializer builder is unable to build a deserializer for the type.
/// </exception>
public virtual IBinaryDeserializer<T> BuildDeserializer<T>(Schema schema)
{
return new BinaryDeserializer<T>(BuildDelegate<T>(schema));
}
}
/// <summary>
/// A base deserializer builder case.
/// </summary>
public abstract class BinaryDeserializerBuilderCase : IBinaryDeserializerBuilderCase
{
/// <summary>
/// Builds a deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache. If a delegate is cached for a specific type-schema pair, that delegate
/// will be returned for all subsequent occurrences of the pair.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object. Since
/// this is not a typed method, the general <see cref="Delegate" /> type is used.
/// </returns>
public abstract Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache);
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
public abstract bool IsMatch(Schema schema);
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
public abstract bool IsMatch(TypeResolution resolution);
}
/// <summary>
/// A deserializer builder case that matches <see cref="ArraySchema" /> and attempts to map it
/// to enumerable types.
/// </summary>
public class ArrayDeserializerBuilderCase : BinaryDeserializerBuilderCase
{
/// <summary>
/// The codec that generated deserializers should use for read operations.
/// </summary>
protected readonly IBinaryCodec Codec;
/// <summary>
/// The deserializer builder to use to build item deserializers.
/// </summary>
protected readonly IBinaryDeserializerBuilder DeserializerBuilder;
/// <summary>
/// Creates a new array deserializer builder case.
/// </summary>
/// <param name="codec">
/// The codec that generated deserializers should use for read operations.
/// </param>
/// <param name="deserializerBuilder">
/// The deserializer builder to use to build item deserializers.
/// </param>
public ArrayDeserializerBuilderCase(IBinaryCodec codec, IBinaryDeserializerBuilder deserializerBuilder)
{
Codec = codec;
DeserializerBuilder = deserializerBuilder;
}
/// <summary>
/// Builds an array deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the schema is not an <see cref="ArraySchema" /> or the resolution is not an
/// <see cref="ArrayResolution" />.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when the resolved type is neither an array type nor a type assignable from
/// <see cref="List{T}" />.
/// </exception>
public override Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache)
{
if (!(resolution is ArrayResolution arrayResolution))
{
throw new ArgumentException("An array deserializer can only be built for an array resolution.");
}
if (!(schema is ArraySchema arraySchema))
{
throw new ArgumentException("An array deserializer can only be built for an array schema.");
}
var target = arrayResolution.Type;
var item = arrayResolution.ItemType;
var codec = Expression.Constant(Codec);
var stream = Expression.Parameter(typeof(Stream));
Expression result = null;
try
{
var build = typeof(IBinaryDeserializerBuilder)
.GetMethod(nameof(IBinaryDeserializerBuilder.BuildDelegate))
.MakeGenericMethod(item);
var readBlocks = typeof(IBinaryCodec)
.GetMethods()
.Single(m => m.Name == nameof(IBinaryCodec.ReadBlocks)
&& m.GetGenericArguments().Length == 1
)
.MakeGenericMethod(item);
result = Expression.Call(
codec,
readBlocks,
stream,
Expression.Constant(
build.Invoke(DeserializerBuilder, new object[] { arraySchema.Item, cache }),
typeof(Func<,>).MakeGenericType(typeof(Stream), item)
)
);
}
catch (TargetInvocationException indirect)
{
ExceptionDispatchInfo.Capture(indirect.InnerException).Throw();
}
var convert = typeof(Enumerable).GetMethods()
.Where(m => m.Name == (target.IsArray
? nameof(Enumerable.ToArray)
: nameof(Enumerable.ToList)
))
.Single()
.MakeGenericMethod(item);
if (!target.IsAssignableFrom(convert.ReturnType))
{
throw new UnsupportedTypeException(target, $"An array deserializer cannot be built for type {target.FullName}.");
}
result = Expression.ConvertChecked(Expression.Call(null, convert, result), target);
var lambda = Expression.Lambda(result, "array deserializer", new[] { stream });
var compiled = lambda.Compile();
cache.Add((target, schema), compiled);
return compiled;
}
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
/// <returns>
/// Whether the schema is an <see cref="ArraySchema" />.
/// </returns>
public override bool IsMatch(Schema schema)
{
return schema is ArraySchema;
}
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
/// <returns>
/// Whether the resolution is an <see cref="ArrayResolution" />.
/// </returns>
public override bool IsMatch(TypeResolution resolution)
{
return resolution is ArrayResolution;
}
}
/// <summary>
/// A deserializer builder case that matches <see cref="BooleanSchema" /> and attempts to map
/// it to any provided type.
/// </summary>
public class BooleanDeserializerBuilderCase : BinaryDeserializerBuilderCase
{
/// <summary>
/// The codec that generated deserializers should use for read operations.
/// </summary>
protected readonly IBinaryCodec Codec;
/// <summary>
/// Creates a new boolean deserializer builder case.
/// </summary>
/// <param name="codec">
/// The codec that generated deserializers should use for read operations.
/// </param>
public BooleanDeserializerBuilderCase(IBinaryCodec codec)
{
Codec = codec ?? throw new ArgumentNullException(nameof(codec), "Binary codec cannot be null.");
}
/// <summary>
/// Builds a boolean deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the schema is not a <see cref="BooleanSchema" />.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when no conversion from <see cref="bool" /> exists.
/// </exception>
public override Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache)
{
if (!(schema is BooleanSchema))
{
throw new ArgumentException("A boolean deserializer can only be built for a boolean schema.");
}
var source = typeof(bool);
var target = resolution.Type;
var codec = Expression.Constant(Codec);
var stream = Expression.Parameter(typeof(Stream));
var readValue = typeof(IBinaryCodec)
.GetMethod(nameof(IBinaryCodec.ReadBoolean));
Expression result = Expression.Call(codec, readValue, stream);
if (source != target)
{
try
{
result = Expression.ConvertChecked(result, target);
}
catch (InvalidOperationException inner)
{
throw new UnsupportedTypeException(target, $"A boolean deserializer cannot be built for type {target.FullName}.", inner);
}
}
var lambda = Expression.Lambda(result, "boolean deserializer", new[] { stream });
var compiled = lambda.Compile();
cache.Add((target, schema), compiled);
return compiled;
}
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
/// <returns>
/// Whether the schema is a <see cref="BooleanSchema" />.
/// </returns>
public override bool IsMatch(Schema schema)
{
return schema is BooleanSchema;
}
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
/// <returns>
/// Always true; this case will apply but fail if no conversion exists from <see cref="bool" />.
/// </returns>
public override bool IsMatch(TypeResolution resolution)
{
return true;
}
}
/// <summary>
/// A deserializer builder case that matches <see cref="BytesSchema" /> and attempts to map it
/// to any provided type.
/// </summary>
public class BytesDeserializerBuilderCase : BinaryDeserializerBuilderCase
{
/// <summary>
/// The codec that generated deserializers should use for read operations.
/// </summary>
protected readonly IBinaryCodec Codec;
/// <summary>
/// Creates a new variable-length bytes deserializer builder case.
/// </summary>
/// <param name="codec">
/// The codec that generated deserializers should use for read operations.
/// </param>
public BytesDeserializerBuilderCase(IBinaryCodec codec)
{
Codec = codec ?? throw new ArgumentNullException(nameof(codec), "Binary codec cannot be null.");
}
/// <summary>
/// Builds a variable-length bytes deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the schema is not a <see cref="BytesSchema" />.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when no conversion from <see cref="T:System.Byte[]" /> exists.
/// </exception>
public override Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache)
{
if (!(schema is BytesSchema))
{
throw new ArgumentException("A bytes deserializer can only be built for a bytes schema.");
}
var source = typeof(byte[]);
var target = resolution.Type;
var codec = Expression.Constant(Codec);
var stream = Expression.Parameter(typeof(Stream));
var readLength = typeof(IBinaryCodec)
.GetMethod(nameof(IBinaryCodec.ReadInteger));
Expression result = Expression.ConvertChecked(Expression.Call(codec, readLength, stream), typeof(int));
var readValue = typeof(IBinaryCodec)
.GetMethod(nameof(IBinaryCodec.Read));
result = Expression.Call(codec, readValue, stream, result);
if (source != target)
{
if (target == typeof(Guid) || target == typeof(Guid?))
{
var guidConstructor = typeof(Guid)
.GetConstructor(new[] { typeof(byte[]) });
result = Expression.New(guidConstructor, result);
}
try
{
result = Expression.ConvertChecked(result, target);
}
catch (InvalidOperationException inner)
{
throw new UnsupportedTypeException(target, $"A bytes deserializer cannot be built for type {target.FullName}.", inner);
}
}
var lambda = Expression.Lambda(result, "bytes deserializer", new[] { stream });
var compiled = lambda.Compile();
cache.Add((target, schema), compiled);
return compiled;
}
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
/// <returns>
/// Whether the schema is a <see cref="BytesSchema" />.
/// </returns>
public override bool IsMatch(Schema schema)
{
return schema is BytesSchema;
}
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
/// <returns>
/// Always true; this case will apply but fail if no conversion exists from <see cref="T:System.Byte[]" />.
/// </returns>
public override bool IsMatch(TypeResolution resolution)
{
return true;
}
}
/// <summary>
/// A deserializer builder case that matches <see cref="DecimalLogicalType" /> and attempts to
/// map it to any provided type.
/// </summary>
public class DecimalDeserializerBuilderCase : BinaryDeserializerBuilderCase
{
/// <summary>
/// The codec that generated deserializers should use for read operations.
/// </summary>
protected readonly IBinaryCodec Codec;
/// <summary>
/// Creates a new decimal deserializer builder case.
/// </summary>
/// <param name="codec">
/// The codec that generated deserializers should use for read operations.
/// </param>
public DecimalDeserializerBuilderCase(IBinaryCodec codec)
{
Codec = codec ?? throw new ArgumentNullException(nameof(codec), "Binary codec cannot be null.");
}
/// <summary>
/// Builds a decimal deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the schema is not a <see cref="BytesSchema" /> or a <see cref="FixedSchema "/>
/// with logical type <see cref="DecimalLogicalType" />.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when no conversion from <see cref="decimal" /> exists.
/// </exception>
public override Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache)
{
if (!(schema.LogicalType is DecimalLogicalType decimalLogicalType))
{
throw new ArgumentException("A decimal deserializer can only be built for schema with a decimal logical type.");
}
var precision = decimalLogicalType.Precision;
var scale = decimalLogicalType.Scale;
var source = typeof(decimal);
var target = resolution.Type;
var codec = Expression.Constant(Codec);
var stream = Expression.Parameter(typeof(Stream));
Expression result;
// figure out the size:
if (schema is BytesSchema)
{
var readLength = typeof(IBinaryCodec)
.GetMethod(nameof(IBinaryCodec.ReadInteger));
result = Expression.ConvertChecked(Expression.Call(codec, readLength, stream), typeof(int));
}
else if (schema is FixedSchema fixedSchema)
{
result = Expression.Constant(fixedSchema.Size);
}
else
{
throw new ArgumentException("A decimal deserializer can only be built for a bytes or a fixed schema.");
}
var readValue = typeof(IBinaryCodec)
.GetMethod(nameof(IBinaryCodec.Read));
// read the bytes:
result = Expression.Call(codec, readValue, stream, result);
// declare some variables for in-place transformation:
var bytes = Expression.Variable(typeof(byte[]));
var integer = Expression.Variable(typeof(BigInteger));
var integerConstructor = typeof(BigInteger)
.GetConstructor(new[] { typeof(byte[]) });
var abs = typeof(BigInteger)
.GetMethod(nameof(BigInteger.Abs), new[] { typeof(BigInteger) });
var ceil = typeof(Math)
.GetMethod(nameof(Math.Ceiling), new[] { typeof(double) });
var log = typeof(BigInteger)
.GetMethod(nameof(BigInteger.Log10), new[] { typeof(BigInteger) });
var max = typeof(Math)
.GetMethod(nameof(Math.Max), new[] { typeof(double), typeof(double) });
var pow = typeof(Math)
.GetMethod(nameof(Math.Pow), new[] { typeof(double), typeof(double) });
var reverse = typeof(Array)
.GetMethod(nameof(Array.Reverse), new[] { typeof(Array) });
result = Expression.Block(
new[] { bytes, integer },
// store the bytes in a variable:
Expression.Assign(bytes, result),
// BigInteger is little-endian, so reverse:
Expression.Call(null, reverse, bytes),
// create the BigInteger:
Expression.Assign(integer, Expression.New(integerConstructor, bytes)),
// arithmetic:
// var digits = Math.Ceiling(BigInteger.Log10(BigInteger.Abs(integer)));
// var truncated = integer - (integer % (BigInteger)Math.Pow(10, Math.Max(0, digits - precision)));
//
// return (decimal)truncated / (decimal)Math.Pow(10, scale);
Expression.Divide(
Expression.ConvertChecked(
Expression.Subtract(integer,
Expression.Modulo(integer,
Expression.ConvertChecked(
Expression.Call(null, pow, Expression.Constant(10.0),
Expression.Call(null, max, Expression.Constant(0.0),
Expression.Subtract(
Expression.Call(null, ceil,
Expression.Call(null, log,
Expression.Call(null, abs, integer))),
Expression.Constant((double)precision)))),
typeof(BigInteger)))),
typeof(decimal)),
Expression.Constant((decimal)Math.Pow(10, scale)))
);
if (source != target)
{
try
{
result = Expression.ConvertChecked(result, target);
}
catch (InvalidOperationException inner)
{
throw new UnsupportedTypeException(target, $"A decimal deserializer cannot be built for type {target.FullName}.", inner);
}
}
var lambda = Expression.Lambda(result, "decimal deserializer", new[] { stream });
var compiled = lambda.Compile();
cache.Add((target, schema), compiled);
return compiled;
}
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
/// <returns>
/// Whether the schema is a <see cref="BytesSchema" /> or a <see cref="FixedSchema "/> with
/// logical type <see cref="DecimalLogicalType" />.
/// </returns>
public override bool IsMatch(Schema schema)
{
return (schema is BytesSchema || schema is FixedSchema) && schema.LogicalType is DecimalLogicalType;
}
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
/// <returns>
/// Always true; this case will apply but fail if no conversion exists from <see cref="decimal" />.
/// </returns>
public override bool IsMatch(TypeResolution resolution)
{
return true;
}
}
/// <summary>
/// A deserializer builder case that matches <see cref="DoubleSchema" /> and attempts to map it
/// to any provided type.
/// </summary>
public class DoubleDeserializerBuilderCase : BinaryDeserializerBuilderCase
{
/// <summary>
/// The codec that generated deserializers should use for read operations.
/// </summary>
protected readonly IBinaryCodec Codec;
/// <summary>
/// Creates a new double deserializer builder case.
/// </summary>
/// <param name="codec">
/// The codec that generated deserializers should use for read operations.
/// </param>
public DoubleDeserializerBuilderCase(IBinaryCodec codec)
{
Codec = codec ?? throw new ArgumentNullException(nameof(codec), "Binary codec cannot be null.");
}
/// <summary>
/// Builds a double deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the schema is not a <see cref="DoubleSchema" />.
/// </exception>
/// <exception cref="UnsupportedTypeException">
/// Thrown when no conversion from <see cref="double" /> exists.
/// </exception>
public override Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache)
{
if (!(schema is DoubleSchema))
{
throw new ArgumentException("A double deserializer can only be built for a double schema.");
}
var source = typeof(double);
var target = resolution.Type;
var codec = Expression.Constant(Codec);
var stream = Expression.Parameter(typeof(Stream));
var readValue = typeof(IBinaryCodec)
.GetMethod(nameof(IBinaryCodec.ReadDouble));
Expression result = Expression.Call(codec, readValue, stream);
if (source != target)
{
try
{
result = Expression.ConvertChecked(result, target);
}
catch (InvalidOperationException inner)
{
throw new UnsupportedTypeException(target, $"A double deserializer cannot be built for type {target.FullName}.", inner);
}
}
var lambda = Expression.Lambda(result, "double deserializer", new[] { stream });
var compiled = lambda.Compile();
cache.Add((target, schema), compiled);
return compiled;
}
/// <summary>
/// Determines whether the case can be applied to a schema.
/// </summary>
/// <returns>
/// Whether the schema is a <see cref="DoubleSchema" />.
/// </returns>
public override bool IsMatch(Schema schema)
{
return schema is DoubleSchema;
}
/// <summary>
/// Determines whether the case can be applied to a type resolution.
/// </summary>
/// <returns>
/// Always true; this case will apply but fail if no conversion exists from <see cref="double" />.
/// </returns>
public override bool IsMatch(TypeResolution resolution)
{
return true;
}
}
/// <summary>
/// A deserializer builder case that matches <see cref="DurationLogicalType" /> and attempts to
/// map it to <see cref="TimeSpan" />.
/// </summary>
public class DurationDeserializerBuilderCase : BinaryDeserializerBuilderCase
{
/// <summary>
/// The codec that generated deserializers should use for read operations.
/// </summary>
protected readonly IBinaryCodec Codec;
/// <summary>
/// Creates a new duration deserializer builder case.
/// </summary>
/// <param name="codec">
/// The codec that generated deserializers should use for read operations.
/// </param>
public DurationDeserializerBuilderCase(IBinaryCodec codec)
{
Codec = codec ?? throw new ArgumentNullException(nameof(codec), "Binary codec cannot be null.");
}
/// <summary>
/// Builds a duration deserializer for a type-schema pair.
/// </summary>
/// <param name="resolution">
/// The resolution to obtain type information from.
/// </param>
/// <param name="schema">
/// The schema to map to the type.
/// </param>
/// <param name="cache">
/// A delegate cache.
/// </param>
/// <returns>
/// A function that accepts a <see cref="Stream" /> and returns a deserialized object.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the schema is not a <see cref="FixedSchema" /> with size 12 and logical
/// type <see cref="DurationLogicalType" /> or when the type is not <see cref="TimeSpan" />.
/// </exception>
public override Delegate BuildDelegate(TypeResolution resolution, Schema schema, IDictionary<(Type, Schema), Delegate> cache)
{
if (!(schema.LogicalType is DurationLogicalType))
{
throw new ArgumentException("A duration deserializer can only be built for a schema with a duration logical type.");
}
if (!(schema is FixedSchema fixedSchema && fixedSchema.Size == 12))
{
throw new ArgumentException("A duration deserializer can only be built for a fixed schema with size 12.");
}
var target = resolution.Type;
if (!(target == typeof(TimeSpan) || target == typeof(TimeSpan?)))
{
throw new ArgumentException($"A duration deserializer cannot be built for {target.Name}.");
}
Func<Stream, long> read = input =>
{
var bytes = Codec.Read(input, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
return BitConverter.ToUInt32(bytes, 0);
};
var codec = Expression.Constant(Codec);
var stream = Expression.Parameter(typeof(Stream));