/
Utf8JsonReader.MultiSegment.cs
2614 lines (2323 loc) · 101 KB
/
Utf8JsonReader.MultiSegment.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
// 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;
namespace System.Text.Json
{
public ref partial struct Utf8JsonReader
{
/// <summary>
/// Constructs a new <see cref="Utf8JsonReader"/> instance.
/// </summary>
/// <param name="jsonData">The ReadOnlySequence<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(ReadOnlySequence<byte> jsonData, bool isFinalBlock, JsonReaderState state)
{
_buffer = jsonData.First.Span;
_isFinalBlock = isFinalBlock;
_isInputSequence = true;
_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;
ValueSpan = ReadOnlySpan<byte>.Empty;
_sequence = jsonData;
HasValueSequence = false;
ValueSequence = ReadOnlySequence<byte>.Empty;
if (jsonData.IsSingleSegment)
{
_nextPosition = default;
_currentPosition = jsonData.Start;
_isLastSegment = isFinalBlock;
_isMultiSegment = false;
}
else
{
_currentPosition = jsonData.Start;
_nextPosition = _currentPosition;
bool firstSegmentIsEmpty = _buffer.Length == 0;
if (firstSegmentIsEmpty)
{
// Once we find a non-empty segment, we need to set current position to it.
// Therefore, track the next position in a copy before it gets advanced to the next segment.
SequencePosition previousNextPosition = _nextPosition;
while (jsonData.TryGet(ref _nextPosition, out ReadOnlyMemory<byte> memory, advance: true))
{
// _currentPosition should point to the segment right befor the segment that _nextPosition points to.
_currentPosition = previousNextPosition;
if (memory.Length != 0)
{
_buffer = memory.Span;
break;
}
previousNextPosition = _nextPosition;
}
}
// If firstSegmentIsEmpty is true,
// only check if we have reached the last segment but do not advance _nextPosition. The while loop above already advanced it.
// Otherwise, we would end up skipping a segment (i.e. advance = false).
// If firstSegmentIsEmpty is false,
// make sure to advance _nextPosition so that it is no longer the same as _currentPosition (i.e. advance = true).
_isLastSegment = !jsonData.TryGet(ref _nextPosition, out _, advance: !firstSegmentIsEmpty) && isFinalBlock; // Don't re-order to avoid short-circuiting
Debug.Assert(!_nextPosition.Equals(_currentPosition));
_isMultiSegment = true;
}
}
/// <summary>
/// Constructs a new <see cref="Utf8JsonReader"/> instance.
/// </summary>
/// <param name="jsonData">The ReadOnlySequence<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(ReadOnlySequence<byte> jsonData, JsonReaderOptions options = default)
: this(jsonData, isFinalBlock: true, new JsonReaderState(options))
{
}
private bool ReadMultiSegment()
{
bool retVal = false;
HasValueSequence = false;
ValueIsEscaped = false;
ValueSpan = default;
ValueSequence = default;
if (!HasMoreDataMultiSegment())
{
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)
{
SkipWhiteSpaceMultiSegment();
if (!HasMoreDataMultiSegment())
{
goto Done;
}
first = _buffer[_consumed];
}
TokenStartIndex = BytesConsumed;
if (_tokenType == JsonTokenType.None)
{
goto ReadFirstToken;
}
if (first == JsonConstants.Slash)
{
retVal = ConsumeNextTokenOrRollbackMultiSegment(first);
goto Done;
}
if (_tokenType == JsonTokenType.StartObject)
{
if (first == JsonConstants.CloseBrace)
{
EndObject();
}
else
{
if (first != JsonConstants.Quote)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfPropertyNotFound, first);
}
long prevTotalConsumed = _totalConsumed;
int prevConsumed = _consumed;
long prevPosition = _bytePositionInLine;
long prevLineNumber = _lineNumber;
SequencePosition copy = _currentPosition;
retVal = ConsumePropertyNameMultiSegment();
if (!retVal)
{
// roll back potential changes
_consumed = prevConsumed;
_tokenType = JsonTokenType.StartObject;
_bytePositionInLine = prevPosition;
_lineNumber = prevLineNumber;
_totalConsumed = prevTotalConsumed;
_currentPosition = copy;
}
goto Done;
}
}
else if (_tokenType == JsonTokenType.StartArray)
{
if (first == JsonConstants.CloseBracket)
{
EndArray();
}
else
{
retVal = ConsumeValueMultiSegment(first);
goto Done;
}
}
else if (_tokenType == JsonTokenType.PropertyName)
{
retVal = ConsumeValueMultiSegment(first);
goto Done;
}
else
{
retVal = ConsumeNextTokenOrRollbackMultiSegment(first);
goto Done;
}
retVal = true;
Done:
return retVal;
ReadFirstToken:
retVal = ReadFirstTokenMultiSegment(first);
goto Done;
}
private bool ValidateStateAtEndOfData()
{
Debug.Assert(_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 true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasMoreDataMultiSegment()
{
if (_consumed >= (uint)_buffer.Length)
{
if (_isNotPrimitive && IsLastSpan)
{
if (!ValidateStateAtEndOfData())
{
return false;
}
}
if (!GetNextSpan())
{
if (_isNotPrimitive && IsLastSpan)
{
ValidateStateAtEndOfData();
}
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 HasMoreDataMultiSegment(ExceptionResource resource)
{
if (_consumed >= (uint)_buffer.Length)
{
if (IsLastSpan)
{
ThrowHelper.ThrowJsonReaderException(ref this, resource);
}
if (!GetNextSpan())
{
if (IsLastSpan)
{
ThrowHelper.ThrowJsonReaderException(ref this, resource);
}
return false;
}
}
return true;
}
private bool GetNextSpan()
{
ReadOnlyMemory<byte> memory;
while (true)
{
Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() != null);
SequencePosition copy = _currentPosition;
_currentPosition = _nextPosition;
bool noMoreData = !_sequence.TryGet(ref _nextPosition, out memory, advance: true);
if (noMoreData)
{
_currentPosition = copy;
_isLastSegment = true;
return false;
}
if (memory.Length != 0)
{
break;
}
// _currentPosition needs to point to last non-empty segment
// Since memory.Length == 0, we need to revert back to previous.
_currentPosition = copy;
Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() != null);
}
if (_isFinalBlock)
{
_isLastSegment = !_sequence.TryGet(ref _nextPosition, out _, advance: false);
}
_buffer = memory.Span;
_totalConsumed += _consumed;
_consumed = 0;
return true;
}
private bool ReadFirstTokenMultiSegment(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
{
if (JsonHelpers.IsDigit(first) || first == '-')
{
if (!TryGetNumberMultiSegment(_buffer.Slice(_consumed), out int numberOfBytes))
{
return false;
}
_tokenType = JsonTokenType.Number;
_consumed += numberOfBytes;
return true;
}
else if (!ConsumeValueMultiSegment(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 SkipWhiteSpaceMultiSegment()
{
while (true)
{
SkipWhiteSpace();
if (_consumed < _buffer.Length)
{
break;
}
if (!GetNextSpan())
{
break;
}
}
}
/// <summary>
/// This method contains the logic for processing the next value token and determining
/// what type of data it is.
/// </summary>
private bool ConsumeValueMultiSegment(byte marker)
{
while (true)
{
Debug.Assert((_trailingCommaBeforeComment && _readerOptions.CommentHandling == JsonCommentHandling.Allow) || !_trailingCommaBeforeComment);
Debug.Assert((_trailingCommaBeforeComment && marker != JsonConstants.Slash) || !_trailingCommaBeforeComment);
_trailingCommaBeforeComment = false;
if (marker == JsonConstants.Quote)
{
return ConsumeStringMultiSegment();
}
else if (marker == JsonConstants.OpenBrace)
{
StartObject();
}
else if (marker == JsonConstants.OpenBracket)
{
StartArray();
}
else if (JsonHelpers.IsDigit(marker) || marker == '-')
{
return ConsumeNumberMultiSegment();
}
else if (marker == 'f')
{
return ConsumeLiteralMultiSegment(JsonConstants.FalseValue, JsonTokenType.False);
}
else if (marker == 't')
{
return ConsumeLiteralMultiSegment(JsonConstants.TrueValue, JsonTokenType.True);
}
else if (marker == 'n')
{
return ConsumeLiteralMultiSegment(JsonConstants.NullValue, JsonTokenType.Null);
}
else
{
switch (_readerOptions.CommentHandling)
{
case JsonCommentHandling.Disallow:
break;
case JsonCommentHandling.Allow:
if (marker == JsonConstants.Slash)
{
SequencePosition copy = _currentPosition;
if (!SkipOrConsumeCommentMultiSegmentWithRollback())
{
_currentPosition = copy;
return false;
}
return true;
}
break;
default:
Debug.Assert(_readerOptions.CommentHandling == JsonCommentHandling.Skip);
if (marker == JsonConstants.Slash)
{
SequencePosition copy = _currentPosition;
if (SkipCommentMultiSegment(out _))
{
if (_consumed >= (uint)_buffer.Length)
{
if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive);
}
if (!GetNextSpan())
{
if (_isNotPrimitive && IsLastSpan && _tokenType != JsonTokenType.EndArray && _tokenType != JsonTokenType.EndObject)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidEndOfJsonNonPrimitive);
}
_currentPosition = copy;
return false;
}
}
marker = _buffer[_consumed];
// This check is done as an optimization to avoid calling SkipWhiteSpace when not necessary.
if (marker <= JsonConstants.Space)
{
SkipWhiteSpaceMultiSegment();
if (!HasMoreDataMultiSegment())
{
_currentPosition = copy;
return false;
}
marker = _buffer[_consumed];
}
TokenStartIndex = BytesConsumed;
// Skip comments and consume the actual JSON value.
continue;
}
_currentPosition = copy;
return false;
}
break;
}
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedStartOfValueNotFound, marker);
}
break;
}
return true;
}
// Consumes 'null', or 'true', or 'false'
private bool ConsumeLiteralMultiSegment(ReadOnlySpan<byte> literal, JsonTokenType tokenType)
{
ReadOnlySpan<byte> span = _buffer.Slice(_consumed);
Debug.Assert(span.Length > 0);
Debug.Assert(span[0] == 'n' || span[0] == 't' || span[0] == 'f');
int consumed = literal.Length;
if (!span.StartsWith(literal))
{
int prevConsumed = _consumed;
if (CheckLiteralMultiSegment(span, literal, out consumed))
{
goto Done;
}
_consumed = prevConsumed;
return false;
}
ValueSpan = span.Slice(0, literal.Length);
HasValueSequence = false;
Done:
_tokenType = tokenType;
_consumed += consumed;
_bytePositionInLine += consumed;
return true;
}
private bool CheckLiteralMultiSegment(ReadOnlySpan<byte> span, ReadOnlySpan<byte> literal, out int consumed)
{
Debug.Assert(span.Length > 0 && span[0] == literal[0] && literal.Length <= JsonConstants.MaximumLiteralLength);
Span<byte> readSoFar = stackalloc byte[JsonConstants.MaximumLiteralLength];
int written = 0;
long prevTotalConsumed = _totalConsumed;
SequencePosition copy = _currentPosition;
if (span.Length >= literal.Length || IsLastSpan)
{
_bytePositionInLine += FindMismatch(span, literal);
int amountToWrite = Math.Min(span.Length, (int)_bytePositionInLine + 1);
span.Slice(0, amountToWrite).CopyTo(readSoFar);
written += amountToWrite;
goto Throw;
}
else
{
if (!literal.StartsWith(span))
{
_bytePositionInLine += FindMismatch(span, literal);
int amountToWrite = Math.Min(span.Length, (int)_bytePositionInLine + 1);
span.Slice(0, amountToWrite).CopyTo(readSoFar);
written += amountToWrite;
goto Throw;
}
ReadOnlySpan<byte> leftToMatch = literal.Slice(span.Length);
SequencePosition startPosition = _currentPosition;
int startConsumed = _consumed;
int alreadyMatched = literal.Length - leftToMatch.Length;
while (true)
{
_totalConsumed += alreadyMatched;
_bytePositionInLine += alreadyMatched;
if (!GetNextSpan())
{
_totalConsumed = prevTotalConsumed;
consumed = default;
_currentPosition = copy;
if (IsLastSpan)
{
goto Throw;
}
return false;
}
int amountToWrite = Math.Min(span.Length, readSoFar.Length - written);
span.Slice(0, amountToWrite).CopyTo(readSoFar.Slice(written));
written += amountToWrite;
span = _buffer;
if (span.StartsWith(leftToMatch))
{
HasValueSequence = true;
SequencePosition start = new SequencePosition(startPosition.GetObject(), startPosition.GetInteger() + startConsumed);
SequencePosition end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + leftToMatch.Length);
ValueSequence = _sequence.Slice(start, end);
consumed = leftToMatch.Length;
return true;
}
if (!leftToMatch.StartsWith(span))
{
_bytePositionInLine += FindMismatch(span, leftToMatch);
amountToWrite = Math.Min(span.Length, (int)_bytePositionInLine + 1);
span.Slice(0, amountToWrite).CopyTo(readSoFar.Slice(written));
written += amountToWrite;
goto Throw;
}
leftToMatch = leftToMatch.Slice(span.Length);
alreadyMatched = span.Length;
}
}
Throw:
_totalConsumed = prevTotalConsumed;
consumed = default;
_currentPosition = copy;
throw GetInvalidLiteralMultiSegment(readSoFar.Slice(0, written).ToArray());
}
private static int FindMismatch(ReadOnlySpan<byte> span, ReadOnlySpan<byte> literal)
{
Debug.Assert(span.Length > 0);
int indexOfFirstMismatch;
#if NET7_0_OR_GREATER
indexOfFirstMismatch = span.CommonPrefixLength(literal);
#else
int minLength = Math.Min(span.Length, literal.Length);
for (indexOfFirstMismatch = 0; indexOfFirstMismatch < minLength; indexOfFirstMismatch++)
{
if (span[indexOfFirstMismatch] != literal[indexOfFirstMismatch])
{
break;
}
}
#endif
Debug.Assert(indexOfFirstMismatch >= 0 && indexOfFirstMismatch < literal.Length);
return indexOfFirstMismatch;
}
private JsonException GetInvalidLiteralMultiSegment(ReadOnlySpan<byte> span)
{
byte firstByte = span[0];
ExceptionResource resource;
switch (firstByte)
{
case (byte)'t':
resource = ExceptionResource.ExpectedTrue;
break;
case (byte)'f':
resource = ExceptionResource.ExpectedFalse;
break;
default:
Debug.Assert(firstByte == 'n');
resource = ExceptionResource.ExpectedNull;
break;
}
return ThrowHelper.GetJsonReaderException(ref this, resource, nextByte: default, bytes: span);
}
private bool ConsumeNumberMultiSegment()
{
if (!TryGetNumberMultiSegment(_buffer.Slice(_consumed), out int consumed))
{
return false;
}
_tokenType = JsonTokenType.Number;
_consumed += consumed;
if (_consumed >= (uint)_buffer.Length)
{
Debug.Assert(IsLastSpan);
// If there is no more data, and the JSON is not a single value, throw.
if (_isNotPrimitive)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedEndOfDigitNotFound, _buffer[_consumed - 1]);
}
}
// If there is more data and the JSON is not a single value, assert that there is an end of number delimiter.
// Else, if either the JSON is a single value XOR if there is no more data, don't assert anything since there won't always be an end of number delimiter.
Debug.Assert(
((_consumed < _buffer.Length) &&
!_isNotPrimitive &&
JsonConstants.Delimiters.IndexOf(_buffer[_consumed]) >= 0)
|| (_isNotPrimitive ^ (_consumed >= (uint)_buffer.Length)));
return true;
}
private bool ConsumePropertyNameMultiSegment()
{
_trailingCommaBeforeComment = false;
if (!ConsumeStringMultiSegment())
{
return false;
}
if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedValueAfterPropertyNameNotFound))
{
return false;
}
byte first = _buffer[_consumed];
// This check is done as an optimization to avoid calling SkipWhiteSpace when not necessary.
// We do not validate if 'first' is an invalid JSON byte here (such as control characters).
// Those cases are captured below where we only accept ':'.
if (first <= JsonConstants.Space)
{
SkipWhiteSpaceMultiSegment();
if (!HasMoreDataMultiSegment(ExceptionResource.ExpectedValueAfterPropertyNameNotFound))
{
return false;
}
first = _buffer[_consumed];
}
// The next character must be a key / value separator. Validate and skip.
if (first != JsonConstants.KeyValueSeparator)
{
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound, first);
}
_consumed++;
_bytePositionInLine++;
_tokenType = JsonTokenType.PropertyName;
return true;
}
private bool ConsumeStringMultiSegment()
{
Debug.Assert(_buffer.Length >= _consumed + 1);
Debug.Assert(_buffer[_consumed] == JsonConstants.Quote);
// Create local copy to avoid bounds checks.
ReadOnlySpan<byte> localBuffer = _buffer.Slice(_consumed + 1);
// Vectorized search for either quote, backslash, or any control character.
// If the first found byte is a quote, we have reached an end of string, and
// can avoid validation.
// Otherwise, in the uncommon case, iterate one character at a time and validate.
int idx = localBuffer.IndexOfQuoteOrAnyControlOrBackSlash();
if (idx >= 0)
{
byte foundByte = localBuffer[idx];
if (foundByte == JsonConstants.Quote)
{
_bytePositionInLine += idx + 2; // Add 2 for the start and end quotes.
ValueSpan = localBuffer.Slice(0, idx);
HasValueSequence = false;
ValueIsEscaped = false;
_tokenType = JsonTokenType.String;
_consumed += idx + 2;
return true;
}
else
{
return ConsumeStringAndValidateMultiSegment(localBuffer, idx);
}
}
else
{
if (IsLastSpan)
{
_bytePositionInLine += localBuffer.Length + 1; // Account for the start quote
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound);
}
return ConsumeStringNextSegment();
}
}
private bool ConsumeStringNextSegment()
{
PartialStateForRollback rollBackState = CaptureState();
SequencePosition end;
HasValueSequence = true;
int leftOver = _buffer.Length - _consumed;
while (true)
{
if (!GetNextSpan())
{
if (IsLastSpan)
{
_bytePositionInLine += leftOver;
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound);
}
RollBackState(rollBackState);
return false;
}
//Create local copy to avoid bounds checks.
ReadOnlySpan<byte> localBuffer = _buffer;
int idx = localBuffer.IndexOfQuoteOrAnyControlOrBackSlash();
if (idx >= 0)
{
byte foundByte = localBuffer[idx];
if (foundByte == JsonConstants.Quote)
{
end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + idx);
_bytePositionInLine += leftOver + idx + 1; // Add 1 for the end quote of the string.
_totalConsumed += leftOver;
_consumed = idx + 1; // Add 1 for the end quote of the string.
ValueIsEscaped = false;
break;
}
else
{
_bytePositionInLine += leftOver + idx;
ValueIsEscaped = true;
bool nextCharEscaped = false;
while (true)
{
StartOfLoop:
for (; idx < localBuffer.Length; idx++)
{
byte currentByte = localBuffer[idx];
if (currentByte == JsonConstants.Quote)
{
if (!nextCharEscaped)
{
goto Done;
}
nextCharEscaped = false;
}
else if (currentByte == JsonConstants.BackSlash)
{
nextCharEscaped = !nextCharEscaped;
}
else if (nextCharEscaped)
{
int index = JsonConstants.EscapableChars.IndexOf(currentByte);
if (index == -1)
{
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, currentByte);
}
if (currentByte == 'u')
{
// Expecting 4 hex digits to follow the escaped 'u'
_bytePositionInLine++; // move past the 'u'
int numberOfHexDigits = 0;
int j = idx + 1;
while (true)
{
for (; j < localBuffer.Length; j++)
{
byte nextByte = localBuffer[j];
if (!JsonReaderHelper.IsHexDigit(nextByte))
{
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidHexCharacterWithinString, nextByte);
}
numberOfHexDigits++;
_bytePositionInLine++;
if (numberOfHexDigits >= 4)
{
nextCharEscaped = false;
idx = j + 1; // Skip the 4 hex digits, the for loop accounts for idx incrementing past the 'u'
goto StartOfLoop;
}
}
if (!GetNextSpan())
{
if (IsLastSpan)
{
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound);
}
// We found less than 4 hex digits.
RollBackState(rollBackState);
return false;
}
_totalConsumed += localBuffer.Length;
localBuffer = _buffer;
j = 0;
}
}
nextCharEscaped = false;
}
else if (currentByte < JsonConstants.Space)
{
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterWithinString, currentByte);
}
_bytePositionInLine++;
}
if (!GetNextSpan())
{
if (IsLastSpan)
{
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.EndOfStringNotFound);
}
RollBackState(rollBackState);
return false;
}
_totalConsumed += localBuffer.Length;
localBuffer = _buffer;
idx = 0;
}
Done:
_bytePositionInLine++; // Add 1 for the end quote of the string.
_consumed = idx + 1; // Add 1 for the end quote of the string.
_totalConsumed += leftOver;
end = new SequencePosition(_currentPosition.GetObject(), _currentPosition.GetInteger() + idx);
break;
}
}
_totalConsumed += localBuffer.Length;
_bytePositionInLine += localBuffer.Length;
}
SequencePosition start = rollBackState.GetStartPosition(offset: 1); // Offset for the starting quote
ValueSequence = _sequence.Slice(start, end);
_tokenType = JsonTokenType.String;
return true;
}
// Found a backslash or control characters which are considered invalid within a string.
// Search through the rest of the string one byte at a time.
// https://tools.ietf.org/html/rfc8259#section-7
private bool ConsumeStringAndValidateMultiSegment(ReadOnlySpan<byte> data, int idx)
{
Debug.Assert(idx >= 0 && idx < data.Length);
Debug.Assert(data[idx] != JsonConstants.Quote);
Debug.Assert(data[idx] == JsonConstants.BackSlash || data[idx] < JsonConstants.Space);
PartialStateForRollback rollBackState = CaptureState();
SequencePosition end;
HasValueSequence = false;
int leftOverFromConsumed = _buffer.Length - _consumed;
_bytePositionInLine += idx + 1; // Add 1 for the first quote
bool nextCharEscaped = false;
while (true)
{
StartOfLoop:
for (; idx < data.Length; idx++)
{
byte currentByte = data[idx];
if (currentByte == JsonConstants.Quote)
{
if (!nextCharEscaped)
{
goto Done;
}
nextCharEscaped = false;
}
else if (currentByte == JsonConstants.BackSlash)
{
nextCharEscaped = !nextCharEscaped;
}
else if (nextCharEscaped)
{
int index = JsonConstants.EscapableChars.IndexOf(currentByte);
if (index == -1)
{
RollBackState(rollBackState, isError: true);
ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.InvalidCharacterAfterEscapeWithinString, currentByte);
}
if (currentByte == 'u')
{