/
JsonArray.cs
366 lines (314 loc) · 12.6 KB
/
JsonArray.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
// 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.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization.Converters;
using System.Threading;
namespace System.Text.Json.Nodes
{
/// <summary>
/// Represents a mutable JSON array.
/// </summary>
/// <remarks>
/// It is safe to perform multiple concurrent read operations on a <see cref="JsonArray"/>,
/// but issues can occur if the collection is modified while it's being read.
/// </remarks>
[DebuggerDisplay("JsonArray[{List.Count}]")]
[DebuggerTypeProxy(typeof(DebugView))]
public sealed partial class JsonArray : JsonNode
{
private JsonElement? _jsonElement;
private List<JsonNode?>? _list;
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class that is empty.
/// </summary>
/// <param name="options">Options to control the behavior.</param>
public JsonArray(JsonNodeOptions? options = null) : base(options) { }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class that contains items from the specified params array.
/// </summary>
/// <param name="options">Options to control the behavior.</param>
/// <param name="items">The items to add to the new <see cref="JsonArray"/>.</param>
public JsonArray(JsonNodeOptions options, params JsonNode?[] items) : base(options)
{
InitializeFromArray(items);
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class that contains items from the specified array.
/// </summary>
/// <param name="items">The items to add to the new <see cref="JsonArray"/>.</param>
public JsonArray(params JsonNode?[] items) : base()
{
InitializeFromArray(items);
}
internal override JsonValueKind GetValueKindCore() => JsonValueKind.Array;
internal override JsonNode DeepCloneCore()
{
GetUnderlyingRepresentation(out List<JsonNode?>? list, out JsonElement? jsonElement);
if (list is null)
{
return jsonElement.HasValue
? new JsonArray(jsonElement.Value.Clone(), Options)
: new JsonArray(Options);
}
var jsonArray = new JsonArray(Options)
{
_list = new List<JsonNode?>(list.Count)
};
for (int i = 0; i < list.Count; i++)
{
jsonArray.Add(list[i]?.DeepCloneCore());
}
return jsonArray;
}
internal override bool DeepEqualsCore(JsonNode? node)
{
switch (node)
{
case null or JsonObject:
return false;
case JsonValue value:
// JsonValue instances have special comparison semantics, dispatch to their implementation.
return value.DeepEqualsCore(this);
case JsonArray array:
List<JsonNode?> currentList = List;
List<JsonNode?> otherList = array.List;
if (currentList.Count != otherList.Count)
{
return false;
}
for (int i = 0; i < currentList.Count; i++)
{
if (!DeepEquals(currentList[i], otherList[i]))
{
return false;
}
}
return true;
default:
Debug.Fail("Impossible case");
return false;
}
}
internal int GetElementIndex(JsonNode? node)
{
return List.IndexOf(node);
}
/// <summary>
/// Returns an enumerable that wraps calls to <see cref="JsonNode.GetValue{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the value to obtain from the <see cref="JsonValue"/>.</typeparam>
/// <returns>An enumerable iterating over values of the array.</returns>
public IEnumerable<T> GetValues<T>()
{
foreach (JsonNode? item in List)
{
yield return item is null ? (T)(object?)null! : item.GetValue<T>();
}
}
private void InitializeFromArray(JsonNode?[] items)
{
var list = new List<JsonNode?>(items);
for (int i = 0; i < items.Length; i++)
{
items[i]?.AssignParent(this);
}
_list = list;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class that contains items from the specified <see cref="JsonElement"/>.
/// </summary>
/// <returns>
/// The new instance of the <see cref="JsonArray"/> class that contains items from the specified <see cref="JsonElement"/>.
/// </returns>
/// <param name="element">The <see cref="JsonElement"/>.</param>
/// <param name="options">Options to control the behavior.</param>
/// <exception cref="InvalidOperationException">
/// The <paramref name="element"/> is not a <see cref="JsonValueKind.Array"/>.
/// </exception>
public static JsonArray? Create(JsonElement element, JsonNodeOptions? options = null)
{
return element.ValueKind switch
{
JsonValueKind.Null => null,
JsonValueKind.Array => new JsonArray(element, options),
_ => throw new InvalidOperationException(SR.Format(SR.NodeElementWrongType, nameof(JsonValueKind.Array))),
};
}
internal JsonArray(JsonElement element, JsonNodeOptions? options = null) : base(options)
{
Debug.Assert(element.ValueKind == JsonValueKind.Array);
_jsonElement = element;
}
/// <summary>
/// Adds an object to the end of the <see cref="JsonArray"/>.
/// </summary>
/// <typeparam name="T">The type of object to be added.</typeparam>
/// <param name="value">
/// The object to be added to the end of the <see cref="JsonArray"/>.
/// </param>
[RequiresUnreferencedCode(JsonValue.CreateUnreferencedCodeMessage)]
[RequiresDynamicCode(JsonValue.CreateDynamicCodeMessage)]
public void Add<T>(T? value)
{
JsonNode? nodeToAdd = ConvertFromValue(value, Options);
Add(nodeToAdd);
}
/// <summary>
/// Gets or creates the underlying list containing the element nodes of the array.
/// </summary>
internal List<JsonNode?> List => _list is { } list ? list : InitializeList();
internal JsonNode? GetItem(int index)
{
return List[index];
}
internal void SetItem(int index, JsonNode? value)
{
value?.AssignParent(this);
DetachParent(List[index]);
List[index] = value;
}
internal override void GetPath(ref ValueStringBuilder path, JsonNode? child)
{
Parent?.GetPath(ref path, this);
if (child != null)
{
int index = List.IndexOf(child);
Debug.Assert(index >= 0);
path.Append('[');
#if NETCOREAPP
Span<char> chars = stackalloc char[JsonConstants.MaximumFormatUInt32Length];
bool formatted = ((uint)index).TryFormat(chars, out int charsWritten);
Debug.Assert(formatted);
path.Append(chars.Slice(0, charsWritten));
#else
path.Append(index.ToString());
#endif
path.Append(']');
}
}
/// <inheritdoc/>
public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null)
{
if (writer is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(writer));
}
GetUnderlyingRepresentation(out List<JsonNode?>? list, out JsonElement? jsonElement);
if (list is null && jsonElement.HasValue)
{
jsonElement.Value.WriteTo(writer);
}
else
{
writer.WriteStartArray();
foreach (JsonNode? element in List)
{
if (element is null)
{
writer.WriteNullValue();
}
else
{
element.WriteTo(writer, options);
}
}
writer.WriteEndArray();
}
}
private List<JsonNode?> InitializeList()
{
GetUnderlyingRepresentation(out List<JsonNode?>? list, out JsonElement? jsonElement);
if (list is null)
{
if (jsonElement.HasValue)
{
JsonElement jElement = jsonElement.Value;
Debug.Assert(jElement.ValueKind == JsonValueKind.Array);
list = new List<JsonNode?>(jElement.GetArrayLength());
foreach (JsonElement element in jElement.EnumerateArray())
{
JsonNode? node = JsonNodeConverter.Create(element, Options);
node?.AssignParent(this);
list.Add(node);
}
}
else
{
list = new();
}
// Ensure _jsonElement is written to after _list
_list = list;
Interlocked.MemoryBarrier();
_jsonElement = null;
}
return list;
}
/// <summary>
/// Provides a coherent view of the underlying representation of the current node.
/// The jsonElement value should be consumed if and only if the list value is null.
/// </summary>
private void GetUnderlyingRepresentation(out List<JsonNode?>? list, out JsonElement? jsonElement)
{
// Because JsonElement cannot be read atomically there might be torn reads,
// however the order of read/write operations guarantees that that's only
// possible if the value of _list is non-null.
jsonElement = _jsonElement;
Interlocked.MemoryBarrier();
list = _list;
}
[ExcludeFromCodeCoverage] // Justification = "Design-time"
private sealed class DebugView
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly JsonArray _node;
public DebugView(JsonArray node)
{
_node = node;
}
public string Json => _node.ToJsonString();
public string Path => _node.GetPath();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private DebugViewItem[] Items
{
get
{
DebugViewItem[] properties = new DebugViewItem[_node.List.Count];
for (int i = 0; i < _node.List.Count; i++)
{
properties[i].Value = _node.List[i];
}
return properties;
}
}
[DebuggerDisplay("{Display,nq}")]
private struct DebugViewItem
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public JsonNode? Value;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string Display
{
get
{
if (Value == null)
{
return $"null";
}
if (Value is JsonValue)
{
return Value.ToJsonString();
}
if (Value is JsonObject jsonObject)
{
return $"JsonObject[{jsonObject.Count}]";
}
JsonArray jsonArray = (JsonArray)Value;
return $"JsonArray[{jsonArray.List.Count}]";
}
}
}
}
}
}