This repository has been archived by the owner on May 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 266
/
StandardClassLibraryFormatters.cs
665 lines (561 loc) · 23 KB
/
StandardClassLibraryFormatters.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Utf8Json.Formatters.Internal;
using Utf8Json.Internal;
using System.Text.RegularExpressions;
#if NETSTANDARD
using System.Numerics;
using System.Threading.Tasks;
#endif
namespace Utf8Json.Formatters
{
// MEMO:should write/read base64 directly like corefxlab/System.Binary.Base64
// https://github.com/dotnet/corefxlab/tree/master/src/System.Binary.Base64/System/Binary
public sealed class ByteArrayFormatter : IJsonFormatter<byte[]>
{
public static readonly IJsonFormatter<byte[]> Default = new ByteArrayFormatter();
public void Serialize(ref JsonWriter writer, byte[] value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
writer.WriteString(Convert.ToBase64String(value, Base64FormattingOptions.None));
}
public byte[] Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;
var str = reader.ReadString();
return Convert.FromBase64String(str);
}
}
public sealed class ByteArraySegmentFormatter : IJsonFormatter<ArraySegment<byte>>
{
public static readonly IJsonFormatter<ArraySegment<byte>> Default = new ByteArraySegmentFormatter();
public void Serialize(ref JsonWriter writer, ArraySegment<byte> value, IJsonFormatterResolver formatterResolver)
{
if (value.Array == null) { writer.WriteNull(); return; }
writer.WriteString(Convert.ToBase64String(value.Array, value.Offset, value.Count, Base64FormattingOptions.None));
}
public ArraySegment<byte> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return default(ArraySegment<byte>);
var str = reader.ReadString();
var bytes = Convert.FromBase64String(str);
return new ArraySegment<byte>(bytes, 0, bytes.Length);
}
}
public sealed class NullableStringFormatter : IJsonFormatter<string>, IObjectPropertyNameFormatter<string>
{
public static readonly IJsonFormatter<string> Default = new NullableStringFormatter();
public void Serialize(ref JsonWriter writer, string value, IJsonFormatterResolver formatterResolver)
{
writer.WriteString(value);
}
public string Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
return reader.ReadString();
}
public void SerializeToPropertyName(ref JsonWriter writer, string value, IJsonFormatterResolver formatterResolver)
{
writer.WriteString(value);
}
public string DesrializeFromPropertyName(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
return reader.ReadString();
}
}
public sealed class NullableStringArrayFormatter : IJsonFormatter<string[]>
{
public static readonly NullableStringArrayFormatter Default = new NullableStringArrayFormatter();
public void Serialize(ref JsonWriter writer, string[] value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
}
else
{
writer.WriteBeginArray();
if (value.Length != 0)
{
writer.WriteString(value[0]);
}
for (int i = 1; i < value.Length; i++)
{
writer.WriteValueSeparator();
writer.WriteString(value[i]);
}
writer.WriteEndArray();
}
}
public string[] Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull())
{
return null;
}
else
{
reader.ReadIsBeginArrayWithVerify();
var array = new string[4];
var count = 0;
while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref count))
{
if (array.Length < count)
{
Array.Resize(ref array, count * 2);
}
array[count - 1] = reader.ReadString();
}
Array.Resize(ref array, count);
return array;
}
}
}
public sealed class CharFormatter : IJsonFormatter<char>
{
public static readonly CharFormatter Default = new CharFormatter();
// MEMO:can be improvement write directly
public void Serialize(ref JsonWriter writer, char value, IJsonFormatterResolver formatterResolver)
{
writer.WriteString(value.ToString(CultureInfo.InvariantCulture));
}
public char Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
return reader.ReadString()[0];
}
}
public sealed class NullableCharFormatter : IJsonFormatter<Char?>
{
public static readonly NullableCharFormatter Default = new NullableCharFormatter();
public void Serialize(ref JsonWriter writer, Char? value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
}
else
{
CharFormatter.Default.Serialize(ref writer, value.Value, formatterResolver);
}
}
public Char? Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull())
{
return null;
}
else
{
return CharFormatter.Default.Deserialize(ref reader, formatterResolver);
}
}
}
public sealed class CharArrayFormatter : IJsonFormatter<char[]>
{
public static readonly CharArrayFormatter Default = new CharArrayFormatter();
public void Serialize(ref JsonWriter writer, char[] value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
}
else
{
writer.WriteBeginArray();
if (value.Length != 0)
{
CharFormatter.Default.Serialize(ref writer, value[0], formatterResolver);
}
for (int i = 1; i < value.Length; i++)
{
writer.WriteValueSeparator();
CharFormatter.Default.Serialize(ref writer, value[i], formatterResolver);
}
writer.WriteEndArray();
}
}
public char[] Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull())
{
return null;
}
else
{
reader.ReadIsBeginArrayWithVerify();
var array = new char[4];
var count = 0;
while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref count))
{
if (array.Length < count)
{
Array.Resize(ref array, count * 2);
}
array[count - 1] = CharFormatter.Default.Deserialize(ref reader, formatterResolver);
}
Array.Resize(ref array, count);
return array;
}
}
}
public sealed class GuidFormatter : IJsonFormatter<Guid>
{
public static readonly IJsonFormatter<Guid> Default = new GuidFormatter();
public void Serialize(ref JsonWriter writer, Guid value, IJsonFormatterResolver formatterResolver)
{
writer.EnsureCapacity(38); // unsafe, control underlying buffer manually
writer.WriteRawUnsafe((byte)'\"');
var rawData = writer.GetBuffer();
new GuidBits(ref value).Write(rawData.Array, writer.CurrentOffset); // len = 36
writer.AdvanceOffset(36);
writer.WriteRawUnsafe((byte)'\"');
}
public Guid Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var segment = reader.ReadStringSegmentUnsafe();
return new GuidBits(ref segment).Value;
}
}
public sealed class DecimalFormatter : IJsonFormatter<decimal>
{
public static readonly IJsonFormatter<decimal> Default = new DecimalFormatter();
readonly bool serializeAsString;
public DecimalFormatter()
: this(false)
{
}
public DecimalFormatter(bool serializeAsString)
{
this.serializeAsString = serializeAsString;
}
public void Serialize(ref JsonWriter writer, decimal value, IJsonFormatterResolver formatterResolver)
{
if (serializeAsString)
{
writer.WriteString(value.ToString(CultureInfo.InvariantCulture));
}
else
{
// write as number format.
writer.WriteRaw(StringEncoding.UTF8.GetBytes(value.ToString(CultureInfo.InvariantCulture)));
}
}
public decimal Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var token = reader.GetCurrentJsonToken();
if (token == JsonToken.Number)
{
var number = reader.ReadNumberSegment();
return decimal.Parse(StringEncoding.UTF8.GetString(number.Array, number.Offset, number.Count), NumberStyles.Float, CultureInfo.InvariantCulture);
}
else if (token == JsonToken.String)
{
return decimal.Parse(reader.ReadString(), NumberStyles.Float, CultureInfo.InvariantCulture);
}
else
{
throw new InvalidOperationException("Invalid Json Token for DecimalFormatter:" + token);
}
}
}
public sealed class UriFormatter : IJsonFormatter<Uri>
{
public static readonly IJsonFormatter<Uri> Default = new UriFormatter();
public void Serialize(ref JsonWriter writer, Uri value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
}
else
{
writer.WriteString(value.ToString());
}
}
public Uri Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull())
{
return null;
}
else
{
return new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute);
}
}
}
public sealed class VersionFormatter : IJsonFormatter<Version>
{
public static readonly IJsonFormatter<Version> Default = new VersionFormatter();
public void Serialize(ref JsonWriter writer, Version value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
}
else
{
writer.WriteString(value.ToString());
}
}
public Version Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull())
{
return null;
}
else
{
return new Version(reader.ReadString());
}
}
}
public sealed class KeyValuePairFormatter<TKey, TValue> : IJsonFormatter<KeyValuePair<TKey, TValue>>
{
public void Serialize(ref JsonWriter writer, KeyValuePair<TKey, TValue> value, IJsonFormatterResolver formatterResolver)
{
writer.WriteRaw(StandardClassLibraryFormatterHelper.keyValuePairName[0]);
formatterResolver.GetFormatterWithVerify<TKey>().Serialize(ref writer, value.Key, formatterResolver);
writer.WriteRaw(StandardClassLibraryFormatterHelper.keyValuePairName[1]);
formatterResolver.GetFormatterWithVerify<TValue>().Serialize(ref writer, value.Value, formatterResolver);
writer.WriteEndObject();
}
public KeyValuePair<TKey, TValue> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) throw new InvalidOperationException("Data is Nil, KeyValuePair can not be null.");
TKey resultKey = default(TKey);
TValue resultValue = default(TValue);
reader.ReadIsBeginObjectWithVerify();
var count = 0;
while (!reader.ReadIsEndObjectWithSkipValueSeparator(ref count))
{
var keyString = reader.ReadPropertyNameSegmentRaw();
int key;
#if NETSTANDARD
StandardClassLibraryFormatterHelper.keyValuePairAutomata.TryGetValue(keyString, out key);
#else
StandardClassLibraryFormatterHelper.keyValuePairAutomata.TryGetValueSafe(keyString, out key);
#endif
switch (key)
{
case 0:
resultKey = formatterResolver.GetFormatterWithVerify<TKey>().Deserialize(ref reader, formatterResolver);
break;
case 1:
resultValue = formatterResolver.GetFormatterWithVerify<TValue>().Deserialize(ref reader, formatterResolver);
break;
default:
reader.ReadNextBlock();
break;
}
}
return new KeyValuePair<TKey, TValue>(resultKey, resultValue);
}
}
public sealed class StringBuilderFormatter : IJsonFormatter<StringBuilder>
{
public static readonly IJsonFormatter<StringBuilder> Default = new StringBuilderFormatter();
public void Serialize(ref JsonWriter writer, StringBuilder value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
writer.WriteString(value.ToString());
}
public StringBuilder Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;
return new StringBuilder(reader.ReadString());
}
}
// BitArray can be represents other format...
public sealed class BitArrayFormatter : IJsonFormatter<BitArray>
{
public static readonly IJsonFormatter<BitArray> Default = new BitArrayFormatter();
public void Serialize(ref JsonWriter writer, BitArray value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
writer.WriteBeginArray();
for (int i = 0; i < value.Length; i++)
{
if (i != 0) writer.WriteValueSeparator();
writer.WriteBoolean(value[i]);
}
writer.WriteEndArray();
}
public BitArray Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;
reader.ReadIsBeginArrayWithVerify();
var c = 0;
var buffer = new ArrayBuffer<bool>(4);
while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref c))
{
buffer.Add(reader.ReadBoolean());
}
return new BitArray(buffer.ToArray());
}
}
public sealed class TypeFormatter : IJsonFormatter<Type>
{
public static readonly TypeFormatter Default = new TypeFormatter();
#if NETSTANDARD
static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+", RegexOptions.Compiled);
#else
static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+");
#endif
bool serializeAssemblyQualifiedName;
bool deserializeSubtractAssemblyQualifiedName;
bool throwOnError;
public TypeFormatter()
: this(true, true, true)
{
}
public TypeFormatter(bool serializeAssemblyQualifiedName, bool deserializeSubtractAssemblyQualifiedName, bool throwOnError)
{
this.serializeAssemblyQualifiedName = serializeAssemblyQualifiedName;
this.deserializeSubtractAssemblyQualifiedName = deserializeSubtractAssemblyQualifiedName;
this.throwOnError = throwOnError;
}
public void Serialize(ref JsonWriter writer, Type value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
if (serializeAssemblyQualifiedName)
{
writer.WriteString(value.AssemblyQualifiedName);
}
else
{
writer.WriteString(value.FullName);
}
}
public Type Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;
var s = reader.ReadString();
if (deserializeSubtractAssemblyQualifiedName)
{
s = SubtractFullNameRegex.Replace(s, "");
}
return Type.GetType(s, throwOnError);
}
}
#if NETSTANDARD
public sealed class BigIntegerFormatter : IJsonFormatter<BigInteger>
{
public static readonly IJsonFormatter<BigInteger> Default = new BigIntegerFormatter();
public void Serialize(ref JsonWriter writer, BigInteger value, IJsonFormatterResolver formatterResolver)
{
// JSON.NET writes Integer format, not compatible.
writer.WriteString(value.ToString(CultureInfo.InvariantCulture));
}
public BigInteger Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var s = reader.ReadString();
return BigInteger.Parse(s, CultureInfo.InvariantCulture);
}
}
// Convert to [Real, Imaginary]
public sealed class ComplexFormatter : IJsonFormatter<Complex>
{
public static readonly IJsonFormatter<Complex> Default = new ComplexFormatter();
public void Serialize(ref JsonWriter writer, Complex value, IJsonFormatterResolver formatterResolver)
{
writer.WriteBeginArray();
writer.WriteDouble(value.Real);
writer.WriteValueSeparator();
writer.WriteDouble(value.Imaginary);
writer.WriteEndArray();
}
public Complex Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
reader.ReadIsBeginArrayWithVerify();
var real = reader.ReadDouble();
reader.ReadIsValueSeparatorWithVerify();
var imaginary = reader.ReadDouble();
reader.ReadIsEndArrayWithVerify();
return new Complex(real, imaginary);
}
}
public sealed class LazyFormatter<T> : IJsonFormatter<Lazy<T>>
{
public void Serialize(ref JsonWriter writer, Lazy<T> value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
formatterResolver.GetFormatterWithVerify<T>().Serialize(ref writer, value.Value, formatterResolver);
}
public Lazy<T> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;
// deserialize immediately(no delay, because capture byte[] causes memory leak)
var v = formatterResolver.GetFormatterWithVerify<T>().Deserialize(ref reader, formatterResolver);
return new Lazy<T>(() => v);
}
}
public sealed class TaskUnitFormatter : IJsonFormatter<Task>
{
public static readonly IJsonFormatter<Task> Default = new TaskUnitFormatter();
static readonly Task CompletedTask = Task.FromResult<object>(null);
public void Serialize(ref JsonWriter writer, Task value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
value.Wait(); // wait!
writer.WriteNull();
}
public Task Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (!reader.ReadIsNull()) throw new InvalidOperationException("Invalid input");
return CompletedTask;
}
}
public sealed class TaskValueFormatter<T> : IJsonFormatter<Task<T>>
{
public void Serialize(ref JsonWriter writer, Task<T> value, IJsonFormatterResolver formatterResolver)
{
if (value == null) { writer.WriteNull(); return; }
// value.Result -> wait...!
formatterResolver.GetFormatterWithVerify<T>().Serialize(ref writer, value.Result, formatterResolver);
}
public Task<T> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.ReadIsNull()) return null;
var v = formatterResolver.GetFormatterWithVerify<T>().Deserialize(ref reader, formatterResolver);
return Task.FromResult(v);
}
}
public sealed class ValueTaskFormatter<T> : IJsonFormatter<ValueTask<T>>
{
public void Serialize(ref JsonWriter writer, ValueTask<T> value, IJsonFormatterResolver formatterResolver)
{
// value.Result -> wait...!
formatterResolver.GetFormatterWithVerify<T>().Serialize(ref writer, value.Result, formatterResolver);
}
public ValueTask<T> Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
var v = formatterResolver.GetFormatterWithVerify<T>().Deserialize(ref reader, formatterResolver);
return new ValueTask<T>(v);
}
}
#endif
}
namespace Utf8Json.Formatters.Internal
{
internal static class StandardClassLibraryFormatterHelper
{
internal static readonly byte[][] keyValuePairName;
internal static readonly AutomataDictionary keyValuePairAutomata;
static StandardClassLibraryFormatterHelper()
{
keyValuePairName = new byte[][]
{
JsonWriter.GetEncodedPropertyNameWithBeginObject("Key"),
JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator("Value"),
};
keyValuePairAutomata = new AutomataDictionary
{
{JsonWriter.GetEncodedPropertyNameWithoutQuotation("Key"), 0 },
{JsonWriter.GetEncodedPropertyNameWithoutQuotation("Value"), 1 },
};
}
}
}