| | | 1 | | using System.Buffers; |
| | | 2 | | using System.Collections; |
| | | 3 | | using System.Text; |
| | | 4 | | using NGql.Core.Abstractions; |
| | | 5 | | using NGql.Core.Extensions; |
| | | 6 | | |
| | | 7 | | namespace NGql.Core.Features; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Generates unique signatures for field definitions based on their arguments/filters. |
| | | 11 | | /// Optimized for performance using Span operations and reduced string allocations. |
| | | 12 | | /// </summary> |
| | | 13 | | public static class FieldSignatureGenerator |
| | | 14 | | { |
| | | 15 | | // Pre-allocated StringBuilder for signature generation to avoid repeated allocations |
| | 6 | 16 | | private static readonly ThreadLocal<StringBuilder> SignatureBuilder = new(() => new StringBuilder(256)); |
| | | 17 | | |
| | | 18 | | // Singleton comparer for sorting by Name for deterministic signature generation. |
| | 3 | 19 | | private static readonly IComparer<FieldDefinition> FieldNameComparer = |
| | 78 | 20 | | Comparer<FieldDefinition>.Create(static (a, b) => StringComparer.OrdinalIgnoreCase.Compare(a.Name, b.Name)); |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Generates a unique hash signature for a collection of field definitions. |
| | | 24 | | /// </summary> |
| | | 25 | | /// <param name="fields">The field definitions to generate signature for.</param> |
| | | 26 | | /// <returns>A unique hash representing the filter signature of the fields.</returns> |
| | | 27 | | public static int GenerateSignature(Dictionary<string, FieldDefinition> fields) |
| | | 28 | | { |
| | 234 | 29 | | if (fields.Count == 0) |
| | | 30 | | { |
| | 6 | 31 | | return 0; |
| | | 32 | | } |
| | | 33 | | |
| | 228 | 34 | | var builder = SignatureBuilder.Value!; |
| | 228 | 35 | | builder.Clear(); |
| | | 36 | | |
| | 1026 | 37 | | foreach (var field in fields.Values) |
| | | 38 | | { |
| | 285 | 39 | | AppendFieldSignature(builder, field, ReadOnlySpan<char>.Empty); |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | // builder.Length is always > 0 here: the empty-fields case was handled above and |
| | | 43 | | // every field appends at least its name to the signature. |
| | | 44 | | // Hash directly over StringBuilder chunks — avoids allocating a temporary string. |
| | | 45 | | unchecked |
| | | 46 | | { |
| | 228 | 47 | | int hash = 5381; |
| | 924 | 48 | | foreach (var chunk in builder.GetChunks()) |
| | | 49 | | { |
| | 59268 | 50 | | foreach (var c in chunk.Span) |
| | 29400 | 51 | | hash = (hash << 5) + hash + c; // djb2: hash*33 + c |
| | | 52 | | } |
| | 228 | 53 | | return hash; |
| | | 54 | | } |
| | | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// Appends field signature to the builder using Span operations for efficient path construction. |
| | | 59 | | /// </summary> |
| | | 60 | | /// <param name="builder">StringBuilder to append to</param> |
| | | 61 | | /// <param name="field">Field definition to process</param> |
| | | 62 | | /// <param name="parentPath">Parent path as ReadOnlySpan to avoid string allocations</param> |
| | | 63 | | private static void AppendFieldSignature(StringBuilder builder, FieldDefinition field, ReadOnlySpan<char> parentPath |
| | | 64 | | { |
| | | 65 | | // Build the current path efficiently using Span operations |
| | 504 | 66 | | Span<char> currentPathBuffer = stackalloc char[256]; // Stack allocation for path building |
| | 504 | 67 | | int pathLength = 0; |
| | | 68 | | |
| | 504 | 69 | | if (!parentPath.IsEmpty) |
| | | 70 | | { |
| | 219 | 71 | | parentPath.CopyTo(currentPathBuffer); |
| | 219 | 72 | | pathLength = parentPath.Length; |
| | 219 | 73 | | currentPathBuffer[pathLength++] = '.'; |
| | | 74 | | } |
| | | 75 | | |
| | 504 | 76 | | var fieldNameSpan = field.Name.AsSpan(); |
| | 504 | 77 | | if (pathLength + fieldNameSpan.Length < currentPathBuffer.Length) |
| | | 78 | | { |
| | 480 | 79 | | fieldNameSpan.CopyTo(currentPathBuffer[pathLength..]); |
| | 480 | 80 | | pathLength += fieldNameSpan.Length; |
| | | 81 | | } |
| | | 82 | | else |
| | | 83 | | { |
| | | 84 | | // Fallback to string concatenation for very long paths. |
| | 24 | 85 | | var currentPath = parentPath.IsEmpty ? field.Name : $"{parentPath.ToString()}.{field.Name}"; |
| | 24 | 86 | | builder.Append(currentPath); |
| | 24 | 87 | | AppendFieldSignatureRemainder(builder, field, currentPath.AsSpan()); |
| | 24 | 88 | | return; |
| | | 89 | | } |
| | | 90 | | |
| | 480 | 91 | | var currentPathSpan = currentPathBuffer[..pathLength]; |
| | | 92 | | |
| | | 93 | | // Append the path to the signature |
| | 480 | 94 | | builder.Append(currentPathSpan); |
| | | 95 | | |
| | 480 | 96 | | AppendFieldSignatureRemainder(builder, field, currentPathSpan); |
| | 480 | 97 | | } |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Appends the remainder of the field signature (arguments and child fields). |
| | | 101 | | /// </summary> |
| | | 102 | | /// <param name="builder">StringBuilder to append to</param> |
| | | 103 | | /// <param name="field">Field definition to process</param> |
| | | 104 | | /// <param name="currentPath">Current path (either as span or string)</param> |
| | | 105 | | private static void AppendFieldSignatureRemainder(StringBuilder builder, FieldDefinition field, ReadOnlySpan<char> c |
| | | 106 | | { |
| | | 107 | | // Add arguments if present |
| | 504 | 108 | | if (field._arguments is { Count: > 0 }) |
| | | 109 | | { |
| | 129 | 110 | | builder.Append('['); |
| | | 111 | | // _arguments is SortedDictionary — already ordered by key, no OrderBy needed. |
| | 1302 | 112 | | foreach (var arg in field._arguments) |
| | | 113 | | { |
| | 522 | 114 | | builder.Append(arg.Key); |
| | 522 | 115 | | builder.Append(':'); |
| | 522 | 116 | | AppendArgumentValue(builder, arg.Value); |
| | 522 | 117 | | builder.Append(';'); |
| | | 118 | | } |
| | 129 | 119 | | builder.Append(']'); |
| | | 120 | | } |
| | | 121 | | |
| | 504 | 122 | | builder.Append('|'); |
| | | 123 | | |
| | | 124 | | // Recursively process child fields sorted by Name for a deterministic hash. |
| | | 125 | | // Dictionary<TKey,TValue> is unordered; explicit sort ensures signature stability. |
| | 504 | 126 | | if (field._children is { Count: > 0 }) |
| | | 127 | | { |
| | 153 | 128 | | var fieldCount = field._children.Count; |
| | 153 | 129 | | var rented = ArrayPool<FieldDefinition>.Shared.Rent(fieldCount); |
| | | 130 | | try |
| | | 131 | | { |
| | 153 | 132 | | field._children.AsSpan().CopyTo(rented); |
| | 153 | 133 | | Array.Sort(rented, 0, fieldCount, FieldNameComparer); |
| | 744 | 134 | | for (var i = 0; i < fieldCount; i++) |
| | 219 | 135 | | AppendFieldSignature(builder, rented[i], currentPath); |
| | 153 | 136 | | } |
| | | 137 | | finally |
| | | 138 | | { |
| | 153 | 139 | | ArrayPool<FieldDefinition>.Shared.Return(rented, clearArray: false); |
| | 153 | 140 | | } |
| | | 141 | | } |
| | 504 | 142 | | } |
| | | 143 | | |
| | | 144 | | |
| | | 145 | | /// <summary> |
| | | 146 | | /// Appends argument value to the signature with optimized handling for common types. |
| | | 147 | | /// </summary> |
| | | 148 | | /// <param name="builder">StringBuilder to append to</param> |
| | | 149 | | /// <param name="value">Argument value to append</param> |
| | | 150 | | private static void AppendArgumentValue(StringBuilder builder, object? value) |
| | | 151 | | { |
| | 582 | 152 | | if (value is null) |
| | | 153 | | { |
| | 3 | 154 | | builder.Append("null"); |
| | 3 | 155 | | return; |
| | | 156 | | } |
| | | 157 | | |
| | 579 | 158 | | if (ValueFormatter.TryAppendPrimitive(value, builder)) |
| | 549 | 159 | | return; |
| | | 160 | | |
| | 30 | 161 | | AppendComplexValue(builder, value); |
| | 30 | 162 | | } |
| | | 163 | | |
| | | 164 | | private static void AppendComplexValue(StringBuilder builder, object value) |
| | | 165 | | { |
| | 30 | 166 | | switch (value) |
| | | 167 | | { |
| | | 168 | | case IDictionary<string, object?> dict: |
| | 15 | 169 | | AppendDictionary(builder, dict); |
| | 15 | 170 | | break; |
| | 12 | 171 | | case IEnumerable enumerable when value is not string: |
| | 12 | 172 | | AppendEnumerable(builder, enumerable); |
| | 12 | 173 | | break; |
| | | 174 | | default: |
| | 3 | 175 | | builder.Append(value); |
| | | 176 | | break; |
| | | 177 | | } |
| | 3 | 178 | | } |
| | | 179 | | |
| | | 180 | | private static void AppendDictionary(StringBuilder builder, IDictionary<string, object?> dict) |
| | | 181 | | { |
| | | 182 | | // Argument dictionaries reach here through Helpers.SortArgumentValue, which converts |
| | | 183 | | // every nested dict to SortedDictionary; the IOrderedEnumerable fallback for plain |
| | | 184 | | // Dictionary instances was a defensive guard that the public API never triggers. |
| | 15 | 185 | | Helpers.WriteCollection('{', '}', dict, builder, (sb, item) => |
| | 15 | 186 | | { |
| | 24 | 187 | | var kvp = (KeyValuePair<string, object?>)item!; |
| | 24 | 188 | | sb.Append(kvp.Key).Append(':'); |
| | 24 | 189 | | AppendArgumentValue(sb, kvp.Value); |
| | 39 | 190 | | }); |
| | 15 | 191 | | } |
| | | 192 | | |
| | | 193 | | private static void AppendEnumerable(StringBuilder builder, IEnumerable enumerable) |
| | 48 | 194 | | => Helpers.WriteCollection('[', ']', enumerable, builder, (sb, item) => AppendArgumentValue(sb, item)); |
| | | 195 | | } |