-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
ReadStack.cs
359 lines (308 loc) · 12.9 KB
/
ReadStack.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
[DebuggerDisplay("Path:{JsonPath()} Current: ConverterStrategy.{Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterStrategy}, {Current.JsonTypeInfo.Type.Name}")]
internal struct ReadStack
{
internal static readonly char[] SpecialCharacters = { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' };
/// <summary>
/// Exposes the stackframe that is currently active.
/// </summary>
public ReadStackFrame Current;
/// <summary>
/// Buffer containing all frames in the stack. For performance it is only populated for serialization depths > 1.
/// </summary>
private ReadStackFrame[] _stack;
/// <summary>
/// Tracks the current depth of the stack.
/// </summary>
private int _count;
/// <summary>
/// If not zero, indicates that the stack is part of a re-entrant continuation of given depth.
/// </summary>
private int _continuationCount;
// State cache when deserializing objects with parameterized constructors.
private List<ArgumentState>? _ctorArgStateCache;
/// <summary>
/// Bytes consumed in the current loop.
/// </summary>
public long BytesConsumed;
/// <summary>
/// Indicates that the state still contains suspended frames waiting re-entry.
/// </summary>
public bool IsContinuation => _continuationCount != 0;
/// <summary>
/// Internal flag to let us know that we need to read ahead in the inner read loop.
/// </summary>
public bool ReadAhead;
// The bag of preservable references.
public ReferenceResolver ReferenceResolver;
/// <summary>
/// Whether we need to read ahead in the inner read loop.
/// </summary>
public bool SupportContinuation;
/// <summary>
/// Whether we can read without the need of saving state for stream and preserve references cases.
/// </summary>
public bool UseFastPath;
/// <summary>
/// Ensures that the stack buffer has sufficient capacity to hold an additional frame.
/// </summary>
private void EnsurePushCapacity()
{
if (_stack is null)
{
_stack = new ReadStackFrame[4];
}
else if (_count - 1 == _stack.Length)
{
Array.Resize(ref _stack, 2 * _stack.Length);
}
}
public void Initialize(Type type, JsonSerializerOptions options, bool supportContinuation)
{
JsonTypeInfo jsonTypeInfo = options.GetOrAddClassForRootType(type);
Initialize(jsonTypeInfo, supportContinuation);
}
internal void Initialize(JsonTypeInfo jsonTypeInfo, bool supportContinuation = false)
{
Current.JsonTypeInfo = jsonTypeInfo;
// The initial JsonPropertyInfo will be used to obtain the converter.
Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo;
Current.NumberHandling = Current.JsonPropertyInfo.NumberHandling;
JsonSerializerOptions options = jsonTypeInfo.Options;
bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve;
if (preserveReferences)
{
ReferenceResolver = options.ReferenceHandler!.CreateResolver(writing: false);
}
SupportContinuation = supportContinuation;
UseFastPath = !supportContinuation && !preserveReferences;
}
public void Push()
{
if (_continuationCount == 0)
{
if (_count == 0)
{
// The first stack frame is held in Current.
_count = 1;
}
else
{
JsonTypeInfo jsonTypeInfo;
JsonNumberHandling? numberHandling = Current.NumberHandling;
ConverterStrategy converterStrategy = Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterStrategy;
if (converterStrategy == ConverterStrategy.Object)
{
if (Current.JsonPropertyInfo != null)
{
jsonTypeInfo = Current.JsonPropertyInfo.RuntimeTypeInfo;
}
else
{
jsonTypeInfo = Current.CtorArgumentState!.JsonParameterInfo!.RuntimeTypeInfo;
}
}
else if (converterStrategy == ConverterStrategy.Value)
{
// Although ConverterStrategy.Value doesn't push, a custom custom converter may re-enter serialization.
jsonTypeInfo = Current.JsonPropertyInfo!.RuntimeTypeInfo;
}
else
{
Debug.Assert(((ConverterStrategy.Enumerable | ConverterStrategy.Dictionary) & converterStrategy) != 0);
jsonTypeInfo = Current.JsonTypeInfo.ElementTypeInfo!;
}
EnsurePushCapacity();
_stack[_count - 1] = Current;
Current = default;
_count++;
Current.JsonTypeInfo = jsonTypeInfo;
Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo;
// Allow number handling on property to win over handling on type.
Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.NumberHandling;
}
}
else
{
// We are re-entering a continuation, adjust indices accordingly
if (_count++ > 0)
{
Current = _stack[_count - 1];
}
// check if we are done
if (_continuationCount == _count)
{
_continuationCount = 0;
}
}
SetConstructorArgumentState();
#if DEBUG
// Ensure the method is always exercised in debug builds.
_ = JsonPath();
#endif
}
public void Pop(bool success)
{
Debug.Assert(_count > 0);
if (!success)
{
// Check if we need to initialize the continuation.
if (_continuationCount == 0)
{
if (_count == 1)
{
// No need to copy any frames here.
_continuationCount = 1;
_count = 0;
return;
}
// Need to push the Current frame to the stack,
// ensure that we have sufficient capacity.
EnsurePushCapacity();
_continuationCount = _count--;
}
else if (--_count == 0)
{
// reached the root, no need to copy frames.
return;
}
_stack[_count] = Current;
Current = _stack[_count - 1];
}
else
{
Debug.Assert(_continuationCount == 0);
if (--_count > 0)
{
Current = _stack[_count - 1];
}
}
SetConstructorArgumentState();
}
// Return a JSONPath using simple dot-notation when possible. When special characters are present, bracket-notation is used:
// $.x.y[0].z
// $['PropertyName.With.Special.Chars']
public string JsonPath()
{
StringBuilder sb = new StringBuilder("$");
// If a continuation, always report back full stack which does not use Current for the last frame.
int count = Math.Max(_count, _continuationCount + 1);
for (int i = 0; i < count - 1; i++)
{
AppendStackFrame(sb, ref _stack[i]);
}
if (_continuationCount == 0)
{
AppendStackFrame(sb, ref Current);
}
return sb.ToString();
static void AppendStackFrame(StringBuilder sb, ref ReadStackFrame frame)
{
// Append the property name.
string? propertyName = GetPropertyName(ref frame);
AppendPropertyName(sb, propertyName);
if (frame.JsonTypeInfo != null && frame.IsProcessingEnumerable())
{
if (frame.ReturnValue is not IEnumerable enumerable)
{
return;
}
// For continuation scenarios only, before or after all elements are read, the exception is not within the array.
if (frame.ObjectState == StackFrameObjectState.None ||
frame.ObjectState == StackFrameObjectState.CreatedObject ||
frame.ObjectState == StackFrameObjectState.ReadElements)
{
sb.Append('[');
sb.Append(GetCount(enumerable));
sb.Append(']');
}
}
}
static int GetCount(IEnumerable enumerable)
{
if (enumerable is ICollection collection)
{
return collection.Count;
}
int count = 0;
IEnumerator enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
count++;
}
return count;
}
static void AppendPropertyName(StringBuilder sb, string? propertyName)
{
if (propertyName != null)
{
if (propertyName.IndexOfAny(SpecialCharacters) != -1)
{
sb.Append(@"['");
sb.Append(propertyName);
sb.Append(@"']");
}
else
{
sb.Append('.');
sb.Append(propertyName);
}
}
}
static string? GetPropertyName(ref ReadStackFrame frame)
{
string? propertyName = null;
// Attempt to get the JSON property name from the frame.
byte[]? utf8PropertyName = frame.JsonPropertyName;
if (utf8PropertyName == null)
{
if (frame.JsonPropertyNameAsString != null)
{
// Attempt to get the JSON property name set manually for dictionary
// keys and KeyValuePair property names.
propertyName = frame.JsonPropertyNameAsString;
}
else
{
// Attempt to get the JSON property name from the JsonPropertyInfo or JsonParameterInfo.
utf8PropertyName = frame.JsonPropertyInfo?.NameAsUtf8Bytes ??
frame.CtorArgumentState?.JsonParameterInfo?.NameAsUtf8Bytes;
}
}
if (utf8PropertyName != null)
{
propertyName = JsonHelpers.Utf8GetString(utf8PropertyName);
}
return propertyName;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetConstructorArgumentState()
{
if (Current.JsonTypeInfo.IsObjectWithParameterizedCtor)
{
// A zero index indicates a new stack frame.
if (Current.CtorArgumentStateIndex == 0)
{
_ctorArgStateCache ??= new List<ArgumentState>();
var newState = new ArgumentState();
_ctorArgStateCache.Add(newState);
(Current.CtorArgumentStateIndex, Current.CtorArgumentState) = (_ctorArgStateCache.Count, newState);
}
else
{
Current.CtorArgumentState = _ctorArgStateCache![Current.CtorArgumentStateIndex - 1];
}
}
}
}
}