-
Notifications
You must be signed in to change notification settings - Fork 253
/
InlineSerializer.cs
3812 lines (3032 loc) · 139 KB
/
InlineSerializer.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 Sigil.NonGeneric;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Jil.Common;
using Jil.SerializeDynamic;
namespace Jil.Serialize
{
class InlineSerializer<ForType>
{
public static bool ReorderMembers = true;
public static bool UseCustomIntegerToString = true;
public static bool SkipDateTimeMathMethods = true;
public static bool UseCustomISODateFormatting = true;
public static bool UseFastLists = true;
public static bool UseFastArrays = true;
public static bool UseFastGuids = true;
public static bool AllocationlessDictionaries = true;
public static bool PropagateConstants = true;
public static bool UseCustomWriteIntUnrolled = true;
public static bool UseCustomRFC1123DateTimeFormatting = true;
static string CharBuffer = "char_buffer";
internal const int CharBufferSize = 36;
internal const int RecursionLimit = 50;
static Dictionary<char, string> CharacterEscapes =
new Dictionary<char, string>
{
{ '\\', @"\\" },
{ '"', @"\""" },
{ '\u0000', @"\u0000" },
{ '\u0001', @"\u0001" },
{ '\u0002', @"\u0002" },
{ '\u0003', @"\u0003" },
{ '\u0004', @"\u0004" },
{ '\u0005', @"\u0005" },
{ '\u0006', @"\u0006" },
{ '\u0007', @"\u0007" },
{ '\u0008', @"\b" },
{ '\u0009', @"\t" },
{ '\u000A', @"\n" },
{ '\u000B', @"\u000B" },
{ '\u000C', @"\f" },
{ '\u000D', @"\r" },
{ '\u000E', @"\u000E" },
{ '\u000F', @"\u000F" },
{ '\u0010', @"\u0010" },
{ '\u0011', @"\u0011" },
{ '\u0012', @"\u0012" },
{ '\u0013', @"\u0013" },
{ '\u0014', @"\u0014" },
{ '\u0015', @"\u0015" },
{ '\u0016', @"\u0016" },
{ '\u0017', @"\u0017" },
{ '\u0018', @"\u0018" },
{ '\u0019', @"\u0019" },
{ '\u001A', @"\u001A" },
{ '\u001B', @"\u001B" },
{ '\u001C', @"\u001C" },
{ '\u001D', @"\u001D" },
{ '\u001E', @"\u001E" },
{ '\u001F', @"\u001F" }
};
private readonly Type RecursionLookupOptionsType; // This is a type that implements ISerializeOptions and has an empty, public constructor
private readonly bool ExcludeNulls;
private readonly bool PrettyPrint;
private readonly bool JSONP;
private readonly DateTimeFormat DateFormat;
private readonly bool IncludeInherited;
private readonly UnspecifiedDateTimeKindBehavior UnspecifiedDateTimeBehavior;
private Dictionary<Type, Sigil.Local> RecursiveTypes;
private Emit Emit;
private readonly bool CallOutOnPossibleDynamic;
private readonly bool BuildingToString;
internal InlineSerializer(Type recursionLookupOptionsType, bool pretty, bool excludeNulls, bool jsonp, DateTimeFormat dateFormat, bool includeInherited, UnspecifiedDateTimeKindBehavior dateTimeBehavior, bool callOutOnPossibleDynamic, bool buildToString)
{
RecursionLookupOptionsType = recursionLookupOptionsType;
PrettyPrint = pretty;
ExcludeNulls = excludeNulls;
JSONP = jsonp;
DateFormat = dateFormat;
IncludeInherited = includeInherited;
UnspecifiedDateTimeBehavior = dateTimeBehavior;
CallOutOnPossibleDynamic = callOutOnPossibleDynamic;
BuildingToString = buildToString;
}
void LoadProperty(PropertyInfo prop)
{
var getMtd = prop.GetMethod;
if (getMtd.IsVirtual)
{
Emit.CallVirtual(getMtd);
}
else
{
Emit.Call(getMtd);
}
}
static MethodInfo TextWriter_WriteString = typeof(TextWriter).GetMethod("Write", new [] { typeof(string) });
static MethodInfo ThunkWriter_WriteString = typeof(ThunkWriter).GetMethod("Write", new[] { typeof(string) });
static MethodInfo ThunkWriter_WriteCommonConstant = typeof(ThunkWriter).GetMethod("WriteCommonConstant", new[] { typeof(ConstantString_Common) });
static MethodInfo ThunkWriter_WriteFormatingContant = typeof(ThunkWriter).GetMethod("WriteFormattingConstant", new[] { typeof(ConstantString_Formatting) });
static MethodInfo ThunkWriter_WriteMinConstant = typeof(ThunkWriter).GetMethod("WriteMinConstant", new[] { typeof(ConstantString_Min) });
static MethodInfo ThunkWriter_WriteValueConstant = typeof(ThunkWriter).GetMethod("WriteValueConstant", new[] { typeof(ConstantString_Value) });
static MethodInfo ThunkWriter_Write000EscapeConstant = typeof(ThunkWriter).GetMethod("Write000EscapeConstant", new[] { typeof(ConstantString_000Escape) });
static MethodInfo ThunkWriter_Write001EscapeConstant = typeof(ThunkWriter).GetMethod("Write001EscapeConstant", new[] { typeof(ConstantString_001Escape) });
static MethodInfo ThunkWriter_WriteDayOfWeek = typeof(ThunkWriter).GetMethod("WriteDayOfWeek", new[] { typeof(ConstantString_DaysOfWeek) });
void WriteString(string str)
{
if (BuildingToString)
{
Emit.LoadArgument(0); // ThunkWriter*
ConstantString_Common constStr;
if (ThunkWriter.IsConstantCommonString(str, out constStr))
{
Emit.LoadConstant((int)constStr); // ThunkWriter* int
Emit.Call(ThunkWriter_WriteCommonConstant); // --empty--
}
else
{
ConstantString_Formatting formattingConstString;
if (ThunkWriter.IsConstantFormattingString(str, out formattingConstString))
{
Emit.LoadConstant((ushort)formattingConstString); // ThinkWriter* ushort
Emit.Call(ThunkWriter_WriteFormatingContant); // --empty--
}
else
{
ConstantString_Min minConstString;
if (ThunkWriter.IsConstantMinString(str, out minConstString))
{
Emit.LoadConstant((ushort)minConstString); // ThunkWriter* ushort
Emit.Call(ThunkWriter_WriteMinConstant); // --empty--
}
else
{
ConstantString_Value valConstString;
if (ThunkWriter.IsConstantValueString(str, out valConstString))
{
Emit.LoadConstant((ushort)valConstString); // ThunkWriter* ushort
Emit.Call(ThunkWriter_WriteValueConstant); // --empty--
}
else
{
ConstantString_000Escape e000ConstString;
if (ThunkWriter.IsConstant000EscapeString(str, out e000ConstString))
{
Emit.LoadConstant((byte)e000ConstString); // ThunkWriter* byte
Emit.Call(ThunkWriter_Write000EscapeConstant); // --empty--
}
else
{
ConstantString_001Escape e001ConstString;
if (ThunkWriter.IsConstant001EscapeString(str, out e001ConstString))
{
Emit.LoadConstant((byte)e001ConstString); // ThunkWriter* byte
Emit.Call(ThunkWriter_Write001EscapeConstant); // --empty--
}
else
{
ConstantString_DaysOfWeek dayOfWeek;
if (ThunkWriter.IsConstantDaysOfWeek(str, out dayOfWeek))
{
Emit.LoadConstant((byte)dayOfWeek); // ThunkWriter* byte
Emit.Call(ThunkWriter_WriteDayOfWeek); // --empty--
}
else
{
Emit.LoadConstant(str); // ThunkWriter* string
Emit.Call(ThunkWriter_WriteString); // --empty--
}
}
}
}
}
}
}
}
else
{
Emit.LoadArgument(0); // TextWriter
Emit.LoadConstant(str); // TextWriter string
Emit.CallVirtual(TextWriter_WriteString); // --empty--
}
}
void LineBreakAndIndent()
{
const int precalcLimit = 10;
var done = Emit.DefineLabel();
var labels = Enumerable.Range(0, precalcLimit).Select(i => Emit.DefineLabel()).ToArray();
Emit.LoadArgument(2); // int
Emit.Switch(labels); // --empty--
// default case
using (var count = Emit.DeclareLocal<int>())
{
WriteString("\n");
var loop = Emit.DefineLabel();
Emit.LoadArgument(2); // int
Emit.StoreLocal(count); // --empty--
Emit.MarkLabel(loop);
Emit.LoadLocal(count); // int
Emit.BranchIfFalse(done); // --empty--
WriteString(" "); // --empty--
Emit.LoadLocal(count); // int
Emit.LoadConstant(-1); // int -1
Emit.Add(); // (int-1)
Emit.StoreLocal(count); // --empty-
Emit.Branch(loop);
}
for (var i = 0; i < labels.Length; i++)
{
var breakAndIndent = "\n" + new string(' ', i);
Emit.MarkLabel(labels[i]); // --empty--
WriteString(breakAndIndent); // --empty--
Emit.Branch(done); // --empty--
}
Emit.MarkLabel(done); // --empty--
}
void IncreaseIndent()
{
// We only need to track this if
// - we're pretty printing
// - or infinite recursion is possible
if (PrettyPrint || RecursiveTypes.Count != 0)
{
Emit.LoadArgument(2); // indent
Emit.LoadConstant(1); // indent 1
Emit.Add(); // (indent+1)
Emit.StoreArgument(2); // --empty--
}
}
void DecreaseIndent()
{
// We only need to track this if
// - we're pretty printing
// - or infinite recursion is possible
if (PrettyPrint || RecursiveTypes.Count != 0)
{
Emit.LoadArgument(2); // indent
Emit.LoadConstant(-1); // indent -1
Emit.Add(); // (indent-1)
Emit.StoreArgument(2); // --empty--
}
if (PrettyPrint)
{
LineBreakAndIndent();
}
}
List<MemberInfo> OrderMembersForAccess(Type forType, Dictionary<Type, Sigil.Local> recursiveTypes)
{
var flags = BindingFlags.Public | BindingFlags.Instance;
if (!IncludeInherited)
{
flags |= BindingFlags.DeclaredOnly;
}
var props = forType.GetProperties(flags).Where(p => p.GetMethod != null && p.GetIndexParameters().Length == 0);
var fields = forType.GetFields(flags);
var members = props.Cast<MemberInfo>().Concat(fields).Where(f => f.ShouldUseMember());
if (forType.IsValueType)
{
return members.ToList();
}
// This order appears to be the "best" for access speed purposes
var ret =
!ReorderMembers ?
members :
Utils.IdealMemberOrderForWriting(forType, recursiveTypes.Keys, members);
return ret.ToList();
}
void WriteConstantMember(MemberInfo member, bool prependComma)
{
string stringEquiv;
if (PrettyPrint)
{
stringEquiv = "\"" + member.GetSerializationName().JsonEscape(JSONP) + "\": ";
}
else
{
stringEquiv = "\"" + member.GetSerializationName().JsonEscape(JSONP) + "\":";
}
if (prependComma)
{
stringEquiv = "," + stringEquiv;
}
stringEquiv += member.GetConstantJSONStringEquivalent(JSONP);
WriteString(stringEquiv);
}
void WriteMember(MemberInfo member, Sigil.Local inLocal = null)
{
// Stack is empty
var asField = member as FieldInfo;
var asProp = member as PropertyInfo;
if (asField == null && asProp == null) throw new ConstructionException("Encountered a serializable member that is neither a field nor a property: " + member);
var serializingType = asField != null ? asField.FieldType : asProp.PropertyType;
// It's a list or dictionary, go and build that code
if (serializingType.IsListType() || serializingType.IsDictionaryType() || serializingType.IsReadOnlyListType() || serializingType.IsReadOnlyDictionaryType())
{
if (inLocal != null)
{
Emit.LoadLocal(inLocal);
}
else
{
Emit.LoadArgument(1);
}
if (asField != null)
{
Emit.LoadField(asField);
}
if (asProp != null)
{
LoadProperty(asProp);
}
using (var loc = Emit.DeclareLocal(serializingType))
{
Emit.StoreLocal(loc);
if (serializingType.IsListType() || serializingType.IsReadOnlyListType())
{
WriteList(serializingType, loc);
return;
}
if (serializingType.IsDictionaryType() || serializingType.IsReadOnlyDictionaryType())
{
WriteDictionary(serializingType, loc);
return;
}
throw new Exception("Shouldn't be possible");
}
}
var isRecursive = RecursiveTypes.ContainsKey(serializingType);
if (isRecursive)
{
Emit.LoadLocal(RecursiveTypes[serializingType]); // Action<TextWriter, serializingType>
}
// Only put this on the stack if we'll need it
var preloadTextWriter =
serializingType.IsPrimitiveType() ||
(serializingType.IsEnum && member.ShouldConvertEnum(serializingType)) ||
isRecursive ||
serializingType.IsNullableType();
if (preloadTextWriter)
{
Emit.LoadArgument(0); // TextWriter
}
if (inLocal == null)
{
if (member.DeclaringType.IsValueType)
{
Emit.LoadArgumentAddress(1); // TextWriter obj*
}
else
{
Emit.LoadArgument(1); // TextWriter obj
}
}
else
{
if (inLocal.LocalType.IsValueType)
{
Emit.LoadLocalAddress(inLocal); // TextWriter obj*
}
else
{
Emit.LoadLocal(inLocal); // TextWriter obj
}
}
if (asField != null)
{
Emit.LoadField(asField); // TextWriter field
}
if (asProp != null)
{
LoadProperty(asProp); // TextWriter prop
}
if (isRecursive)
{
// Stack is:
// - serializingType
// - TextWriter
// - Action<TextWriter, serializingType>
Emit.LoadArgument(2); // Action<> TextWriter serializingType int
Type recursiveAct;
if (BuildingToString)
{
recursiveAct = typeof(StringThunkDelegate<>).MakeGenericType(serializingType);
}
else
{
recursiveAct = typeof(Action<,,>).MakeGenericType(typeof(TextWriter), serializingType, typeof(int));
}
var invoke = recursiveAct.GetMethod("Invoke");
Emit.Call(invoke);
return;
}
if (serializingType.IsPrimitiveType())
{
WritePrimitive(serializingType, quotesNeedHandling: true);
return;
}
if (serializingType.IsNullableType())
{
WriteNullable(serializingType, quotesNeedHandling: true);
return;
}
if (serializingType.IsEnum)
{
Type convertEnumTo;
if (member.ShouldConvertEnum(serializingType, out convertEnumTo))
{
var underlying = Enum.GetUnderlyingType(serializingType);
Emit.Convert(underlying);
if (underlying != convertEnumTo)
{
Emit.Convert(convertEnumTo);
}
WritePrimitive(convertEnumTo, quotesNeedHandling: true);
return;
}
WriteEnum(serializingType, popTextWriter: false);
return;
}
using (var loc = Emit.DeclareLocal(serializingType))
{
Emit.StoreLocal(loc); // TextWriter;
if (serializingType.IsEnumerableType())
{
WriteEnumerable(serializingType, loc);
return;
}
WriteObject(serializingType, loc);
}
}
void WriteNullable(Type nullableType, bool quotesNeedHandling)
{
// Top of stack is
// - nullable
// - TextWriter
var hasValue = nullableType.GetProperty("HasValue");
var value = nullableType.GetProperty("Value");
var underlyingType = nullableType.GetUnderlyingType();
var done = Emit.DefineLabel();
using (var loc = Emit.DeclareLocal(nullableType))
{
var notNull = Emit.DefineLabel();
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter nullableType*
LoadProperty(hasValue); // TextWriter bool
Emit.BranchIfTrue(notNull); // TextWriter
Emit.Pop(); // --empty--
WriteString("null"); // --empty--
Emit.Branch(done); // --empty--
Emit.MarkLabel(notNull); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter nullableType*
LoadProperty(value); // TextValue value
}
if (underlyingType.IsPrimitiveType())
{
WritePrimitive(underlyingType, quotesNeedHandling);
}
else
{
if (underlyingType.IsEnum)
{
WriteEnum(underlyingType, popTextWriter: true);
}
else
{
using (var loc = Emit.DeclareLocal(underlyingType))
{
Emit.StoreLocal(loc); // TextWriter
if (RecursiveTypes.ContainsKey(underlyingType))
{
Type act;
if (BuildingToString)
{
act = typeof(StringThunkDelegate<>).MakeGenericType(underlyingType);
}
else
{
act = typeof(Action<,,>).MakeGenericType(typeof(TextWriter), underlyingType, typeof(int));
}
var invoke = act.GetMethod("Invoke");
Emit.Pop(); // --empty--
Emit.LoadLocal(RecursiveTypes[underlyingType]); // Action<TextWriter, underlyingType>
Emit.LoadArgument(0); // Action<,> TextWriter
Emit.LoadLocal(loc); // Action<,> TextWriter value
Emit.LoadArgument(2); // Action<,> TextWriter value int
Emit.Call(invoke); // --empty--
}
else
{
if (underlyingType.IsListType())
{
WriteList(underlyingType, loc);
}
else
{
if (underlyingType.IsDictionaryType())
{
WriteDictionary(underlyingType, loc);
}
else
{
if (underlyingType.IsEnumerableType())
{
WriteEnumerable(underlyingType, loc);
}
else
{
Emit.Pop();
WriteObject(underlyingType, loc);
}
}
}
}
}
}
}
Emit.MarkLabel(done);
}
void WriteMicrosoftStyleDateTime()
{
// top of stack:
// - DateTime
// - TextWriter
using (var loc = Emit.DeclareLocal<DateTime>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTime*
}
if (!SkipDateTimeMathMethods)
{
var subtractMtd = typeof(DateTime).GetMethod("Subtract", new[] { typeof(DateTime) });
var totalMs = typeof(TimeSpan).GetProperty("TotalMilliseconds");
var dtCons = typeof(DateTime).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(DateTimeKind) });
Emit.LoadConstant(1970); // TextWriter DateTime* 1970
Emit.LoadConstant(1); // TextWriter DateTime* 1970 1
Emit.LoadConstant(1); // TextWriter DateTime* 1970 1 1
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0 0
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0 0 0
Emit.LoadConstant((int)DateTimeKind.Utc); // TextWriter DateTime* 1970 1 1 0 0 0 Utc
Emit.NewObject(dtCons); // TextWriter DateTime* DateTime*
Emit.Call(subtractMtd); // TextWriter TimeSpan
using (var loc = Emit.DeclareLocal<TimeSpan>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter TimeSpan*
}
LoadProperty(totalMs); // TextWriter double
Emit.Convert<long>(); // TextWriter int
WriteString("\"\\/Date("); // TextWriter int
WritePrimitive(typeof(long), quotesNeedHandling: false); // --empty--
WriteString(")\\/\""); // --empty--
return;
}
var getTicks = typeof(DateTime).GetProperty("Ticks");
LoadProperty(getTicks); // TextWriter long
Emit.LoadConstant(621355968000000000L); // TextWriter long (Unix Epoch Ticks long)
Emit.Subtract(); // TextWriter long
Emit.LoadConstant(10000L); // TextWriter long 10000
Emit.Divide(); // TextWriter long
WriteString("\"\\/Date("); // TextWriter int
WritePrimitive(typeof(long), quotesNeedHandling: false); // --empty--
WriteString(")\\/\""); // --empty--
}
void WriteMillisecondsStyleDateTime()
{
using (var loc = Emit.DeclareLocal<DateTime>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTime*
}
if (!SkipDateTimeMathMethods)
{
var subtractMtd = typeof(DateTime).GetMethod("Subtract", new[] { typeof(DateTime) });
var totalMs = typeof(TimeSpan).GetProperty("TotalMilliseconds");
var dtCons = typeof(DateTime).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(DateTimeKind) });
Emit.LoadConstant(1970); // TextWriter DateTime* 1970
Emit.LoadConstant(1); // TextWriter DateTime* 1970 1
Emit.LoadConstant(1); // TextWriter DateTime* 1970 1 1
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0 0
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0 0 0
Emit.LoadConstant((int)DateTimeKind.Utc); // TextWriter DateTime* 1970 1 1 0 0 0 Utc
Emit.NewObject(dtCons); // TextWriter DateTime* DateTime*
Emit.Call(subtractMtd); // TextWriter TimeSpan
using (var loc = Emit.DeclareLocal<TimeSpan>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter TimeSpan*
}
LoadProperty(totalMs); // TextWriter double
Emit.Convert<long>(); // TextWriter int
WritePrimitive(typeof(long), quotesNeedHandling: false); // --empty--
return;
}
var getTicks = typeof(DateTime).GetProperty("Ticks");
LoadProperty(getTicks); // TextWriter long
Emit.LoadConstant(621355968000000000L); // TextWriter long (Unix Epoch Ticks long)
Emit.Subtract(); // TextWriter long
Emit.LoadConstant(10000L); // TextWriter long 10000
Emit.Divide(); // TextWriter long
WritePrimitive(typeof(long), quotesNeedHandling: false); // --empty--
}
void WriteSecondsStyleDateTime()
{
using (var loc = Emit.DeclareLocal<DateTime>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTime*
}
if (!SkipDateTimeMathMethods)
{
var subtractMtd = typeof(DateTime).GetMethod("Subtract", new[] { typeof(DateTime) });
var totalS = typeof(TimeSpan).GetProperty("TotalSeconds");
var dtCons = typeof(DateTime).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(DateTimeKind) });
Emit.LoadConstant(1970); // TextWriter DateTime* 1970
Emit.LoadConstant(1); // TextWriter DateTime* 1970 1
Emit.LoadConstant(1); // TextWriter DateTime* 1970 1 1
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0 0
Emit.LoadConstant(0); // TextWriter DateTime* 1970 1 1 0 0 0
Emit.LoadConstant((int)DateTimeKind.Utc); // TextWriter DateTime* 1970 1 1 0 0 0 Utc
Emit.NewObject(dtCons); // TextWriter DateTime* DateTime*
Emit.Call(subtractMtd); // TextWriter TimeSpan
using (var loc = Emit.DeclareLocal<TimeSpan>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter TimeSpan*
}
LoadProperty(totalS); // TextWriter double
Emit.Convert<long>(); // TextWriter int
WritePrimitive(typeof(long), quotesNeedHandling: false); // --empty--
return;
}
var getTicks = typeof(DateTime).GetProperty("Ticks");
LoadProperty(getTicks); // TextWriter long
Emit.LoadConstant(621355968000000000L); // TextWriter long (Unix Epoch Ticks long)
Emit.Subtract(); // TextWriter long
Emit.LoadConstant(10000000L); // TextWriter long 10000000
Emit.Divide(); // TextWriter long
WritePrimitive(typeof(long), quotesNeedHandling: false); // --empty--
}
void WriteISO8601StyleDateTime()
{
// top of stack is
// - DateTime
// - TextWriter
if (!UseCustomISODateFormatting)
{
var toString = typeof(DateTime).GetMethod("ToString", new[] { typeof(string) });
using (var loc = Emit.DeclareLocal<DateTime>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTime*
}
Emit.LoadConstant("\\\"yyyy-MM-ddTHH:mm:ssZ\\\""); // TextWriter DateTime* string
Emit.Call(toString); // TextWriter string
if (BuildingToString)
{
Emit.Call(ThunkWriter_WriteString); // --empty--
}
else
{
Emit.CallVirtual(TextWriter_WriteString); // --empty--
}
return;
}
Emit.LoadLocal(CharBuffer); // TextWriter DateTime char[]
Emit.Call(Methods.GetCustomISO8601ToString(BuildingToString)); // --empty--
}
static readonly MethodInfo DateTime_ToString = typeof(DateTime).GetMethod("ToString", new[] { typeof(string) });
void WriteRFC1123StyleDateTime()
{
// top of stack is
// - DateTime
// - TextWriter
if (!UseCustomRFC1123DateTimeFormatting)
{
using (var loc = Emit.DeclareLocal<DateTime>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // DateTime* TextWriter
}
Emit.LoadConstant("R"); // string DateTime* TextWriter
Emit.Call(DateTime_ToString); // string TextWriter
WritePrimitive(typeof(string), quotesNeedHandling: true); // --empty--
return;
}
Emit.Call(Methods.GetCustomRFC1123(BuildingToString)); // --empty--
}
static readonly MethodInfo DateTimeOffset_UtcDateTime = typeof(DateTimeOffset).GetProperty("UtcDateTime").GetMethod;
static readonly MethodInfo DateTimeOffset_DateTime = typeof(DateTimeOffset).GetProperty("DateTime").GetMethod;
static readonly MethodInfo DateTimeOffset_Offset = typeof(DateTimeOffset).GetProperty("Offset").GetMethod;
static readonly MethodInfo TimeSpan_Hours = typeof(TimeSpan).GetProperty("Hours").GetMethod;
static readonly MethodInfo TimeSpan_Minutes = typeof(TimeSpan).GetProperty("Minutes").GetMethod;
void WriteDateTimeOffset()
{
// top of stack:
// - DateTimeOffset
// - TextWriter
if (DateFormat == DateTimeFormat.SecondsSinceUnixEpoch ||
DateFormat == DateTimeFormat.MillisecondsSinceUnixEpoch ||
DateFormat == DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch ||
DateFormat == DateTimeFormat.RFC1123)
{
// No room for an offset in these forms, so just re-use DateTime logic
// One wrinkle, the Microsoft-style *can* include an offset... but the seconds
// count is still from UTC. Since the offset isn't necessary, we're not
// going to emit it because it's a waste of time.
using (var loc = Emit.DeclareLocal<DateTimeOffset>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTimeOffset*
}
Emit.Call(DateTimeOffset_UtcDateTime); // TextWriter DateTime
WriteDateTime();
return;
}
if (DateFormat == DateTimeFormat.ISO8601)
{
// Get the DateTime equivalent and the offset on the stack
using (var dtoLoc = Emit.DeclareLocal<DateTimeOffset>())
using (var tsLoc = Emit.DeclareLocal<TimeSpan>())
{
Emit.StoreLocal(dtoLoc); // TextWriter
Emit.LoadLocalAddress(dtoLoc); // TextWriter DateTimeOffset*
Emit.Call(DateTimeOffset_DateTime); // TextWriter DateTime
Emit.LoadLocalAddress(dtoLoc); // TextWriter DateTime DateTimeOffset*
Emit.Call(DateTimeOffset_Offset); // TextWriter DateTime TimeSpan
Emit.StoreLocal(tsLoc); // TextWriter DateTime
Emit.LoadLocalAddress(tsLoc); // TextWriter DateTime TimeSpan*
Emit.Call(TimeSpan_Hours); // TextWriter DateTime int
Emit.LoadLocalAddress(tsLoc); // TextWriter DateTime int TimeSpan*
Emit.Call(TimeSpan_Minutes); // TextWriter DateTime int int
}
Emit.LoadLocal(CharBuffer);
Emit.Call(Methods.GetCustomISO8601WithOffsetToString(BuildingToString));
return;
}
throw new ConstructionException("Unexpected DateTimeFormat: " + DateFormat);
}
static readonly MethodInfo TimeSpan_TotalSeconds = typeof(TimeSpan).GetProperty("TotalSeconds").GetMethod;
static readonly MethodInfo TimeSpan_TotalMilliseconds = typeof(TimeSpan).GetProperty("TotalMilliseconds").GetMethod;
void WriteTimeSpan()
{
// top of stack:
// - TimeSpan
// - TextWriter
if (DateFormat == DateTimeFormat.SecondsSinceUnixEpoch)
{
using (var loc = Emit.DeclareLocal<TimeSpan>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter TimeSpan*
}
Emit.Call(TimeSpan_TotalSeconds); // TextWriter double
WritePrimitive(typeof(double), false); // --empty--
return;
}
if (DateFormat == DateTimeFormat.MillisecondsSinceUnixEpoch)
{
using (var loc = Emit.DeclareLocal<TimeSpan>())
{
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter TimeSpan*
}
Emit.Call(TimeSpan_TotalMilliseconds); // TextWriter double
WritePrimitive(typeof(double), false); // --empty--
return;
}
Emit.LoadLocal(CharBuffer); // TextWriter TimeSpan char[]
switch(DateFormat)
{
case DateTimeFormat.ISO8601:
Emit.Call(Methods.GetWriteTimeSpanISO8601(BuildingToString)); // --empty--
return;
case DateTimeFormat.RFC1123:
case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch:
Emit.Call(Methods.GetWriteTimeSpanMicrosoft(BuildingToString)); // --empty--
return;
default: throw new Exception("Unexpected DateTimeFormat [" + DateFormat + "]");
}
}
void WriteDateTime()
{
// top of stack:
// - DateTime
// - TextWriter
var toUniversalTime = typeof(DateTime).GetMethod("ToUniversalTime");
var kind = typeof(DateTime).GetProperty("Kind");
var specifyKind = typeof(DateTime).GetMethod("SpecifyKind", BindingFlags.Public | BindingFlags.Static);
using (var loc = Emit.DeclareLocal<DateTime>())
{
var noChange = Emit.DefineLabel();
var convertToKind = UnspecifiedDateTimeBehavior == UnspecifiedDateTimeKindBehavior.IsLocal ? DateTimeKind.Local : DateTimeKind.Utc;
Emit.StoreLocal(loc); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTime*
LoadProperty(kind); // TextWriter DateTimeKind
Emit.LoadConstant((int)DateTimeKind.Unspecified); // TextWriter DateTimeKind DateTimeKind
Emit.UnsignedBranchIfNotEqual(noChange); // TextWriter
Emit.LoadLocal(loc); // TextWriter DateTime
Emit.LoadConstant((int)convertToKind); // TextWriter DateTime DateTimeKind
Emit.Call(specifyKind); // TextWriter DateTime
Emit.StoreLocal(loc); // TextWriter
Emit.MarkLabel(noChange); // TextWriter
Emit.LoadLocalAddress(loc); // TextWriter DateTime*
Emit.Call(toUniversalTime); // TextWriter DateTime
}
switch (DateFormat)
{
case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch:
WriteMicrosoftStyleDateTime();
return;
case DateTimeFormat.MillisecondsSinceUnixEpoch:
WriteMillisecondsStyleDateTime();
return;
case DateTimeFormat.SecondsSinceUnixEpoch:
WriteSecondsStyleDateTime();
return;
case DateTimeFormat.ISO8601:
WriteISO8601StyleDateTime();
return;
case DateTimeFormat.RFC1123:
WriteRFC1123StyleDateTime();
return;
default:
throw new ConstructionException("Unexpected DateFormat: " + DateFormat);
}
}
void CallWriteInt()
{
if (UseCustomWriteIntUnrolled)
{
Emit.Call(Methods.GetCustomWriteIntUnrolledSigned(BuildingToString));
}
else
{
Emit.Call(Methods.GetCustomWriteInt(BuildingToString));
}
}
void CallWriteUInt()