-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathUtf8JsonReader.cs
More file actions
2562 lines (2272 loc) · 97.5 KB
/
Utf8JsonReader.cs
File metadata and controls
2562 lines (2272 loc) · 97.5 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text.Json
{
/// <summary>
/// Provides a high-performance API for forward-only, read-only access to the UTF-8 encoded JSON text.
/// It processes the text sequentially with no caching and adheres strictly to the JSON RFC
/// by default (https://tools.ietf.org/html/rfc8259). When it encounters invalid JSON, it throws
/// a JsonException with basic error information like line number and byte position on the line.
/// Since this type is a ref struct, it does not directly support async. However, it does provide
/// support for reentrancy to read incomplete data, and continue reading once more data is presented.
/// To be able to set max depth while reading OR allow skipping comments, create an instance of
/// <see cref="JsonReaderState"/> and pass that in to the reader.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public ref partial struct Utf8JsonReader
{
private ReadOnlySpan<byte> _buffer;
private readonly bool _isFinalBlock;
private readonly bool _isInputSequence;
private long _lineNumber;
private long _bytePositionInLine;
// bytes consumed in the current segment (not token)
private int _consumed;
private bool _inObject;
private bool _isNotPrimitive;
private JsonTokenType _tokenType;
private JsonTokenType _previousTokenType;
private JsonReaderOptions _readerOptions;
private BitStack _bitStack;
private long _totalConsumed;
private bool _isLastSegment;
private readonly bool _isMultiSegment;
private bool _trailingCommaBeforeComment;
private SequencePosition _nextPosition;
private SequencePosition _currentPosition;
private readonly ReadOnlySequence<byte> _sequence;
private bool IsLastSpan => _isFinalBlock && (!_isMultiSegment || _isLastSegment);
internal ReadOnlySequence<byte> OriginalSequence => _sequence;
internal ReadOnlySpan<byte> OriginalSpan => _sequence.IsEmpty ? _buffer : default;
internal readonly int ValueLength => HasValueSequence ? checked((int)ValueSequence.Length) : ValueSpan.Length;
/// <summary>
/// Gets the value of the last processed token as a ReadOnlySpan<byte> slice
/// of the input payload. If the JSON is provided within a ReadOnlySequence<byte>
/// and the slice that represents the token value fits in a single segment, then
/// <see cref="ValueSpan"/> will contain the sliced value since it can be represented as a span.
/// Otherwise, the <see cref="ValueSequence"/> will contain the token value.
/// </summary>
/// <remarks>
/// If <see cref="HasValueSequence"/> is true, <see cref="ValueSpan"/> contains useless data, likely for
/// a previous single-segment token. Therefore, only access <see cref="ValueSpan"/> if <see cref="HasValueSequence"/> is false.
/// Otherwise, the token value must be accessed from <see cref="ValueSequence"/>.
/// </remarks>
public ReadOnlySpan<byte> ValueSpan { get; private set; }
/// <summary>
/// Returns the total amount of bytes consumed by the <see cref="Utf8JsonReader"/> so far
/// for the current instance of the <see cref="Utf8JsonReader"/> with the given UTF-8 encoded input text.
/// </summary>
public readonly long BytesConsumed
{
get
{
#if DEBUG
if (!_isInputSequence)
{
Debug.Assert(_totalConsumed == 0);
}
#endif
return _totalConsumed + _consumed;
}
}
/// <summary>
/// Returns the index that the last processed JSON token starts at
/// within the given UTF-8 encoded input text, skipping any white space.
/// </summary>
/// <remarks>
/// For JSON strings (including property names), this points to before the start quote.
/// For comments, this points to before the first comment delimiter (i.e. '/').
/// </remarks>
public long TokenStartIndex { get; private set; }
/// <summary>
/// Tracks the recursive depth of the nested objects / arrays within the JSON text
/// processed so far. This provides the depth of the current token.
/// </summary>
public readonly int CurrentDepth
{
get
{
int readerDepth = _bitStack.CurrentDepth;
if (TokenType == JsonTokenType.StartArray || TokenType == JsonTokenType.StartObject)
{
Debug.Assert(readerDepth >= 1);
readerDepth--;
}
return readerDepth;
}
}
internal bool IsInArray => !_inObject;
/// <summary>
/// Gets the type of the last processed JSON token in the UTF-8 encoded JSON text.
/// </summary>
public readonly JsonTokenType TokenType => _tokenType;
/// <summary>
/// Lets the caller know which of the two 'Value' properties to read to get the
/// token value. For input data within a ReadOnlySpan<byte> this will
/// always return false. For input data within a ReadOnlySequence<byte>, this
/// will only return true if the token value straddles more than a single segment and
/// hence couldn't be represented as a span.
/// </summary>
public bool HasValueSequence { get; private set; }
/// <summary>
/// Lets the caller know whether the current <see cref="ValueSpan" /> or <see cref="ValueSequence"/> properties
/// contain escape sequences per RFC 8259 section 7, and therefore require unescaping before being consumed.
/// </summary>
public bool ValueIsEscaped { get; private set; }
/// <summary>
/// Returns the mode of this instance of the <see cref="Utf8JsonReader"/>.
/// True when the reader was constructed with the input span containing the entire data to process.
/// False when the reader was constructed knowing that the input span may contain partial data with more data to follow.
/// </summary>
public readonly bool IsFinalBlock => _isFinalBlock;
/// <summary>
/// Gets the value of the last processed token as a ReadOnlySpan<byte> slice
/// of the input payload. If the JSON is provided within a ReadOnlySequence<byte>
/// and the slice that represents the token value fits in a single segment, then
/// <see cref="ValueSpan"/> will contain the sliced value since it can be represented as a span.
/// Otherwise, the <see cref="ValueSequence"/> will contain the token value.
/// </summary>
/// <remarks>
/// If <see cref="HasValueSequence"/> is false, <see cref="ValueSequence"/> contains useless data, likely for
/// a previous multi-segment token. Therefore, only access <see cref="ValueSequence"/> if <see cref="HasValueSequence"/> is true.
/// Otherwise, the token value must be accessed from <see cref="ValueSpan"/>.
/// </remarks>
public ReadOnlySequence<byte> ValueSequence { get; private set; }
/// <summary>
/// Returns the current <see cref="SequencePosition"/> within the provided UTF-8 encoded
/// input ReadOnlySequence<byte>. If the <see cref="Utf8JsonReader"/> was constructed
/// with a ReadOnlySpan<byte> instead, this will always return a default <see cref="SequencePosition"/>.
/// </summary>
public readonly SequencePosition Position
{
get
{
if (_isInputSequence)
{
Debug.Assert(_currentPosition.GetObject() != null);
return _sequence.GetPosition(_consumed, _currentPosition);
}
return default;
}
}
/// <summary>
/// Returns the current snapshot of the <see cref="Utf8JsonReader"/> state which must
/// be captured by the caller and passed back in to the <see cref="Utf8JsonReader"/> ctor with more data.
/// Unlike the <see cref="Utf8JsonReader"/>, which is a ref struct, the state can survive
/// across async/await boundaries and hence this type is required to provide support for reading
/// in more data asynchronously before continuing with a new instance of the <see cref="Utf8JsonReader"/>.
/// </summary>
public readonly JsonReaderState CurrentState => new JsonReaderState
{
_lineNumber = _lineNumber,
_bytePositionInLine = _bytePositionInLine,
_inObject = _inObject,
_isNotPrimitive = _isNotPrimitive,
_valueIsEscaped = ValueIsEscaped,
_trailingCommaBeforeComment = _trailingCommaBeforeComment,
_tokenType = _tokenType,
_previousTokenType = _previousTokenType,
_readerOptions = _readerOptions,
_bitStack = _bitStack,
};
/// <summary>
/// Constructs a new <see cref="Utf8JsonReader"/> instance.
/// </summary>
/// <param name="jsonData">The ReadOnlySpan<byte> containing the UTF-8 encoded JSON text to process.</param>
/// <param name="isFinalBlock">True when the input span contains the entire data to process.
/// Set to false only if it is known that the input span contains partial data with more data to follow.</param>
/// <param name="state">If this is the first call to the ctor, pass in a default state. Otherwise,
/// capture the state from the previous instance of the <see cref="Utf8JsonReader"/> and pass that back.</param>
/// <remarks>
/// Since this type is a ref struct, it is a stack-only type and all the limitations of ref structs apply to it.
/// This is the reason why the ctor accepts a <see cref="JsonReaderState"/>.
/// </remarks>
public Utf8JsonReader(ReadOnlySpan<byte> jsonData, bool isFinalBlock, JsonReaderState state)
{
_buffer = jsonData;
_isFinalBlock = isFinalBlock;
_isInputSequence = false;
_lineNumber = state._lineNumber;
_bytePositionInLine = state._bytePositionInLine;
_inObject = state._inObject;
_isNotPrimitive = state._isNotPrimitive;
ValueIsEscaped = state._valueIsEscaped;
_trailingCommaBeforeComment = state._trailingCommaBeforeComment;
_tokenType = state._tokenType;
_previousTokenType = state._previousTokenType;
_readerOptions = state._readerOptions;
if (_readerOptions.MaxDepth == 0)
{
_readerOptions.MaxDepth = JsonReaderOptions.DefaultMaxDepth; // If max depth is not set, revert to the default depth.
}
_bitStack = state._bitStack;
_consumed = 0;
TokenStartIndex = 0;
_totalConsumed = 0;
_isLastSegment = _isFinalBlock;
_isMultiSegment = false;
ValueSpan = ReadOnlySpan<byte>.Empty;
_currentPosition = default;
_nextPosition = default;
_sequence = default;
HasValueSequence = false;
ValueSequence = ReadOnlySequence<byte>.Empty;
}
/// <summary>
/// Constructs a new <see cref="Utf8JsonReader"/> instance.
/// </summary>
/// <param name="jsonData">The ReadOnlySpan<byte> containing the UTF-8 encoded JSON text to process.</param>
/// <param name="options">Defines the customized behavior of the <see cref="Utf8JsonReader"/>
/// that is different from the JSON RFC (for example how to handle comments or maximum depth allowed when reading).
/// By default, the <see cref="Utf8JsonReader"/> follows the JSON RFC strictly (i.e. comments within the JSON are invalid) and reads up to a maximum depth of 64.</param>
/// <remarks>
/// <para>
/// Since this type is a ref struct, it is a stack-only type and all the limitations of ref structs apply to it.
/// </para>
/// <para>
/// This assumes that the entire JSON payload is passed in (equivalent to <see cref="IsFinalBlock"/> = true)
/// </para>
/// </remarks>
public Utf8JsonReader(ReadOnlySpan<byte> jsonData, JsonReaderOptions options = default)
: this(jsonData, isFinalBlock: true, new JsonReaderState(options))
{
}
/// <summary>
/// Read the next JSON token from input source.
/// </summary>
/// <returns>True if the token was read successfully, else false.</returns>
/// <exception cref="JsonException">
/// Thrown when an invalid JSON token is encountered according to the JSON RFC
/// or if the current depth exceeds the recursive limit set by the max depth.
/// </exception>
public bool Read()
{
bool retVal = _isMultiSegment ? ReadMultiSegment() : ReadSingleSegment();
if (!retVal)
{
if (_isFinalBlock && TokenType == JsonTokenType.None)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedJsonTokens);
}
}
return retVal;
}
/// <summary>
/// Skips the children of the current JSON token.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when the reader was given partial data with more data to follow (i.e. <see cref="IsFinalBlock"/> is false).
/// </exception>
/// <exception cref="JsonException">
/// Thrown when an invalid JSON token is encountered while skipping, according to the JSON RFC,
/// or if the current depth exceeds the recursive limit set by the max depth.
/// </exception>
/// <remarks>
/// When <see cref="TokenType"/> is <see cref="JsonTokenType.PropertyName" />, the reader first moves to the property value.
/// When <see cref="TokenType"/> (originally, or after advancing) is <see cref="JsonTokenType.StartObject" /> or
/// <see cref="JsonTokenType.StartArray" />, the reader advances to the matching
/// <see cref="JsonTokenType.EndObject" /> or <see cref="JsonTokenType.EndArray" />.
///
/// For all other token types, the reader does not move. After the next call to <see cref="Read"/>, the reader will be at
/// the next value (when in an array), the next property name (when in an object), or the end array/object token.
/// </remarks>
public void Skip()
{
if (!_isFinalBlock)
{
ThrowHelper.ThrowInvalidOperationException_CannotSkipOnPartial();
}
SkipHelper();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SkipHelper()
{
Debug.Assert(_isFinalBlock);
if (TokenType == JsonTokenType.PropertyName)
{
bool result = Read();
// Since _isFinalBlock == true here, and the JSON token is not a primitive value or comment.
// Read() is guaranteed to return true OR throw for invalid/incomplete data.
Debug.Assert(result);
}
if (TokenType == JsonTokenType.StartObject || TokenType == JsonTokenType.StartArray)
{
int depth = CurrentDepth;
do
{
bool result = Read();
// Since _isFinalBlock == true here, and the JSON token is not a primitive value or comment.
// Read() is guaranteed to return true OR throw for invalid/incomplete data.
Debug.Assert(result);
}
while (depth < CurrentDepth);
}
}
/// <summary>
/// Tries to skip the children of the current JSON token.
/// </summary>
/// <returns>True if there was enough data for the children to be skipped successfully, else false.</returns>
/// <exception cref="JsonException">
/// Thrown when an invalid JSON token is encountered while skipping, according to the JSON RFC,
/// or if the current depth exceeds the recursive limit set by the max depth.
/// </exception>
/// <remarks>
/// <para>
/// If the reader did not have enough data to completely skip the children of the current token,
/// it will be reset to the state it was in before the method was called.
/// </para>
/// <para>
/// When <see cref="TokenType"/> is <see cref="JsonTokenType.PropertyName" />, the reader first moves to the property value.
/// When <see cref="TokenType"/> (originally, or after advancing) is <see cref="JsonTokenType.StartObject" /> or
/// <see cref="JsonTokenType.StartArray" />, the reader advances to the matching
/// <see cref="JsonTokenType.EndObject" /> or <see cref="JsonTokenType.EndArray" />.
///
/// For all other token types, the reader does not move. After the next call to <see cref="Read"/>, the reader will be at
/// the next value (when in an array), the next property name (when in an object), or the end array/object token.
/// </para>
/// </remarks>
public bool TrySkip()
{
if (_isFinalBlock)
{
SkipHelper();
return true;
}
return TrySkipHelper();
}
private bool TrySkipHelper()
{
Debug.Assert(!_isFinalBlock);
Utf8JsonReader restore = this;
if (TokenType == JsonTokenType.PropertyName)
{
if (!Read())
{
goto Restore;
}
}
if (TokenType == JsonTokenType.StartObject || TokenType == JsonTokenType.StartArray)
{
int depth = CurrentDepth;
do
{
if (!Read())
{
goto Restore;
}
}
while (depth < CurrentDepth);
}
return true;
Restore:
this = restore;
return false;
}
/// <summary>
/// Compares the UTF-8 encoded text to the unescaped JSON token value in the source and returns true if they match.
/// </summary>
/// <param name="utf8Text">The UTF-8 encoded text to compare against.</param>
/// <returns>True if the JSON token value in the source matches the UTF-8 encoded look up text.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to find a text match on a JSON token that is not a string
/// (i.e. other than <see cref="JsonTokenType.String"/> or <see cref="JsonTokenType.PropertyName"/>).
/// <seealso cref="TokenType" />
/// </exception>
/// <remarks>
/// <para>
/// If the look up text is invalid UTF-8 text, the method will return false since you cannot have
/// invalid UTF-8 within the JSON payload.
/// </para>
/// <para>
/// The comparison of the JSON token value in the source and the look up text is done by first unescaping the JSON value in source,
/// if required. The look up text is matched as is, without any modifications to it.
/// </para>
/// </remarks>
public readonly bool ValueTextEquals(ReadOnlySpan<byte> utf8Text)
{
if (!IsTokenTypeString(TokenType))
{
ThrowHelper.ThrowInvalidOperationException_ExpectedStringComparison(TokenType);
}
return TextEqualsHelper(utf8Text);
}
/// <summary>
/// Compares the string text to the unescaped JSON token value in the source and returns true if they match.
/// </summary>
/// <param name="text">The text to compare against.</param>
/// <returns>True if the JSON token value in the source matches the look up text.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to find a text match on a JSON token that is not a string
/// (i.e. other than <see cref="JsonTokenType.String"/> or <see cref="JsonTokenType.PropertyName"/>).
/// <seealso cref="TokenType" />
/// </exception>
/// <remarks>
/// <para>
/// If the look up text is invalid UTF-8 text, the method will return false since you cannot have
/// invalid UTF-8 within the JSON payload.
/// </para>
/// <para>
/// The comparison of the JSON token value in the source and the look up text is done by first unescaping the JSON value in source,
/// if required. The look up text is matched as is, without any modifications to it.
/// </para>
/// </remarks>
public readonly bool ValueTextEquals(string? text)
{
return ValueTextEquals(text.AsSpan());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private readonly bool TextEqualsHelper(ReadOnlySpan<byte> otherUtf8Text)
{
if (HasValueSequence)
{
return CompareToSequence(otherUtf8Text);
}
if (ValueIsEscaped)
{
return UnescapeAndCompare(otherUtf8Text);
}
return otherUtf8Text.SequenceEqual(ValueSpan);
}
/// <summary>
/// Compares the text to the unescaped JSON token value in the source and returns true if they match.
/// </summary>
/// <param name="text">The text to compare against.</param>
/// <returns>True if the JSON token value in the source matches the look up text.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if trying to find a text match on a JSON token that is not a string
/// (i.e. other than <see cref="JsonTokenType.String"/> or <see cref="JsonTokenType.PropertyName"/>).
/// <seealso cref="TokenType" />
/// </exception>
/// <remarks>
/// <para>
/// If the look up text is invalid or incomplete UTF-16 text (i.e. unpaired surrogates), the method will return false
/// since you cannot have invalid UTF-16 within the JSON payload.
/// </para>
/// <para>
/// The comparison of the JSON token value in the source and the look up text is done by first unescaping the JSON value in source,
/// if required. The look up text is matched as is, without any modifications to it.
/// </para>
/// </remarks>
public readonly bool ValueTextEquals(ReadOnlySpan<char> text)
{
if (!IsTokenTypeString(TokenType))
{
ThrowHelper.ThrowInvalidOperationException_ExpectedStringComparison(TokenType);
}
if (MatchNotPossible(text.Length))
{
return false;
}
byte[]? otherUtf8TextArray = null;
scoped Span<byte> otherUtf8Text;
int length = checked(text.Length * JsonConstants.MaxExpansionFactorWhileTranscoding);
if (length > JsonConstants.StackallocByteThreshold)
{
otherUtf8TextArray = ArrayPool<byte>.Shared.Rent(length);
otherUtf8Text = otherUtf8TextArray;
}
else
{
otherUtf8Text = stackalloc byte[JsonConstants.StackallocByteThreshold];
}
OperationStatus status = JsonWriterHelper.ToUtf8(text, otherUtf8Text, out int written);
Debug.Assert(status != OperationStatus.DestinationTooSmall);
bool result;
if (status == OperationStatus.InvalidData)
{
result = false;
}
else
{
Debug.Assert(status == OperationStatus.Done);
result = TextEqualsHelper(otherUtf8Text.Slice(0, written));
}
if (otherUtf8TextArray != null)
{
otherUtf8Text.Slice(0, written).Clear();
ArrayPool<byte>.Shared.Return(otherUtf8TextArray);
}
return result;
}
private readonly bool CompareToSequence(ReadOnlySpan<byte> other)
{
Debug.Assert(HasValueSequence);
if (ValueIsEscaped)
{
return UnescapeSequenceAndCompare(other);
}
ReadOnlySequence<byte> localSequence = ValueSequence;
Debug.Assert(!localSequence.IsSingleSegment);
if (localSequence.Length != other.Length)
{
return false;
}
int matchedSoFar = 0;
foreach (ReadOnlyMemory<byte> memory in localSequence)
{
ReadOnlySpan<byte> span = memory.Span;
if (other.Slice(matchedSoFar).StartsWith(span))
{
matchedSoFar += span.Length;
}
else
{
return false;
}
}
return true;
}
private readonly bool UnescapeAndCompare(ReadOnlySpan<byte> other)
{
Debug.Assert(!HasValueSequence);
ReadOnlySpan<byte> localSpan = ValueSpan;
if (localSpan.Length < other.Length || localSpan.Length / JsonConstants.MaxExpansionFactorWhileEscaping > other.Length)
{
return false;
}
int idx = localSpan.IndexOf(JsonConstants.BackSlash);
Debug.Assert(idx != -1);
if (!other.StartsWith(localSpan.Slice(0, idx)))
{
return false;
}
return JsonReaderHelper.UnescapeAndCompare(localSpan.Slice(idx), other.Slice(idx));
}
private readonly bool UnescapeSequenceAndCompare(ReadOnlySpan<byte> other)
{
Debug.Assert(HasValueSequence);
Debug.Assert(!ValueSequence.IsSingleSegment);
ReadOnlySequence<byte> localSequence = ValueSequence;
long sequenceLength = localSequence.Length;
// The JSON token value will at most shrink by 6 when unescaping.
// If it is still larger than the lookup string, there is no value in unescaping and doing the comparison.
if (sequenceLength < other.Length || sequenceLength / JsonConstants.MaxExpansionFactorWhileEscaping > other.Length)
{
return false;
}
int matchedSoFar = 0;
bool result = false;
foreach (ReadOnlyMemory<byte> memory in localSequence)
{
ReadOnlySpan<byte> span = memory.Span;
int idx = span.IndexOf(JsonConstants.BackSlash);
if (idx != -1)
{
if (!other.Slice(matchedSoFar).StartsWith(span.Slice(0, idx)))
{
break;
}
matchedSoFar += idx;
other = other.Slice(matchedSoFar);
localSequence = localSequence.Slice(matchedSoFar);
if (localSequence.IsSingleSegment)
{
result = JsonReaderHelper.UnescapeAndCompare(localSequence.First.Span, other);
}
else
{
result = JsonReaderHelper.UnescapeAndCompare(localSequence, other);
}
break;
}
if (!other.Slice(matchedSoFar).StartsWith(span))
{
break;
}
matchedSoFar += span.Length;
}
return result;
}
// Returns true if the TokenType is a primitive string "value", i.e. PropertyName or String
// Otherwise, return false.
private static bool IsTokenTypeString(JsonTokenType tokenType)
{
return tokenType == JsonTokenType.PropertyName || tokenType == JsonTokenType.String;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private readonly bool MatchNotPossible(int charTextLength)
{
if (HasValueSequence)
{
return MatchNotPossibleSequence(charTextLength);
}
int sourceLength = ValueSpan.Length;
// Transcoding from UTF-16 to UTF-8 will change the length by somwhere between 1x and 3x.
// Unescaping the token value will at most shrink its length by 6x.
// There is no point incurring the transcoding/unescaping/comparing cost if:
// - The token value is smaller than charTextLength
// - The token value needs to be transcoded AND unescaped and it is more than 6x larger than charTextLength
// - For an ASCII UTF-16 characters, transcoding = 1x, escaping = 6x => 6x factor
// - For non-ASCII UTF-16 characters within the BMP, transcoding = 2-3x, but they are represented as a single escaped hex value, \uXXXX => 6x factor
// - For non-ASCII UTF-16 characters outside of the BMP, transcoding = 4x, but the surrogate pair (2 characters) are represented by 16 bytes \uXXXX\uXXXX => 6x factor
// - The token value needs to be transcoded, but NOT escaped and it is more than 3x larger than charTextLength
// - For an ASCII UTF-16 characters, transcoding = 1x,
// - For non-ASCII UTF-16 characters within the BMP, transcoding = 2-3x,
// - For non-ASCII UTF-16 characters outside of the BMP, transcoding = 2x, (surrogate pairs - 2 characters transcode to 4 UTF-8 bytes)
if (sourceLength < charTextLength
|| sourceLength / (ValueIsEscaped ? JsonConstants.MaxExpansionFactorWhileEscaping : JsonConstants.MaxExpansionFactorWhileTranscoding) > charTextLength)
{
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private readonly bool MatchNotPossibleSequence(int charTextLength)
{
long sourceLength = ValueSequence.Length;
if (sourceLength < charTextLength
|| sourceLength / (ValueIsEscaped ? JsonConstants.MaxExpansionFactorWhileEscaping : JsonConstants.MaxExpansionFactorWhileTranscoding) > charTextLength)
{
return true;
}
return false;
}
private void StartObject()
{
if (_bitStack.CurrentDepth >= _readerOptions.MaxDepth)
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ObjectDepthTooLarge);
_bitStack.PushTrue();
ValueSpan = _buffer.Slice(_consumed, 1);
_consumed++;
_bytePositionInLine++;
_tokenType = JsonTokenType.StartObject;
_inObject = true;
}
private void EndObject()
{
if (!_inObject || _bitStack.CurrentDepth <= 0)
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.MismatchedObjectArray, JsonConstants.CloseBrace);
if (_trailingCommaBeforeComment)
{
if (!_readerOptions.AllowTrailingCommas)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd);
}
_trailingCommaBeforeComment = false;
}
_tokenType = JsonTokenType.EndObject;
ValueSpan = _buffer.Slice(_consumed, 1);
UpdateBitStackOnEndToken();
}
private void StartArray()
{
if (_bitStack.CurrentDepth >= _readerOptions.MaxDepth)
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ArrayDepthTooLarge);
_bitStack.PushFalse();
ValueSpan = _buffer.Slice(_consumed, 1);
_consumed++;
_bytePositionInLine++;
_tokenType = JsonTokenType.StartArray;
_inObject = false;
}
private void EndArray()
{
if (_inObject || _bitStack.CurrentDepth <= 0)
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.MismatchedObjectArray, JsonConstants.CloseBracket);
if (_trailingCommaBeforeComment)
{
if (!_readerOptions.AllowTrailingCommas)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd);
}
_trailingCommaBeforeComment = false;
}
_tokenType = JsonTokenType.EndArray;
ValueSpan = _buffer.Slice(_consumed, 1);
UpdateBitStackOnEndToken();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void UpdateBitStackOnEndToken()
{
_consumed++;
_bytePositionInLine++;
_inObject = _bitStack.Pop();
}
private bool ReadSingleSegment()
{
bool retVal = false;
ValueSpan = default;
ValueIsEscaped = false;
if (!HasMoreData())
{
goto Done;
}
byte first = _buffer[_consumed];
// This check is done as an optimization to avoid calling SkipWhiteSpace when not necessary.
// SkipWhiteSpace only skips the whitespace characters as defined by JSON RFC 8259 section 2.
// We do not validate if 'first' is an invalid JSON byte here (such as control characters).
// Those cases are captured in ConsumeNextToken and ConsumeValue.
if (first <= JsonConstants.Space)
{
SkipWhiteSpace();
if (!HasMoreData())
{
goto Done;
}
first = _buffer[_consumed];
}
TokenStartIndex = _consumed;
if (_tokenType == JsonTokenType.None)
{
goto ReadFirstToken;
}
if (first == JsonConstants.Slash)
{
retVal = ConsumeNextTokenOrRollback(first);
goto Done;
}
if (_tokenType == JsonTokenType.StartObject)
{
if (first == JsonConstants.CloseBrace)
{
EndObject();
}
else
{
if (first != JsonConstants.Quote)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, first);
}
int prevConsumed = _consumed;
long prevPosition = _bytePositionInLine;
long prevLineNumber = _lineNumber;
retVal = ConsumePropertyName();
if (!retVal)
{
// roll back potential changes
_consumed = prevConsumed;
_tokenType = JsonTokenType.StartObject;
_bytePositionInLine = prevPosition;
_lineNumber = prevLineNumber;
}
goto Done;
}
}
else if (_tokenType == JsonTokenType.StartArray)
{
if (first == JsonConstants.CloseBracket)
{
EndArray();
}
else
{
retVal = ConsumeValue(first);
goto Done;
}
}
else if (_tokenType == JsonTokenType.PropertyName)
{
retVal = ConsumeValue(first);
goto Done;
}
else
{
retVal = ConsumeNextTokenOrRollback(first);
goto Done;
}
retVal = true;
Done:
return retVal;
ReadFirstToken:
retVal = ReadFirstToken(first);
goto Done;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasMoreData()
{
if (_consumed >= (uint)_buffer.Length)
{
if (_isNotPrimitive && IsLastSpan)
{
if (_bitStack.CurrentDepth != 0)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ZeroDepthAtEnd);
}
if (_readerOptions.CommentHandling == JsonCommentHandling.Allow && _tokenType == JsonTokenType.Comment)
{
return false;
}
if (_tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive);
}
}
return false;
}
return true;
}
// Unlike the parameter-less overload of HasMoreData, if there is no more data when this method is called, we know the JSON input is invalid.
// This is because, this method is only called after a ',' (i.e. we expect a value/property name) or after
// a property name, which means it must be followed by a value.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasMoreData(ExceptionResource resource)
{
if (_consumed >= (uint)_buffer.Length)
{
if (IsLastSpan)
{
ThrowHelper.ThrowJsonReaderException(ref this, resource);
}
return false;
}
return true;
}
private bool ReadFirstToken(byte first)
{
if (first == JsonConstants.OpenBrace)
{
_bitStack.SetFirstBit();
_tokenType = JsonTokenType.StartObject;
ValueSpan = _buffer.Slice(_consumed, 1);
_consumed++;
_bytePositionInLine++;
_inObject = true;
_isNotPrimitive = true;
}
else if (first == JsonConstants.OpenBracket)
{
_bitStack.ResetFirstBit();
_tokenType = JsonTokenType.StartArray;
ValueSpan = _buffer.Slice(_consumed, 1);
_consumed++;
_bytePositionInLine++;
_isNotPrimitive = true;
}
else
{
// Create local copy to avoid bounds checks.
ReadOnlySpan<byte> localBuffer = _buffer;
if (JsonHelpers.IsDigit(first) || first == '-')
{
if (!TryGetNumber(localBuffer.Slice(_consumed), out int numberOfBytes))
{
return false;
}
_tokenType = JsonTokenType.Number;
_consumed += numberOfBytes;
_bytePositionInLine += numberOfBytes;
return true;
}
else if (!ConsumeValue(first))
{
return false;
}
if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray)
{
_isNotPrimitive = true;
}
// Intentionally fall out of the if-block to return true
}
return true;
}
private void SkipWhiteSpace()
{
// Create local copy to avoid bounds checks.
ReadOnlySpan<byte> localBuffer = _buffer;
for (; _consumed < localBuffer.Length; _consumed++)
{
byte val = localBuffer[_consumed];