| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | #if NET |
| | | 8 | | using System.Runtime.CompilerServices; |
| | | 9 | | #endif |
| | | 10 | | using System.Text; |
| | | 11 | | using System.Text.Json.Serialization.Metadata; |
| | | 12 | | |
| | | 13 | | namespace System.Text.Json.Serialization |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Classifies JSON payloads into union case types by comparing their JSON value types |
| | | 17 | | /// and, for JSON objects, their property names. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <remarks> |
| | | 20 | | /// <para> |
| | | 21 | | /// The default union classification distinguishes cases that use different JSON token kinds, |
| | | 22 | | /// such as a string and an array. This classifier adds structural classification for .NET |
| | | 23 | | /// POCOs configured to serialize as JSON objects. |
| | | 24 | | /// </para> |
| | | 25 | | /// <para> |
| | | 26 | | /// To classify an object, the classifier starts with every POCO case as a candidate. For each |
| | | 27 | | /// property name at the level of the current JSON object, it eliminates candidates that do not |
| | | 28 | | /// define a matching property. Property values and nested content are not examined, and |
| | | 29 | | /// property order does not affect the result. Name matching honors |
| | | 30 | | /// <see cref="JsonSerializerOptions.PropertyNameCaseInsensitive"/>. |
| | | 31 | | /// </para> |
| | | 32 | | /// <para> |
| | | 33 | | /// After reading the object, candidates missing a required property are eliminated. Missing |
| | | 34 | | /// optional properties have no effect. A property name that is not defined by any case |
| | | 35 | | /// eliminates only cases configured with <see cref="JsonUnmappedMemberHandling.Disallow"/>. |
| | | 36 | | /// </para> |
| | | 37 | | /// <para> |
| | | 38 | | /// The classifier selects the case when exactly one candidate remains. Classification fails |
| | | 39 | | /// when no candidates or multiple candidates remain. Configurations containing a case that can |
| | | 40 | | /// never be selected uniquely are rejected when the classifier is created. |
| | | 41 | | /// </para> |
| | | 42 | | /// <para> |
| | | 43 | | /// This classifier supports union types only. Nested union cases, polymorphic cases, and |
| | | 44 | | /// reference-preserving deserialization are not supported. |
| | | 45 | | /// </para> |
| | | 46 | | /// </remarks> |
| | | 47 | | public class JsonUnionTypeStructuralClassifier : JsonTypeClassifierFactory |
| | | 48 | | { |
| | | 49 | | /// <summary> |
| | | 50 | | /// Initializes a new instance of the <see cref="JsonUnionTypeStructuralClassifier"/> class. |
| | | 51 | | /// </summary> |
| | 0 | 52 | | public JsonUnionTypeStructuralClassifier() |
| | 0 | 53 | | { |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <inheritdoc/> |
| | | 57 | | public override bool CanClassify(JsonTypeClassifierContext context) |
| | 0 | 58 | | { |
| | 0 | 59 | | ArgumentNullException.ThrowIfNull(context); |
| | 0 | 60 | | return context.Kind is JsonTypeClassifierKind.Union; |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <inheritdoc/> |
| | | 64 | | public override JsonTypeClassifier CreateJsonClassifier( |
| | | 65 | | JsonTypeClassifierContext context, |
| | | 66 | | JsonSerializerOptions options) |
| | 0 | 67 | | { |
| | 0 | 68 | | ArgumentNullException.ThrowIfNull(context); |
| | 0 | 69 | | ArgumentNullException.ThrowIfNull(options); |
| | | 70 | | |
| | 0 | 71 | | if (context.Kind is not JsonTypeClassifierKind.Union) |
| | 0 | 72 | | { |
| | 0 | 73 | | ThrowHelper.ThrowInvalidOperationException_UnionTypeStructuralClassifierOnlyForUnions(context.DeclaringT |
| | | 74 | | } |
| | | 75 | | |
| | 0 | 76 | | if (options.ReferenceHandlingStrategy is JsonKnownReferenceHandler.Preserve) |
| | 0 | 77 | | { |
| | 0 | 78 | | ThrowHelper.ThrowNotSupportedException_UnionTypeStructuralClassifierPreserveReferencesNotSupported(conte |
| | | 79 | | } |
| | | 80 | | |
| | 0 | 81 | | StructuralClassifier classifier = BuildStructuralClassifier(context.DeclaringTypeInfo, context.UnionCases, o |
| | 0 | 82 | | return classifier.Classify; |
| | 0 | 83 | | } |
| | | 84 | | |
| | | 85 | | private static StructuralClassifier BuildStructuralClassifier( |
| | | 86 | | JsonTypeInfo unionTypeInfo, |
| | | 87 | | IReadOnlyList<JsonUnionCaseInfo> unionCases, |
| | | 88 | | JsonSerializerOptions options) |
| | 0 | 89 | | { |
| | 0 | 90 | | Type unionType = unionTypeInfo.Type; |
| | 0 | 91 | | JsonNumberHandling? unionNumberHandling = unionTypeInfo.NumberHandling; |
| | | 92 | | |
| | | 93 | | // POCO object cases expose JsonPropertyInfo metadata through JsonTypeInfoKind.Object. |
| | | 94 | | // A non-POCO JSON object case advertises the Object shape without such metadata. |
| | 0 | 95 | | Dictionary<JsonValueType, Type> shapeBasedCases = new(); |
| | 0 | 96 | | List<PocoObjectCase> pocoObjectCaseList = []; |
| | 0 | 97 | | int requiredPropertyCount = 0; |
| | | 98 | | |
| | 0 | 99 | | foreach (JsonUnionCaseInfo unionCase in unionCases) |
| | 0 | 100 | | { |
| | 0 | 101 | | AddCase( |
| | 0 | 102 | | unionType, |
| | 0 | 103 | | unionCase.CaseType, |
| | 0 | 104 | | unionNumberHandling, |
| | 0 | 105 | | options, |
| | 0 | 106 | | shapeBasedCases, |
| | 0 | 107 | | pocoObjectCaseList, |
| | 0 | 108 | | ref requiredPropertyCount); |
| | 0 | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | shapeBasedCases.TryGetValue(JsonValueType.Object, out Type? nonPocoJsonObjectCaseType); |
| | 0 | 112 | | if (nonPocoJsonObjectCaseType is not null && |
| | 0 | 113 | | pocoObjectCaseList is { Count: > 0 }) |
| | 0 | 114 | | { |
| | 0 | 115 | | ThrowHelper.ThrowNotSupportedException_UnionTypeStructuralClassifierAmbiguousCases( |
| | 0 | 116 | | unionType, |
| | 0 | 117 | | pocoObjectCaseList[0].CaseType, |
| | 0 | 118 | | nonPocoJsonObjectCaseType, |
| | 0 | 119 | | JsonValueType.Object); |
| | | 120 | | } |
| | | 121 | | |
| | 0 | 122 | | ValidatePocoObjectCases(unionType, pocoObjectCaseList); |
| | | 123 | | |
| | 0 | 124 | | PocoObjectCase[] pocoObjectCases = [..pocoObjectCaseList]; |
| | 0 | 125 | | Dictionary<byte[], List<PocoPropertyClassifierInfo>> pocoPropertyIndex = new(JsonHelpers.ByteArrayOrdinalCom |
| | 0 | 126 | | Dictionary<string, List<PocoPropertyClassifierInfo>>? caseInsensitivePocoPropertyIndex = null; |
| | | 127 | | |
| | | 128 | | // Keep the ordinal and case-insensitive indexes separate so exact matches can be |
| | | 129 | | // processed first when differently-cased names overlap. |
| | 0 | 130 | | foreach (PocoObjectCase pocoObjectCase in pocoObjectCases) |
| | 0 | 131 | | { |
| | 0 | 132 | | foreach (PocoPropertyClassifierInfo property in pocoObjectCase.Properties) |
| | 0 | 133 | | { |
| | 0 | 134 | | AddPocoPropertyInfo(pocoPropertyIndex, property.NameAsUtf8Bytes, property); |
| | | 135 | | |
| | 0 | 136 | | if (!property.IsCaseSensitive) |
| | 0 | 137 | | { |
| | 0 | 138 | | caseInsensitivePocoPropertyIndex ??= new(StringComparer.OrdinalIgnoreCase); |
| | 0 | 139 | | AddPocoPropertyInfo(caseInsensitivePocoPropertyIndex, property.Name, property); |
| | 0 | 140 | | } |
| | 0 | 141 | | } |
| | 0 | 142 | | } |
| | | 143 | | |
| | 0 | 144 | | return new( |
| | 0 | 145 | | shapeBasedCases, |
| | 0 | 146 | | pocoObjectCases, |
| | 0 | 147 | | pocoPropertyIndex, |
| | 0 | 148 | | caseInsensitivePocoPropertyIndex, |
| | 0 | 149 | | requiredPropertyCount); |
| | | 150 | | |
| | | 151 | | static void AddPocoPropertyInfo<TKey>( |
| | | 152 | | Dictionary<TKey, List<PocoPropertyClassifierInfo>> index, |
| | | 153 | | TKey key, |
| | | 154 | | PocoPropertyClassifierInfo propertyInfo) |
| | | 155 | | where TKey : notnull |
| | 0 | 156 | | { |
| | 0 | 157 | | if (!index.TryGetValue(key, out List<PocoPropertyClassifierInfo>? matches)) |
| | 0 | 158 | | { |
| | 0 | 159 | | matches = []; |
| | 0 | 160 | | index.Add(key, matches); |
| | 0 | 161 | | } |
| | | 162 | | |
| | 0 | 163 | | matches.Add(propertyInfo); |
| | 0 | 164 | | } |
| | 0 | 165 | | } |
| | | 166 | | |
| | | 167 | | private static void AddCase( |
| | | 168 | | Type unionType, |
| | | 169 | | Type caseType, |
| | | 170 | | JsonNumberHandling? unionNumberHandling, |
| | | 171 | | JsonSerializerOptions options, |
| | | 172 | | Dictionary<JsonValueType, Type> shapeBasedCases, |
| | | 173 | | List<PocoObjectCase> pocoObjectCases, |
| | | 174 | | ref int requiredPropertyCount) |
| | 0 | 175 | | { |
| | 0 | 176 | | JsonTypeInfo typeInfo = options.GetTypeInfo(caseType); |
| | 0 | 177 | | JsonNumberHandling? numberHandlingOverride = unionNumberHandling ?? typeInfo.NumberHandling; |
| | 0 | 178 | | if (typeInfo is { IsNullable: true, ElementTypeInfo: JsonTypeInfo elementTypeInfo }) |
| | 0 | 179 | | { |
| | 0 | 180 | | typeInfo = elementTypeInfo; |
| | 0 | 181 | | } |
| | | 182 | | |
| | 0 | 183 | | if (typeInfo.Kind is JsonTypeInfoKind.Union) |
| | 0 | 184 | | { |
| | 0 | 185 | | ThrowHelper.ThrowNotSupportedException_UnionTypeStructuralClassifierCaseNotSupported( |
| | 0 | 186 | | unionType, |
| | 0 | 187 | | caseType); |
| | | 188 | | } |
| | | 189 | | |
| | 0 | 190 | | if (typeInfo.PolymorphismOptions is not null) |
| | 0 | 191 | | { |
| | 0 | 192 | | ThrowHelper.ThrowNotSupportedException_UnionTypeStructuralClassifierCaseNotSupported( |
| | 0 | 193 | | unionType, |
| | 0 | 194 | | caseType); |
| | | 195 | | } |
| | | 196 | | |
| | 0 | 197 | | JsonNumberHandling numberHandling = numberHandlingOverride ?? typeInfo.NumberHandling ?? options.NumberHandl |
| | 0 | 198 | | JsonValueType valueTypes = typeInfo.Converter.GetSupportedJsonValueTypes(numberHandling); |
| | | 199 | | |
| | 0 | 200 | | bool isPocoObjectCase = typeInfo is |
| | 0 | 201 | | { |
| | 0 | 202 | | Kind: JsonTypeInfoKind.Object, |
| | 0 | 203 | | Converter.IsInternalConverter: true, |
| | 0 | 204 | | }; |
| | | 205 | | |
| | 0 | 206 | | ReadOnlySpan<JsonValueType> supportedValueTypes = |
| | 0 | 207 | | [ |
| | 0 | 208 | | JsonValueType.Object, |
| | 0 | 209 | | JsonValueType.Array, |
| | 0 | 210 | | JsonValueType.String, |
| | 0 | 211 | | JsonValueType.Number, |
| | 0 | 212 | | JsonValueType.Boolean, |
| | 0 | 213 | | ]; |
| | | 214 | | |
| | | 215 | | // Token kind is the only discriminator for non-object shapes, so only one case can |
| | | 216 | | // claim each kind. POCO object cases instead participate in property matching. |
| | 0 | 217 | | Debug.Assert((valueTypes & |
| | 0 | 218 | | (JsonValueType.Object | |
| | 0 | 219 | | JsonValueType.Array | |
| | 0 | 220 | | JsonValueType.String | |
| | 0 | 221 | | JsonValueType.Number | |
| | 0 | 222 | | JsonValueType.Boolean)) is not 0); |
| | | 223 | | |
| | 0 | 224 | | foreach (JsonValueType valueType in supportedValueTypes) |
| | 0 | 225 | | { |
| | 0 | 226 | | if ((valueTypes & valueType) is 0) |
| | 0 | 227 | | { |
| | 0 | 228 | | continue; |
| | | 229 | | } |
| | | 230 | | |
| | 0 | 231 | | if (valueType is JsonValueType.Object && isPocoObjectCase) |
| | 0 | 232 | | { |
| | 0 | 233 | | pocoObjectCases.Add(BuildPocoObjectCase( |
| | 0 | 234 | | caseType, |
| | 0 | 235 | | typeInfo, |
| | 0 | 236 | | options, |
| | 0 | 237 | | pocoObjectCases.Count, |
| | 0 | 238 | | ref requiredPropertyCount)); |
| | 0 | 239 | | } |
| | 0 | 240 | | else if (!shapeBasedCases.TryAdd(valueType, caseType)) |
| | 0 | 241 | | { |
| | 0 | 242 | | Type conflictingCaseType = shapeBasedCases[valueType]; |
| | 0 | 243 | | ThrowHelper.ThrowNotSupportedException_UnionTypeStructuralClassifierAmbiguousCases( |
| | 0 | 244 | | unionType, |
| | 0 | 245 | | conflictingCaseType, |
| | 0 | 246 | | caseType, |
| | 0 | 247 | | valueType); |
| | | 248 | | } |
| | 0 | 249 | | } |
| | 0 | 250 | | } |
| | | 251 | | |
| | | 252 | | private static PocoObjectCase BuildPocoObjectCase( |
| | | 253 | | Type caseType, |
| | | 254 | | JsonTypeInfo typeInfo, |
| | | 255 | | JsonSerializerOptions options, |
| | | 256 | | int pocoCaseIndex, |
| | | 257 | | ref int requiredPropertyCount) |
| | 0 | 258 | | { |
| | 0 | 259 | | Debug.Assert(typeInfo.Kind is JsonTypeInfoKind.Object); |
| | | 260 | | |
| | 0 | 261 | | bool caseInsensitive = options.PropertyNameCaseInsensitive; |
| | 0 | 262 | | List<PocoPropertyClassifierInfo> properties = new(typeInfo.Properties.Count); |
| | 0 | 263 | | int requiredCount = 0; |
| | 0 | 264 | | bool hasExtensionData = false; |
| | | 265 | | |
| | 0 | 266 | | foreach (JsonPropertyInfo property in typeInfo.Properties) |
| | 0 | 267 | | { |
| | 0 | 268 | | if (property.IsExtensionData) |
| | 0 | 269 | | { |
| | 0 | 270 | | hasExtensionData = true; |
| | 0 | 271 | | continue; |
| | | 272 | | } |
| | | 273 | | |
| | 0 | 274 | | int requiredPropertyIndex = property.IsRequired ? requiredPropertyCount++ : -1; |
| | 0 | 275 | | properties.Add(new( |
| | 0 | 276 | | property.Name, |
| | 0 | 277 | | property.IsRequired, |
| | 0 | 278 | | isCaseSensitive: !caseInsensitive, |
| | 0 | 279 | | pocoCaseIndex, |
| | 0 | 280 | | requiredPropertyIndex)); |
| | | 281 | | |
| | 0 | 282 | | if (property.IsRequired) |
| | 0 | 283 | | { |
| | 0 | 284 | | requiredCount++; |
| | 0 | 285 | | } |
| | 0 | 286 | | } |
| | | 287 | | |
| | 0 | 288 | | JsonUnmappedMemberHandling unmappedMemberHandling = typeInfo.UnmappedMemberHandling ?? |
| | 0 | 289 | | (hasExtensionData ? JsonUnmappedMemberHandling.Skip : options.UnmappedMemberHandling); |
| | | 290 | | |
| | 0 | 291 | | return new( |
| | 0 | 292 | | caseType, |
| | 0 | 293 | | [..properties], |
| | 0 | 294 | | unmappedMemberHandling is JsonUnmappedMemberHandling.Disallow, |
| | 0 | 295 | | requiredCount); |
| | 0 | 296 | | } |
| | | 297 | | |
| | | 298 | | private static void ValidatePocoObjectCases( |
| | | 299 | | Type unionType, |
| | | 300 | | List<PocoObjectCase> pocoObjectCases) |
| | 0 | 301 | | { |
| | | 302 | | // Reject a case when every object it can accept also satisfies another case, since it |
| | | 303 | | // can never be selected uniquely. This quadratic check runs only during construction |
| | | 304 | | // and is bounded by the union cases declared on the type. |
| | 0 | 305 | | for (int i = 0; i < pocoObjectCases.Count; i++) |
| | 0 | 306 | | { |
| | 0 | 307 | | PocoObjectCase pocoObjectCase = pocoObjectCases[i]; |
| | | 308 | | |
| | 0 | 309 | | for (int j = 0; j < pocoObjectCases.Count; j++) |
| | 0 | 310 | | { |
| | 0 | 311 | | if (i == j) |
| | 0 | 312 | | { |
| | 0 | 313 | | continue; |
| | | 314 | | } |
| | | 315 | | |
| | 0 | 316 | | PocoObjectCase other = pocoObjectCases[j]; |
| | 0 | 317 | | if (pocoObjectCase.IsShadowedBy(other)) |
| | 0 | 318 | | { |
| | 0 | 319 | | ThrowHelper.ThrowNotSupportedException_UnionTypeStructuralClassifierUnreachableObjectCase( |
| | 0 | 320 | | unionType, |
| | 0 | 321 | | pocoObjectCase.CaseType, |
| | 0 | 322 | | other.CaseType); |
| | | 323 | | } |
| | 0 | 324 | | } |
| | 0 | 325 | | } |
| | | 326 | | |
| | 0 | 327 | | } |
| | | 328 | | |
| | | 329 | | /// <summary>Classifies JSON values using precomputed union case metadata.</summary> |
| | | 330 | | private sealed class StructuralClassifier |
| | | 331 | | { |
| | | 332 | | // PocoObjectCaseState is 8 bytes, so this caps the stack-allocated buffer at 128 bytes. |
| | | 333 | | private const int InlinePocoObjectCaseCount = 16; |
| | | 334 | | |
| | | 335 | | private readonly Dictionary<byte[], List<PocoPropertyClassifierInfo>> _pocoPropertyIndex; |
| | | 336 | | private readonly Dictionary<string, List<PocoPropertyClassifierInfo>>? _caseInsensitivePocoPropertyIndex; |
| | | 337 | | private readonly int[] _disallowUnmappedPropertiesPocoCaseIndices; |
| | | 338 | | private readonly Dictionary<JsonValueType, Type> _shapeBasedCases; |
| | | 339 | | private readonly PocoObjectCase[] _pocoObjectCases; |
| | | 340 | | private readonly int _requiredPropertyCount; |
| | | 341 | | |
| | 0 | 342 | | public StructuralClassifier( |
| | 0 | 343 | | Dictionary<JsonValueType, Type> shapeBasedCases, |
| | 0 | 344 | | PocoObjectCase[] pocoObjectCases, |
| | 0 | 345 | | Dictionary<byte[], List<PocoPropertyClassifierInfo>> pocoPropertyIndex, |
| | 0 | 346 | | Dictionary<string, List<PocoPropertyClassifierInfo>>? caseInsensitivePocoPropertyIndex, |
| | 0 | 347 | | int requiredPropertyCount) |
| | 0 | 348 | | { |
| | 0 | 349 | | _shapeBasedCases = shapeBasedCases; |
| | 0 | 350 | | _pocoObjectCases = pocoObjectCases; |
| | 0 | 351 | | _pocoPropertyIndex = pocoPropertyIndex; |
| | 0 | 352 | | _caseInsensitivePocoPropertyIndex = caseInsensitivePocoPropertyIndex; |
| | 0 | 353 | | _requiredPropertyCount = requiredPropertyCount; |
| | | 354 | | |
| | 0 | 355 | | List<int>? disallowUnmappedPropertiesPocoCaseIndices = null; |
| | 0 | 356 | | for (int i = 0; i < pocoObjectCases.Length; i++) |
| | 0 | 357 | | { |
| | 0 | 358 | | if (pocoObjectCases[i].DisallowUnmappedProperties) |
| | 0 | 359 | | { |
| | 0 | 360 | | (disallowUnmappedPropertiesPocoCaseIndices ??= []).Add(i); |
| | 0 | 361 | | } |
| | 0 | 362 | | } |
| | | 363 | | |
| | 0 | 364 | | _disallowUnmappedPropertiesPocoCaseIndices = disallowUnmappedPropertiesPocoCaseIndices?.ToArray() ?? []; |
| | 0 | 365 | | } |
| | | 366 | | |
| | | 367 | | public Type? Classify(ref Utf8JsonReader reader) |
| | 0 | 368 | | { |
| | 0 | 369 | | JsonValueType valueType = reader.TokenType switch |
| | 0 | 370 | | { |
| | 0 | 371 | | JsonTokenType.StartObject => JsonValueType.Object, |
| | 0 | 372 | | JsonTokenType.StartArray => JsonValueType.Array, |
| | 0 | 373 | | JsonTokenType.String => JsonValueType.String, |
| | 0 | 374 | | JsonTokenType.Number => JsonValueType.Number, |
| | 0 | 375 | | JsonTokenType.True or JsonTokenType.False => JsonValueType.Boolean, |
| | 0 | 376 | | _ => JsonValueType.None, |
| | 0 | 377 | | }; |
| | | 378 | | |
| | 0 | 379 | | if (valueType is JsonValueType.Object && _pocoObjectCases is { Length: > 0 }) |
| | 0 | 380 | | { |
| | 0 | 381 | | return ClassifyJsonObject(ref reader); |
| | | 382 | | } |
| | | 383 | | |
| | 0 | 384 | | _shapeBasedCases.TryGetValue(valueType, out Type? caseType); |
| | 0 | 385 | | return caseType; |
| | 0 | 386 | | } |
| | | 387 | | |
| | | 388 | | private Type? ClassifyJsonObject(ref Utf8JsonReader reader) |
| | 0 | 389 | | { |
| | 0 | 390 | | Debug.Assert(reader.TokenType is JsonTokenType.StartObject); |
| | 0 | 391 | | Debug.Assert(_pocoObjectCases.Length is > 0); |
| | | 392 | | |
| | | 393 | | // Begin with every POCO object case as a candidate and eliminate cases using property |
| | | 394 | | // names only. After the complete object is scanned, required properties and |
| | | 395 | | // uniqueness determine the result. |
| | 0 | 396 | | PocoObjectCaseState[]? rentedPocoCaseStates = null; |
| | | 397 | | try |
| | 0 | 398 | | { |
| | 0 | 399 | | scoped Span<PocoObjectCaseState> pocoCaseStates = |
| | 0 | 400 | | _pocoObjectCases.Length <= InlinePocoObjectCaseCount |
| | 0 | 401 | | ? stackalloc PocoObjectCaseState[InlinePocoObjectCaseCount] |
| | 0 | 402 | | : (rentedPocoCaseStates = ArrayPool<PocoObjectCaseState>.Shared.Rent(_pocoObjectCases.Length |
| | 0 | 403 | | pocoCaseStates = pocoCaseStates.Slice(0, _pocoObjectCases.Length); |
| | 0 | 404 | | pocoCaseStates.Clear(); |
| | | 405 | | |
| | 0 | 406 | | scoped Span<ulong> pocoCaseCandidateBuffer = stackalloc ulong[ValueBitArray.ScratchBufferSize]; |
| | 0 | 407 | | ValueBitArray isPocoCaseCandidate = new( |
| | 0 | 408 | | _pocoObjectCases.Length, |
| | 0 | 409 | | pocoCaseCandidateBuffer, |
| | 0 | 410 | | initialWordValue: ulong.MaxValue); |
| | | 411 | | |
| | 0 | 412 | | scoped Span<ulong> pocoCaseMatchesCurrentPropertyBuffer = |
| | 0 | 413 | | stackalloc ulong[ValueBitArray.ScratchBufferSize]; |
| | 0 | 414 | | ValueBitArray pocoCaseMatchesCurrentProperty = |
| | 0 | 415 | | new(_pocoObjectCases.Length, pocoCaseMatchesCurrentPropertyBuffer); |
| | | 416 | | |
| | 0 | 417 | | scoped Span<ulong> requiredPropertySeenBuffer = stackalloc ulong[ValueBitArray.ScratchBufferSize]; |
| | 0 | 418 | | ValueBitArray isRequiredPropertySeen = |
| | 0 | 419 | | new(_requiredPropertyCount, requiredPropertySeenBuffer); |
| | 0 | 420 | | int i = 0; |
| | | 421 | | |
| | 0 | 422 | | while (true) |
| | 0 | 423 | | { |
| | 0 | 424 | | reader.ReadWithVerify(); |
| | 0 | 425 | | Debug.Assert(reader.TokenType is JsonTokenType.PropertyName or JsonTokenType.EndObject); |
| | 0 | 426 | | if (reader.TokenType is JsonTokenType.EndObject) |
| | 0 | 427 | | { |
| | 0 | 428 | | return SelectJsonObjectCase( |
| | 0 | 429 | | _pocoObjectCases, |
| | 0 | 430 | | pocoCaseStates, |
| | 0 | 431 | | isPocoCaseCandidate); |
| | | 432 | | } |
| | | 433 | | |
| | 0 | 434 | | ReadNextProperty( |
| | 0 | 435 | | ref reader, |
| | 0 | 436 | | propertyIndex: i++, |
| | 0 | 437 | | pocoCaseStates, |
| | 0 | 438 | | isPocoCaseCandidate, |
| | 0 | 439 | | pocoCaseMatchesCurrentProperty, |
| | 0 | 440 | | isRequiredPropertySeen); |
| | 0 | 441 | | } |
| | | 442 | | } |
| | | 443 | | finally |
| | 0 | 444 | | { |
| | 0 | 445 | | if (rentedPocoCaseStates is not null) |
| | 0 | 446 | | { |
| | | 447 | | #if NET |
| | 0 | 448 | | Debug.Assert(!RuntimeHelpers.IsReferenceOrContainsReferences<PocoObjectCaseState>()); |
| | | 449 | | #endif |
| | 0 | 450 | | ArrayPool<PocoObjectCaseState>.Shared.Return( |
| | 0 | 451 | | rentedPocoCaseStates, |
| | 0 | 452 | | clearArray: false); |
| | 0 | 453 | | } |
| | 0 | 454 | | } |
| | | 455 | | |
| | | 456 | | static Type? SelectJsonObjectCase( |
| | | 457 | | PocoObjectCase[] pocoObjectCases, |
| | | 458 | | scoped ReadOnlySpan<PocoObjectCaseState> pocoCaseStates, |
| | | 459 | | scoped ValueBitArray isPocoCaseCandidate) |
| | 0 | 460 | | { |
| | 0 | 461 | | Type? selectedType = null; |
| | | 462 | | |
| | 0 | 463 | | for (int i = 0; i < pocoObjectCases.Length; i++) |
| | 0 | 464 | | { |
| | 0 | 465 | | PocoObjectCase pocoObjectCase = pocoObjectCases[i]; |
| | 0 | 466 | | PocoObjectCaseState pocoCaseState = pocoCaseStates[i]; |
| | 0 | 467 | | if (!isPocoCaseCandidate[i] || |
| | 0 | 468 | | pocoCaseState.RequiredSeen < pocoObjectCase.RequiredCount) |
| | 0 | 469 | | { |
| | 0 | 470 | | continue; |
| | | 471 | | } |
| | | 472 | | |
| | 0 | 473 | | if (selectedType is not null) |
| | 0 | 474 | | { |
| | 0 | 475 | | return null; |
| | | 476 | | } |
| | | 477 | | |
| | 0 | 478 | | selectedType = pocoObjectCase.CaseType; |
| | 0 | 479 | | } |
| | | 480 | | |
| | 0 | 481 | | return selectedType; |
| | 0 | 482 | | } |
| | 0 | 483 | | } |
| | | 484 | | |
| | | 485 | | private void ReadNextProperty( |
| | | 486 | | scoped ref Utf8JsonReader reader, |
| | | 487 | | int propertyIndex, |
| | | 488 | | scoped Span<PocoObjectCaseState> pocoCaseStates, |
| | | 489 | | scoped ValueBitArray isPocoCaseCandidate, |
| | | 490 | | scoped ValueBitArray pocoCaseMatchesCurrentProperty, |
| | | 491 | | scoped ValueBitArray isRequiredPropertySeen) |
| | 0 | 492 | | { |
| | 0 | 493 | | byte[]? rentedPropertyName = null; |
| | | 494 | | try |
| | 0 | 495 | | { |
| | 0 | 496 | | scoped Span<byte> buffer = default; |
| | | 497 | | scoped ReadOnlySpan<byte> propertyName; |
| | | 498 | | |
| | 0 | 499 | | if (reader is { HasValueSequence: false, ValueIsEscaped: false }) |
| | 0 | 500 | | { |
| | 0 | 501 | | propertyName = reader.ValueSpan; |
| | 0 | 502 | | } |
| | | 503 | | else |
| | 0 | 504 | | { |
| | 0 | 505 | | int bufferLength = reader.ValueLength; |
| | 0 | 506 | | buffer = bufferLength is <= JsonConstants.StackallocByteThreshold |
| | 0 | 507 | | ? stackalloc byte[JsonConstants.StackallocByteThreshold] |
| | 0 | 508 | | : (rentedPropertyName = ArrayPool<byte>.Shared.Rent(bufferLength)); |
| | | 509 | | |
| | 0 | 510 | | int bytesWritten = reader.CopyString(buffer); |
| | 0 | 511 | | propertyName = buffer.Slice(0, bytesWritten); |
| | 0 | 512 | | } |
| | | 513 | | |
| | 0 | 514 | | reader.ReadWithVerify(); |
| | | 515 | | |
| | 0 | 516 | | pocoCaseMatchesCurrentProperty.Clear(); |
| | 0 | 517 | | RecordPropertyMatches( |
| | 0 | 518 | | propertyName, |
| | 0 | 519 | | propertyIndex, |
| | 0 | 520 | | pocoCaseStates, |
| | 0 | 521 | | isPocoCaseCandidate, |
| | 0 | 522 | | pocoCaseMatchesCurrentProperty, |
| | 0 | 523 | | isRequiredPropertySeen); |
| | | 524 | | |
| | 0 | 525 | | reader.SkipWithVerify(); |
| | 0 | 526 | | } |
| | | 527 | | finally |
| | 0 | 528 | | { |
| | 0 | 529 | | if (rentedPropertyName is not null) |
| | 0 | 530 | | { |
| | 0 | 531 | | ArrayPool<byte>.Shared.Return(rentedPropertyName); |
| | 0 | 532 | | } |
| | 0 | 533 | | } |
| | 0 | 534 | | } |
| | | 535 | | |
| | | 536 | | private void RecordPropertyMatches( |
| | | 537 | | scoped ReadOnlySpan<byte> propertyName, |
| | | 538 | | int propertyIndex, |
| | | 539 | | scoped Span<PocoObjectCaseState> pocoCaseStates, |
| | | 540 | | scoped ValueBitArray isPocoCaseCandidate, |
| | | 541 | | scoped ValueBitArray pocoCaseMatchesCurrentProperty, |
| | | 542 | | scoped ValueBitArray isRequiredPropertySeen) |
| | 0 | 543 | | { |
| | | 544 | | // A name known to any POCO case retains only the POCO cases that declare it; an |
| | | 545 | | // unknown name retains only POCO cases that permit unmapped properties. |
| | 0 | 546 | | Debug.Assert(pocoCaseMatchesCurrentProperty.IsEmpty); |
| | 0 | 547 | | bool isKnownPocoProperty = false; |
| | | 548 | | |
| | 0 | 549 | | if (_pocoPropertyIndex.TryLookupUtf8Key( |
| | 0 | 550 | | propertyName, |
| | 0 | 551 | | out List<PocoPropertyClassifierInfo>? propertyMatches)) |
| | 0 | 552 | | { |
| | 0 | 553 | | isKnownPocoProperty = true; |
| | | 554 | | |
| | 0 | 555 | | foreach (PocoPropertyClassifierInfo propertyInfo in propertyMatches) |
| | 0 | 556 | | { |
| | 0 | 557 | | RecordPropertyMatch( |
| | 0 | 558 | | propertyInfo, |
| | 0 | 559 | | propertyIndex, |
| | 0 | 560 | | pocoCaseStates, |
| | 0 | 561 | | isPocoCaseCandidate, |
| | 0 | 562 | | pocoCaseMatchesCurrentProperty, |
| | 0 | 563 | | isRequiredPropertySeen); |
| | 0 | 564 | | } |
| | 0 | 565 | | } |
| | | 566 | | |
| | 0 | 567 | | if (_caseInsensitivePocoPropertyIndex is { } caseInsensitivePocoPropertyIndex && |
| | 0 | 568 | | caseInsensitivePocoPropertyIndex.TryLookupUtf8Key( |
| | 0 | 569 | | propertyName, |
| | 0 | 570 | | out List<PocoPropertyClassifierInfo>? caseInsensitivePropertyMatches)) |
| | 0 | 571 | | { |
| | 0 | 572 | | isKnownPocoProperty = true; |
| | | 573 | | |
| | 0 | 574 | | foreach (PocoPropertyClassifierInfo propertyInfo in caseInsensitivePropertyMatches) |
| | 0 | 575 | | { |
| | 0 | 576 | | RecordPropertyMatch( |
| | 0 | 577 | | propertyInfo, |
| | 0 | 578 | | propertyIndex, |
| | 0 | 579 | | pocoCaseStates, |
| | 0 | 580 | | isPocoCaseCandidate, |
| | 0 | 581 | | pocoCaseMatchesCurrentProperty, |
| | 0 | 582 | | isRequiredPropertySeen); |
| | 0 | 583 | | } |
| | 0 | 584 | | } |
| | | 585 | | |
| | 0 | 586 | | if (isKnownPocoProperty) |
| | 0 | 587 | | { |
| | | 588 | | // An exact or case-insensitive lookup recognized the name, so retain only |
| | | 589 | | // cases whose configured property metadata matched it. |
| | 0 | 590 | | isPocoCaseCandidate.IntersectWith(pocoCaseMatchesCurrentProperty); |
| | 0 | 591 | | } |
| | | 592 | | else |
| | 0 | 593 | | { |
| | | 594 | | // No POCO case recognizes the name, so it eliminates only cases that reject |
| | | 595 | | // unmapped properties. |
| | 0 | 596 | | foreach (int pocoCaseIndex in _disallowUnmappedPropertiesPocoCaseIndices) |
| | 0 | 597 | | { |
| | 0 | 598 | | isPocoCaseCandidate[pocoCaseIndex] = false; |
| | 0 | 599 | | } |
| | 0 | 600 | | } |
| | | 601 | | |
| | | 602 | | static void RecordPropertyMatch( |
| | | 603 | | PocoPropertyClassifierInfo propertyInfo, |
| | | 604 | | int propertyIndex, |
| | | 605 | | scoped Span<PocoObjectCaseState> pocoCaseStates, |
| | | 606 | | scoped ValueBitArray isPocoCaseCandidate, |
| | | 607 | | scoped ValueBitArray pocoCaseMatchesCurrentProperty, |
| | | 608 | | scoped ValueBitArray isRequiredPropertySeen) |
| | 0 | 609 | | { |
| | 0 | 610 | | ref PocoObjectCaseState pocoCaseState = ref pocoCaseStates[propertyInfo.PocoCaseIndex]; |
| | 0 | 611 | | pocoCaseMatchesCurrentProperty[propertyInfo.PocoCaseIndex] = true; |
| | | 612 | | |
| | | 613 | | // Exact matches take precedence over case-insensitive matches, and one JSON |
| | | 614 | | // property can contribute to at most one declared property per POCO object case. |
| | 0 | 615 | | if (!isPocoCaseCandidate[propertyInfo.PocoCaseIndex] || |
| | 0 | 616 | | pocoCaseState.LastMatchedPropertyIndex == propertyIndex) |
| | 0 | 617 | | { |
| | 0 | 618 | | return; |
| | | 619 | | } |
| | | 620 | | |
| | 0 | 621 | | pocoCaseState.LastMatchedPropertyIndex = propertyIndex; |
| | | 622 | | // RequiredPropertyIndex is unique per declared property, so duplicate JSON |
| | | 623 | | // names cannot satisfy the same requirement more than once. |
| | 0 | 624 | | int requiredPropertyIndex = propertyInfo.RequiredPropertyIndex; |
| | 0 | 625 | | if (propertyInfo.IsRequired && |
| | 0 | 626 | | !isRequiredPropertySeen[requiredPropertyIndex]) |
| | 0 | 627 | | { |
| | 0 | 628 | | isRequiredPropertySeen[requiredPropertyIndex] = true; |
| | 0 | 629 | | pocoCaseState.RequiredSeen++; |
| | 0 | 630 | | } |
| | 0 | 631 | | } |
| | 0 | 632 | | } |
| | | 633 | | } |
| | | 634 | | |
| | | 635 | | /// <summary>Describes the POCO property contract used to classify a union case.</summary> |
| | 0 | 636 | | private sealed class PocoObjectCase( |
| | 0 | 637 | | Type caseType, |
| | 0 | 638 | | PocoPropertyClassifierInfo[] properties, |
| | 0 | 639 | | bool disallowUnmappedProperties, |
| | 0 | 640 | | int requiredCount) |
| | | 641 | | { |
| | 0 | 642 | | public Type CaseType { get; } = caseType; |
| | 0 | 643 | | public bool DisallowUnmappedProperties { get; } = disallowUnmappedProperties; |
| | 0 | 644 | | public PocoPropertyClassifierInfo[] Properties { get; } = properties; |
| | 0 | 645 | | public int RequiredCount { get; } = requiredCount; |
| | | 646 | | |
| | | 647 | | public bool IsShadowedBy(PocoObjectCase other) |
| | 0 | 648 | | { |
| | | 649 | | // This case is shadowed when every payload it accepts is also accepted by the |
| | | 650 | | // other case: the other case must be at least as permissive about unknown names, |
| | | 651 | | // recognize every property-name spelling accepted by this case, and require no |
| | | 652 | | // property that this case does not itself require. |
| | 0 | 653 | | if (!DisallowUnmappedProperties && other.DisallowUnmappedProperties) |
| | 0 | 654 | | { |
| | 0 | 655 | | return false; |
| | | 656 | | } |
| | | 657 | | |
| | 0 | 658 | | foreach (PocoPropertyClassifierInfo property in Properties) |
| | 0 | 659 | | { |
| | 0 | 660 | | bool otherHasEquivalentProperty = false; |
| | 0 | 661 | | foreach (PocoPropertyClassifierInfo otherProperty in other.Properties) |
| | 0 | 662 | | { |
| | 0 | 663 | | if (property.IsPropertyNameEquivalent(otherProperty)) |
| | 0 | 664 | | { |
| | 0 | 665 | | otherHasEquivalentProperty = true; |
| | 0 | 666 | | break; |
| | | 667 | | } |
| | 0 | 668 | | } |
| | | 669 | | |
| | 0 | 670 | | if (!otherHasEquivalentProperty) |
| | 0 | 671 | | { |
| | 0 | 672 | | return false; |
| | | 673 | | } |
| | 0 | 674 | | } |
| | | 675 | | |
| | 0 | 676 | | foreach (PocoPropertyClassifierInfo otherProperty in other.Properties) |
| | 0 | 677 | | { |
| | 0 | 678 | | if (!otherProperty.IsRequired) |
| | 0 | 679 | | { |
| | 0 | 680 | | continue; |
| | | 681 | | } |
| | | 682 | | |
| | 0 | 683 | | bool requiredPropertyIsGuaranteedByThisCase = false; |
| | 0 | 684 | | foreach (PocoPropertyClassifierInfo property in Properties) |
| | 0 | 685 | | { |
| | 0 | 686 | | if (property.IsRequired && property.IsPropertyNameEquivalent(otherProperty)) |
| | 0 | 687 | | { |
| | 0 | 688 | | requiredPropertyIsGuaranteedByThisCase = true; |
| | 0 | 689 | | break; |
| | | 690 | | } |
| | 0 | 691 | | } |
| | | 692 | | |
| | 0 | 693 | | if (!requiredPropertyIsGuaranteedByThisCase) |
| | 0 | 694 | | { |
| | 0 | 695 | | return false; |
| | | 696 | | } |
| | 0 | 697 | | } |
| | | 698 | | |
| | 0 | 699 | | return true; |
| | 0 | 700 | | } |
| | | 701 | | } |
| | | 702 | | |
| | | 703 | | /// <summary>Describes how a JSON property name contributes to a POCO object case.</summary> |
| | 0 | 704 | | private sealed class PocoPropertyClassifierInfo( |
| | 0 | 705 | | string name, |
| | 0 | 706 | | bool isRequired, |
| | 0 | 707 | | bool isCaseSensitive, |
| | 0 | 708 | | int pocoCaseIndex, |
| | 0 | 709 | | int requiredPropertyIndex) |
| | | 710 | | { |
| | 0 | 711 | | public int PocoCaseIndex { get; } = pocoCaseIndex; |
| | 0 | 712 | | public bool IsCaseSensitive { get; } = isCaseSensitive; |
| | 0 | 713 | | public bool IsRequired { get; } = isRequired; |
| | 0 | 714 | | public string Name { get; } = name; |
| | 0 | 715 | | public byte[] NameAsUtf8Bytes { get; } = Encoding.UTF8.GetBytes(name); |
| | 0 | 716 | | public int RequiredPropertyIndex { get; } = requiredPropertyIndex; |
| | | 717 | | |
| | | 718 | | public bool IsPropertyNameEquivalent(PocoPropertyClassifierInfo other) |
| | 0 | 719 | | { |
| | 0 | 720 | | Debug.Assert(IsCaseSensitive == other.IsCaseSensitive); |
| | | 721 | | |
| | 0 | 722 | | return string.Equals( |
| | 0 | 723 | | Name, |
| | 0 | 724 | | other.Name, |
| | 0 | 725 | | IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); |
| | 0 | 726 | | } |
| | | 727 | | } |
| | | 728 | | |
| | | 729 | | /// <summary>Tracks per-case matching state while scanning a POCO JSON object.</summary> |
| | | 730 | | private struct PocoObjectCaseState |
| | | 731 | | { |
| | | 732 | | public int RequiredSeen; |
| | | 733 | | |
| | | 734 | | /// <summary> |
| | | 735 | | /// Gets or sets the zero-based index of the last matched JSON property, or -1 if none matched. |
| | | 736 | | /// </summary> |
| | | 737 | | public int LastMatchedPropertyIndex |
| | | 738 | | { |
| | 0 | 739 | | readonly get => field - 1; |
| | | 740 | | set |
| | 0 | 741 | | { |
| | 0 | 742 | | Debug.Assert(value >= 0); |
| | 0 | 743 | | field = value + 1; |
| | 0 | 744 | | } |
| | | 745 | | } |
| | | 746 | | } |
| | | 747 | | } |
| | | 748 | | } |
| | | 749 | | |