From 96bd92a1b8c5a869dd151d49e09375ca280b45dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Chalet?= Date: Wed, 20 Apr 2022 18:55:40 +0200 Subject: [PATCH] Optimize OpenIddictParameter.Count to avoid serialization for JsonValue instances wrapping a JsonElement or a primitive type --- .../Primitives/OpenIddictParameter.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs index 4f061d9c..74d8da22 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs @@ -110,6 +110,18 @@ public readonly struct OpenIddictParameter : IEquatable // If the parameter is a JsonObject, return its length. JsonObject value => value.Count, + // If the parameter is a JsonValue wrapping a JsonElement, + // apply the same logic as with direct JsonElement instances. + JsonValue value when value.TryGetValue(out JsonElement element) + => element.ValueKind is JsonValueKind.Array or JsonValueKind.Object ? Count(element) : 0, + + // If the parameter is a JsonValue wrapping a well-known primitive type + // (e.g int or string), always return 0 as these types can't have a length. + JsonValue value when value.TryGetValue(out bool _) || + value.TryGetValue(out int _) || + value.TryGetValue(out long _) || + value.TryGetValue(out string _) => 0, + // If the parameter is any other JsonNode (e.g a JsonValue), serialize it // to a JsonElement first to determine its actual JSON representation // and extract the number of items if the element is a JSON array or object.