Files
spark/src/client/spark_core/Collections/AggregateDictionary.cs
T

99 lines
3.2 KiB
C#

#nullable enable
namespace Spark.Core.Collections {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
public static class AggregateDictionary {
public static AggregateDictionary<K, V> Create<K, V>(
IDictionary<K, V> src1, IDictionary<K, V> src2, bool isReadOnly = true) where K : notnull =>
new(src1, src2, isReadOnly);
}
public class AggregateDictionary<TKey, TValue> : IDictionary<TKey, TValue> where TKey : notnull {
readonly IDictionary<TKey, TValue> src1;
readonly IDictionary<TKey, TValue> src2;
readonly bool isReadOnly;
public AggregateDictionary(IDictionary<TKey, TValue> src1, IDictionary<TKey, TValue> src2) {
this.src1 = src1;
this.src2 = src2;
}
public AggregateDictionary(IDictionary<TKey, TValue> src1, IDictionary<TKey, TValue> src2, bool isReadOnly = true) {
this.src1 = src1;
this.src2 = src2;
this.isReadOnly = isReadOnly;
}
public int Count => src1.Count + src2.Count;
public bool IsReadOnly => isReadOnly;
public ICollection<TKey> Keys =>
AggregateCollection.Create(src1.Keys, src2.Keys);
public ICollection<TValue> Values =>
AggregateCollection.Create(src1.Values, src2.Values);
public TValue this[TKey key] {
get {
if (src1.TryGetValue(key, out var v1)) {
return v1;
}
if (src2.TryGetValue(key, out var v2)) {
return v2;
}
throw new KeyNotFoundException();
}
set {
if (isReadOnly) {
throw new NotSupportedException();
}
src1[key] = value;
}
}
public void Add(TKey key, TValue value) =>
throw new NotSupportedException();
public void Add(KeyValuePair<TKey, TValue> item) =>
throw new NotSupportedException();
public void Clear() =>
throw new NotSupportedException();
public bool Contains(KeyValuePair<TKey, TValue> item) =>
src1.Contains(item) || src2.Contains(item);
public bool ContainsKey(TKey key) =>
(key is TKey k1 && src1.ContainsKey(k1)) || (key is TKey k2 && src2.ContainsKey(k2));
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) =>
AggregateCollection.Create(src1, src2).CopyTo(array, arrayIndex);
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
foreach (var kv in src1) {
yield return new(kv.Key, kv.Value);
}
foreach (var kv in src2) {
yield return new(kv.Key, kv.Value);
}
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) =>
src1.TryGetValue(key, out value) ||
src2.TryGetValue(key, out value);
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
bool IDictionary<TKey, TValue>.Remove(TKey key) =>
throw new NotSupportedException();
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) =>
throw new NotSupportedException();
}
}