| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Collections.Immutable; |
| | | 3 | | |
| | | 4 | | namespace Hertzole.ScriptableValues.Generator; |
| | | 5 | | |
| | | 6 | | internal readonly ref struct ArrayDictionaryBuilder<TKey, TValue> where TKey : notnull |
| | | 7 | | { |
| | | 8 | | private readonly IEqualityComparer<TKey> comparer; |
| | | 9 | | private readonly Dictionary<TKey, ArrayBuilder<TValue>> builders; |
| | | 10 | | |
| | | 11 | | public ArrayDictionaryBuilder(IEqualityComparer<TKey> comparer) |
| | | 12 | | { |
| | 0 | 13 | | this.comparer = comparer; |
| | 0 | 14 | | builders = new Dictionary<TKey, ArrayBuilder<TValue>>(comparer); |
| | 0 | 15 | | } |
| | | 16 | | |
| | | 17 | | public void Add(TKey key, TValue value) |
| | | 18 | | { |
| | 0 | 19 | | if (builders.TryGetValue(key, out ArrayBuilder<TValue> array)) |
| | | 20 | | { |
| | 0 | 21 | | array.Add(value); |
| | | 22 | | } |
| | | 23 | | else |
| | | 24 | | { |
| | 0 | 25 | | ArrayBuilder<TValue> builder = new ArrayBuilder<TValue>(); |
| | 0 | 26 | | builder.Add(value); |
| | 0 | 27 | | builders.Add(key, builder); |
| | | 28 | | } |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | public ImmutableDictionary<TKey, ImmutableArray<TValue>> ToImmutable() |
| | | 32 | | { |
| | 0 | 33 | | ImmutableDictionary<TKey, ImmutableArray<TValue>>.Builder builder = ImmutableDictionary.CreateBuilder<TKey, Immu |
| | | 34 | | |
| | 0 | 35 | | foreach (KeyValuePair<TKey, ArrayBuilder<TValue>> pair in builders) |
| | | 36 | | { |
| | 0 | 37 | | builder.Add(pair.Key, pair.Value.ToImmutable()); |
| | | 38 | | } |
| | | 39 | | |
| | 0 | 40 | | return builder.ToImmutable(); |
| | | 41 | | } |
| | | 42 | | } |