-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathUtf8JsonWriter.cs
More file actions
1134 lines (971 loc) · 43.1 KB
/
Copy pathUtf8JsonWriter.cs
File metadata and controls
1134 lines (971 loc) · 43.1 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.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
#if !NET
using System.Runtime.InteropServices;
#endif
namespace System.Text.Json
{
/// <summary>
/// Provides a high-performance API for forward-only, non-cached writing of UTF-8 encoded JSON text.
/// </summary>
/// <remarks>
/// <para>
/// It writes the text sequentially with no caching and adheres to the JSON RFC
/// by default (https://tools.ietf.org/html/rfc8259), with the exception of writing comments.
/// </para>
/// <para>
/// When the user attempts to write invalid JSON and validation is enabled, it throws
/// an <see cref="InvalidOperationException"/> with a context specific error message.
/// </para>
/// <para>
/// To be able to format the output with indentation and whitespace OR to skip validation, create an instance of
/// <see cref="JsonWriterOptions"/> and pass that in to the writer.
/// </para>
/// </remarks>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable
{
private const int DefaultGrowthSize = 4096;
private const int InitialGrowthSize = 256;
private IBufferWriter<byte>? _output;
private Stream? _stream;
private ArrayBufferWriter<byte>? _arrayBufferWriter;
private Memory<byte> _memory;
private bool _inObject;
private bool _commentAfterNoneOrPropertyName;
private JsonTokenType _tokenType;
private BitStack _bitStack;
// The highest order bit of _currentDepth is used to discern whether we are writing the first item in a list or not.
// if (_currentDepth >> 31) == 1, add a list separator before writing the item
// else, no list separator is needed since we are writing the first item.
private int _currentDepth;
private JsonWriterOptions _options; // Since JsonWriterOptions is a struct, use a field to avoid a copy for internal code.
// Cache indentation settings from JsonWriterOptions to avoid recomputing them in the hot path.
private byte _indentByte;
private int _indentLength;
// A length of 1 will emit LF for indented writes, a length of 2 will emit CRLF. Other values are invalid.
private int _newLineLength;
/// <summary>
/// Returns the amount of bytes written by the <see cref="Utf8JsonWriter"/> so far
/// that have not yet been flushed to the output and committed.
/// </summary>
public int BytesPending { get; private set; }
/// <summary>
/// Returns the amount of bytes committed to the output by the <see cref="Utf8JsonWriter"/> so far.
/// </summary>
/// <remarks>
/// In the case of IBufferwriter, this is how much the IBufferWriter has advanced.
/// In the case of Stream, this is how much data has been written to the stream.
/// </remarks>
public long BytesCommitted { get; private set; }
/// <summary>
/// Gets the custom behavior when writing JSON using
/// the <see cref="Utf8JsonWriter"/> which indicates whether to format the output
/// while writing and whether to skip structural JSON validation or not.
/// </summary>
public JsonWriterOptions Options => _options;
private int Indentation => CurrentDepth * _indentLength;
internal JsonTokenType TokenType => _tokenType;
/// <summary>
/// Tracks the recursive depth of the nested objects / arrays within the JSON text
/// written so far. This provides the depth of the current token.
/// </summary>
public int CurrentDepth => _currentDepth & JsonConstants.RemoveFlagsBitMask;
private Utf8JsonWriter()
{
}
/// <summary>
/// Constructs a new <see cref="Utf8JsonWriter"/> instance with a specified <paramref name="bufferWriter"/>.
/// </summary>
/// <param name="bufferWriter">An instance of <see cref="IBufferWriter{Byte}" /> used as a destination for writing JSON text into.</param>
/// <param name="options">Defines the customized behavior of the <see cref="Utf8JsonWriter"/>
/// By default, the <see cref="Utf8JsonWriter"/> writes JSON minimized (that is, with no extra whitespace)
/// and validates that the JSON being written is structurally valid according to JSON RFC.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when the instance of <see cref="IBufferWriter{Byte}" /> that is passed in is null.
/// </exception>
public Utf8JsonWriter(IBufferWriter<byte> bufferWriter, JsonWriterOptions options = default)
{
if (bufferWriter is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(bufferWriter));
}
_output = bufferWriter;
SetOptions(options);
}
/// <summary>
/// Constructs a new <see cref="Utf8JsonWriter"/> instance with a specified <paramref name="utf8Json"/>.
/// </summary>
/// <param name="utf8Json">An instance of <see cref="Stream" /> used as a destination for writing JSON text into.</param>
/// <param name="options">Defines the customized behavior of the <see cref="Utf8JsonWriter"/>
/// By default, the <see cref="Utf8JsonWriter"/> writes JSON minimized (that is, with no extra whitespace)
/// and validates that the JSON being written is structurally valid according to JSON RFC.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when the instance of <see cref="Stream" /> that is passed in is null.
/// </exception>
public Utf8JsonWriter(Stream utf8Json, JsonWriterOptions options = default)
{
if (utf8Json is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(utf8Json));
}
if (!utf8Json.CanWrite)
throw new ArgumentException(SR.StreamNotWritable);
_stream = utf8Json;
SetOptions(options);
_arrayBufferWriter = new ArrayBufferWriter<byte>();
}
private void SetOptions(JsonWriterOptions options)
{
_options = options;
_indentByte = (byte)_options.IndentCharacter;
_indentLength = options.IndentSize;
Debug.Assert(options.NewLine is "\n" or "\r\n", "Invalid NewLine string.");
_newLineLength = options.NewLine.Length;
if (_options.MaxDepth == 0)
{
_options.MaxDepth = JsonWriterOptions.DefaultMaxDepth; // If max depth is not set, revert to the default depth.
}
}
/// <summary>
/// Resets the <see cref="Utf8JsonWriter"/> internal state so that it can be re-used.
/// </summary>
/// <remarks>
/// The <see cref="Utf8JsonWriter"/> will continue to use the original writer options
/// and the original output as the destination (either <see cref="IBufferWriter{Byte}" /> or <see cref="Stream" />).
/// </remarks>
/// <exception cref="ObjectDisposedException">
/// The instance of <see cref="Utf8JsonWriter"/> has been disposed.
/// </exception>
public void Reset()
{
CheckNotDisposed();
_arrayBufferWriter?.Clear();
ResetHelper();
}
/// <summary>
/// Resets the <see cref="Utf8JsonWriter"/> internal state so that it can be re-used with the new instance of <see cref="Stream" />.
/// </summary>
/// <param name="utf8Json">An instance of <see cref="Stream" /> used as a destination for writing JSON text into.</param>
/// <remarks>
/// The <see cref="Utf8JsonWriter"/> will continue to use the original writer options
/// but now write to the passed in <see cref="Stream" /> as the new destination.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// Thrown when the instance of <see cref="Stream" /> that is passed in is null.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The instance of <see cref="Utf8JsonWriter"/> has been disposed.
/// </exception>
public void Reset(Stream utf8Json)
{
CheckNotDisposed();
if (utf8Json == null)
throw new ArgumentNullException(nameof(utf8Json));
if (!utf8Json.CanWrite)
throw new ArgumentException(SR.StreamNotWritable);
_stream = utf8Json;
if (_arrayBufferWriter == null)
{
_arrayBufferWriter = new ArrayBufferWriter<byte>();
}
else
{
_arrayBufferWriter.Clear();
}
_output = null;
ResetHelper();
}
/// <summary>
/// Resets the <see cref="Utf8JsonWriter"/> internal state so that it can be re-used with the new instance of <see cref="IBufferWriter{Byte}" />.
/// </summary>
/// <param name="bufferWriter">An instance of <see cref="IBufferWriter{Byte}" /> used as a destination for writing JSON text into.</param>
/// <remarks>
/// The <see cref="Utf8JsonWriter"/> will continue to use the original writer options
/// but now write to the passed in <see cref="IBufferWriter{Byte}" /> as the new destination.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// Thrown when the instance of <see cref="IBufferWriter{Byte}" /> that is passed in is null.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The instance of <see cref="Utf8JsonWriter"/> has been disposed.
/// </exception>
public void Reset(IBufferWriter<byte> bufferWriter)
{
CheckNotDisposed();
_output = bufferWriter ?? throw new ArgumentNullException(nameof(bufferWriter));
_stream = null;
_arrayBufferWriter = null;
ResetHelper();
}
internal void ResetAllStateForCacheReuse()
{
ResetHelper();
_stream = null;
_arrayBufferWriter = null;
_output = null;
}
internal void Reset(IBufferWriter<byte> bufferWriter, JsonWriterOptions options)
{
Debug.Assert(_output is null && _stream is null && _arrayBufferWriter is null);
_output = bufferWriter;
SetOptions(options);
}
internal static Utf8JsonWriter CreateEmptyInstanceForCaching() => new Utf8JsonWriter();
private void ResetHelper()
{
BytesPending = default;
BytesCommitted = default;
_memory = default;
_inObject = default;
_tokenType = default;
_commentAfterNoneOrPropertyName = default;
_currentDepth = default;
_bitStack = default;
}
private void CheckNotDisposed()
{
if (_stream == null)
{
// The conditions are ordered with stream first as that would be the most common mode
if (_output == null)
{
ThrowHelper.ThrowObjectDisposedException_Utf8JsonWriter();
}
}
}
/// <summary>
/// Commits the JSON text written so far which makes it visible to the output destination.
/// </summary>
/// <remarks>
/// In the case of IBufferWriter, this advances the underlying <see cref="IBufferWriter{Byte}" /> based on what has been written so far.
/// In the case of Stream, this writes the data to the stream and flushes it.
/// </remarks>
/// <exception cref="ObjectDisposedException">
/// The instance of <see cref="Utf8JsonWriter"/> has been disposed.
/// </exception>
public void Flush()
{
CheckNotDisposed();
_memory = default;
if (_stream != null)
{
Debug.Assert(_arrayBufferWriter != null);
if (BytesPending != 0)
{
_arrayBufferWriter.Advance(BytesPending);
BytesPending = 0;
#if NET
_stream.Write(_arrayBufferWriter.WrittenSpan);
#else
Debug.Assert(_arrayBufferWriter.WrittenMemory.Length == _arrayBufferWriter.WrittenCount);
bool result = MemoryMarshal.TryGetArray(_arrayBufferWriter.WrittenMemory, out ArraySegment<byte> underlyingBuffer);
Debug.Assert(result);
Debug.Assert(underlyingBuffer.Offset == 0);
Debug.Assert(_arrayBufferWriter.WrittenCount == underlyingBuffer.Count);
_stream.Write(underlyingBuffer.Array, underlyingBuffer.Offset, underlyingBuffer.Count);
#endif
BytesCommitted += _arrayBufferWriter.WrittenCount;
_arrayBufferWriter.Clear();
}
_stream.Flush();
}
else
{
Debug.Assert(_output != null);
if (BytesPending != 0)
{
_output.Advance(BytesPending);
BytesCommitted += BytesPending;
BytesPending = 0;
}
}
}
/// <summary>
/// Commits any left over JSON text that has not yet been flushed and releases all resources used by the current instance.
/// </summary>
/// <remarks>
/// <para>
/// In the case of IBufferWriter, this advances the underlying <see cref="IBufferWriter{Byte}" /> based on what has been written so far.
/// In the case of Stream, this writes the data to the stream and flushes it.
/// </para>
/// <para>
/// The <see cref="Utf8JsonWriter"/> instance cannot be re-used after disposing.
/// </para>
/// </remarks>
public void Dispose()
{
if (_stream == null)
{
// The conditions are ordered with stream first as that would be the most common mode
if (_output == null)
{
return;
}
}
Flush();
ResetHelper();
_stream = null;
_arrayBufferWriter = null;
_output = null;
}
/// <summary>
/// Asynchronously commits any left over JSON text that has not yet been flushed and releases all resources used by the current instance.
/// </summary>
/// <remarks>
/// <para>
/// In the case of IBufferWriter, this advances the underlying <see cref="IBufferWriter{Byte}" /> based on what has been written so far.
/// In the case of Stream, this writes the data to the stream and flushes it.
/// </para>
/// <para>
/// The <see cref="Utf8JsonWriter"/> instance cannot be re-used after disposing.
/// </para>
/// </remarks>
public async ValueTask DisposeAsync()
{
if (_stream == null)
{
// The conditions are ordered with stream first as that would be the most common mode
if (_output == null)
{
return;
}
}
await FlushAsync().ConfigureAwait(false);
ResetHelper();
_stream = null;
_arrayBufferWriter = null;
_output = null;
}
/// <summary>
/// Asynchronously commits the JSON text written so far which makes it visible to the output destination.
/// </summary>
/// <remarks>
/// In the case of IBufferWriter, this advances the underlying <see cref="IBufferWriter{Byte}" /> based on what has been written so far.
/// In the case of Stream, this writes the data to the stream and flushes it asynchronously, while monitoring cancellation requests.
/// </remarks>
/// <exception cref="ObjectDisposedException">
/// The instance of <see cref="Utf8JsonWriter"/> has been disposed.
/// </exception>
public async Task FlushAsync(CancellationToken cancellationToken = default)
{
CheckNotDisposed();
_memory = default;
if (_stream != null)
{
Debug.Assert(_arrayBufferWriter != null);
if (BytesPending != 0)
{
_arrayBufferWriter.Advance(BytesPending);
BytesPending = 0;
#if NET
await _stream.WriteAsync(_arrayBufferWriter.WrittenMemory, cancellationToken).ConfigureAwait(false);
#else
Debug.Assert(_arrayBufferWriter.WrittenMemory.Length == _arrayBufferWriter.WrittenCount);
bool result = MemoryMarshal.TryGetArray(_arrayBufferWriter.WrittenMemory, out ArraySegment<byte> underlyingBuffer);
Debug.Assert(result);
Debug.Assert(underlyingBuffer.Offset == 0);
Debug.Assert(_arrayBufferWriter.WrittenCount == underlyingBuffer.Count);
await _stream.WriteAsync(underlyingBuffer.Array, underlyingBuffer.Offset, underlyingBuffer.Count, cancellationToken).ConfigureAwait(false);
#endif
BytesCommitted += _arrayBufferWriter.WrittenCount;
_arrayBufferWriter.Clear();
}
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
else
{
Debug.Assert(_output != null);
if (BytesPending != 0)
{
_output.Advance(BytesPending);
BytesCommitted += BytesPending;
BytesPending = 0;
}
}
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartArray()
{
WriteStart(JsonConstants.OpenBracket);
_tokenType = JsonTokenType.StartArray;
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartObject()
{
WriteStart(JsonConstants.OpenBrace);
_tokenType = JsonTokenType.StartObject;
}
private void WriteStart(byte token)
{
if (CurrentDepth >= _options.MaxDepth)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.DepthTooLarge, _currentDepth, _options.MaxDepth, token: default, tokenType: default);
if (_options.IndentedOrNotSkipValidation)
{
WriteStartSlow(token);
}
else
{
WriteStartMinimized(token);
}
_currentDepth &= JsonConstants.RemoveFlagsBitMask;
_currentDepth++;
}
private void WriteStartMinimized(byte token)
{
if (_memory.Length - BytesPending < 2) // 1 start token, and optionally, 1 list separator
{
Grow(2);
}
Span<byte> output = _memory.Span;
if (_currentDepth < 0)
{
output[BytesPending++] = JsonConstants.ListSeparator;
}
output[BytesPending++] = token;
}
private void WriteStartSlow(byte token)
{
Debug.Assert(_options.Indented || !_options.SkipValidation);
if (_options.Indented)
{
if (!_options.SkipValidation)
{
ValidateStart();
UpdateBitStackOnStart(token);
}
WriteStartIndented(token);
}
else
{
Debug.Assert(!_options.SkipValidation);
ValidateStart();
UpdateBitStackOnStart(token);
WriteStartMinimized(token);
}
}
private void ValidateStart()
{
if (_inObject)
{
if (_tokenType != JsonTokenType.PropertyName)
{
Debug.Assert(_tokenType != JsonTokenType.None && _tokenType != JsonTokenType.StartArray);
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotStartObjectArrayWithoutProperty, currentDepth: default, maxDepth: _options.MaxDepth, token: default, _tokenType);
}
}
else
{
Debug.Assert(_tokenType != JsonTokenType.PropertyName);
Debug.Assert(_tokenType != JsonTokenType.StartObject);
// It is more likely for CurrentDepth to not equal 0 when writing valid JSON, so check that first to rely on short-circuiting and return quickly.
if (CurrentDepth == 0 && _tokenType != JsonTokenType.None)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose, currentDepth: default, maxDepth: _options.MaxDepth, token: default, _tokenType);
}
}
}
private void WriteStartIndented(byte token)
{
int indent = Indentation;
Debug.Assert(indent <= _indentLength * _options.MaxDepth);
int minRequired = indent + 1; // 1 start token
int maxRequired = minRequired + 3; // Optionally, 1 list separator and 1-2 bytes for new line
if (_memory.Length - BytesPending < maxRequired)
{
Grow(maxRequired);
}
Span<byte> output = _memory.Span;
if (_currentDepth < 0)
{
output[BytesPending++] = JsonConstants.ListSeparator;
}
if (_tokenType is not JsonTokenType.PropertyName and not JsonTokenType.None || _commentAfterNoneOrPropertyName)
{
WriteNewLine(output);
WriteIndentation(output.Slice(BytesPending), indent);
BytesPending += indent;
}
output[BytesPending++] = token;
}
/// <summary>
/// Writes the beginning of a JSON array with a pre-encoded property name as the key.
/// </summary>
/// <param name="propertyName">The JSON-encoded name of the property to write.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartArray(JsonEncodedText propertyName)
{
WriteStartHelper(propertyName.EncodedUtf8Bytes, JsonConstants.OpenBracket);
_tokenType = JsonTokenType.StartArray;
}
/// <summary>
/// Writes the beginning of a JSON object with a pre-encoded property name as the key.
/// </summary>
/// <param name="propertyName">The JSON-encoded name of the property to write.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartObject(JsonEncodedText propertyName)
{
WriteStartHelper(propertyName.EncodedUtf8Bytes, JsonConstants.OpenBrace);
_tokenType = JsonTokenType.StartObject;
}
private void WriteStartHelper(ReadOnlySpan<byte> utf8PropertyName, byte token)
{
Debug.Assert(utf8PropertyName.Length <= JsonConstants.MaxUnescapedTokenSize);
ValidateDepth();
WriteStartByOptions(utf8PropertyName, token);
_currentDepth &= JsonConstants.RemoveFlagsBitMask;
_currentDepth++;
}
/// <summary>
/// Writes the beginning of a JSON array with a property name as the key.
/// </summary>
/// <param name="utf8PropertyName">The UTF-8 encoded property name of the JSON array to be written.</param>
/// <remarks>
/// The property name is escaped before writing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the specified property name is too large.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartArray(ReadOnlySpan<byte> utf8PropertyName)
{
ValidatePropertyNameAndDepth(utf8PropertyName);
WriteStartEscape(utf8PropertyName, JsonConstants.OpenBracket);
_currentDepth &= JsonConstants.RemoveFlagsBitMask;
_currentDepth++;
_tokenType = JsonTokenType.StartArray;
}
/// <summary>
/// Writes the beginning of a JSON object with a property name as the key.
/// </summary>
/// <param name="utf8PropertyName">The UTF-8 encoded property name of the JSON object to be written.</param>
/// <remarks>
/// The property name is escaped before writing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the specified property name is too large.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartObject(ReadOnlySpan<byte> utf8PropertyName)
{
ValidatePropertyNameAndDepth(utf8PropertyName);
WriteStartEscape(utf8PropertyName, JsonConstants.OpenBrace);
_currentDepth &= JsonConstants.RemoveFlagsBitMask;
_currentDepth++;
_tokenType = JsonTokenType.StartObject;
}
private void WriteStartEscape(ReadOnlySpan<byte> utf8PropertyName, byte token)
{
int propertyIdx = JsonWriterHelper.NeedsEscaping(utf8PropertyName, _options.Encoder);
Debug.Assert(propertyIdx >= -1 && propertyIdx < utf8PropertyName.Length);
if (propertyIdx != -1)
{
WriteStartEscapeProperty(utf8PropertyName, token, propertyIdx);
}
else
{
WriteStartByOptions(utf8PropertyName, token);
}
}
private void WriteStartByOptions(ReadOnlySpan<byte> utf8PropertyName, byte token)
{
ValidateWritingProperty(token);
if (_options.Indented)
{
WritePropertyNameIndented(utf8PropertyName, token);
}
else
{
WritePropertyNameMinimized(utf8PropertyName, token);
}
}
private void WriteStartEscapeProperty(ReadOnlySpan<byte> utf8PropertyName, byte token, int firstEscapeIndexProp)
{
Debug.Assert(int.MaxValue / JsonConstants.MaxExpansionFactorWhileEscaping >= utf8PropertyName.Length);
Debug.Assert(firstEscapeIndexProp >= 0 && firstEscapeIndexProp < utf8PropertyName.Length);
byte[]? propertyArray = null;
int length = JsonWriterHelper.GetMaxEscapedLength(utf8PropertyName.Length, firstEscapeIndexProp);
Span<byte> escapedPropertyName = length <= JsonConstants.StackallocByteThreshold ?
stackalloc byte[JsonConstants.StackallocByteThreshold] :
(propertyArray = ArrayPool<byte>.Shared.Rent(length));
JsonWriterHelper.EscapeString(utf8PropertyName, escapedPropertyName, firstEscapeIndexProp, _options.Encoder, out int written);
WriteStartByOptions(escapedPropertyName.Slice(0, written), token);
if (propertyArray != null)
{
ArrayPool<byte>.Shared.Return(propertyArray);
}
}
/// <summary>
/// Writes the beginning of a JSON array with a property name as the key.
/// </summary>
/// <param name="propertyName">The name of the property to write.</param>
/// <remarks>
/// The property name is escaped before writing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the specified property name is too large.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The <paramref name="propertyName"/> parameter is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartArray(string propertyName)
{
if (propertyName is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(propertyName));
}
WriteStartArray(propertyName.AsSpan());
}
/// <summary>
/// Writes the beginning of a JSON object with a property name as the key.
/// </summary>
/// <param name="propertyName">The name of the property to write.</param>
/// <remarks>
/// The property name is escaped before writing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the specified property name is too large.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The <paramref name="propertyName"/> parameter is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartObject(string propertyName)
{
if (propertyName is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(propertyName));
}
WriteStartObject(propertyName.AsSpan());
}
/// <summary>
/// Writes the beginning of a JSON array with a property name as the key.
/// </summary>
/// <param name="propertyName">The name of the property to write.</param>
/// <remarks>
/// The property name is escaped before writing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the specified property name is too large.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartArray(ReadOnlySpan<char> propertyName)
{
ValidatePropertyNameAndDepth(propertyName);
WriteStartEscape(propertyName, JsonConstants.OpenBracket);
_currentDepth &= JsonConstants.RemoveFlagsBitMask;
_currentDepth++;
_tokenType = JsonTokenType.StartArray;
}
/// <summary>
/// Writes the beginning of a JSON object with a property name as the key.
/// </summary>
/// <param name="propertyName">The name of the property to write.</param>
/// <remarks>
/// The property name is escaped before writing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the specified property name is too large.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the depth of the JSON has exceeded the maximum depth of 1000
/// OR if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteStartObject(ReadOnlySpan<char> propertyName)
{
ValidatePropertyNameAndDepth(propertyName);
WriteStartEscape(propertyName, JsonConstants.OpenBrace);
_currentDepth &= JsonConstants.RemoveFlagsBitMask;
_currentDepth++;
_tokenType = JsonTokenType.StartObject;
}
private void WriteStartEscape(ReadOnlySpan<char> propertyName, byte token)
{
int propertyIdx = JsonWriterHelper.NeedsEscaping(propertyName, _options.Encoder);
Debug.Assert(propertyIdx >= -1 && propertyIdx < propertyName.Length);
if (propertyIdx != -1)
{
WriteStartEscapeProperty(propertyName, token, propertyIdx);
}
else
{
WriteStartByOptions(propertyName, token);
}
}
private void WriteStartByOptions(ReadOnlySpan<char> propertyName, byte token)
{
ValidateWritingProperty(token);
if (_options.Indented)
{
WritePropertyNameIndented(propertyName, token);
}
else
{
WritePropertyNameMinimized(propertyName, token);
}
}
private void WriteStartEscapeProperty(ReadOnlySpan<char> propertyName, byte token, int firstEscapeIndexProp)
{
Debug.Assert(int.MaxValue / JsonConstants.MaxExpansionFactorWhileEscaping >= propertyName.Length);
Debug.Assert(firstEscapeIndexProp >= 0 && firstEscapeIndexProp < propertyName.Length);
char[]? propertyArray = null;
int length = JsonWriterHelper.GetMaxEscapedLength(propertyName.Length, firstEscapeIndexProp);
Span<char> escapedPropertyName = length <= JsonConstants.StackallocCharThreshold ?
stackalloc char[JsonConstants.StackallocCharThreshold] :
(propertyArray = ArrayPool<char>.Shared.Rent(length));
JsonWriterHelper.EscapeString(propertyName, escapedPropertyName, firstEscapeIndexProp, _options.Encoder, out int written);
WriteStartByOptions(escapedPropertyName.Slice(0, written), token);
if (propertyArray != null)
{
ArrayPool<char>.Shared.Return(propertyArray);
}
}
/// <summary>
/// Writes the end of a JSON array.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteEndArray()
{
WriteEnd(JsonConstants.CloseBracket);
_tokenType = JsonTokenType.EndArray;
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this would result in invalid JSON being written (while validation is enabled).
/// </exception>
public void WriteEndObject()
{
WriteEnd(JsonConstants.CloseBrace);
_tokenType = JsonTokenType.EndObject;
}
private void WriteEnd(byte token)
{
if (_options.IndentedOrNotSkipValidation)
{
WriteEndSlow(token);
}
else
{
WriteEndMinimized(token);
}
SetFlagToAddListSeparatorBeforeNextItem();
// Necessary if WriteEndX is called without a corresponding WriteStartX first.
if (CurrentDepth != 0)
{
_currentDepth--;
}
}
private void WriteEndMinimized(byte token)
{
if (_memory.Length - BytesPending < 1) // 1 end token
{
Grow(1);
}
Span<byte> output = _memory.Span;
output[BytesPending++] = token;
}
private void WriteEndSlow(byte token)
{
Debug.Assert(_options.Indented || !_options.SkipValidation);
if (_options.Indented)
{
if (!_options.SkipValidation)
{
ValidateEnd(token);
}
WriteEndIndented(token);
}
else
{
Debug.Assert(!_options.SkipValidation);
ValidateEnd(token);
WriteEndMinimized(token);
}
}
private void ValidateEnd(byte token)
{
if (_bitStack.CurrentDepth <= 0 || _tokenType == JsonTokenType.PropertyName)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, currentDepth: default, maxDepth: _options.MaxDepth, token, _tokenType);
if (token == JsonConstants.CloseBracket)
{
if (_inObject)
{
Debug.Assert(_tokenType != JsonTokenType.None);
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, currentDepth: default, maxDepth: _options.MaxDepth, token, _tokenType);
}
}
else
{
Debug.Assert(token == JsonConstants.CloseBrace);
if (!_inObject)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.MismatchedObjectArray, currentDepth: default, maxDepth: _options.MaxDepth, token, _tokenType);
}
}
_inObject = _bitStack.Pop();
}
private void WriteEndIndented(byte token)
{
// Do not format/indent empty JSON object/array.
if (_tokenType == JsonTokenType.StartObject || _tokenType == JsonTokenType.StartArray)
{
WriteEndMinimized(token);
}
else
{
int indent = Indentation;
// Necessary if WriteEndX is called without a corresponding WriteStartX first.
if (indent != 0)
{
// The end token should be at an outer indent and since we haven't updated