// #nullable disable using System; using System.Collections; using System.Collections.Generic; namespace OpenAI { internal partial class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull { private IDictionary _innerDictionary; public ChangeTrackingDictionary() { } public ChangeTrackingDictionary(IDictionary dictionary) { if (dictionary == null) { return; } _innerDictionary = new Dictionary(dictionary); } public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) { if (dictionary == null) { return; } _innerDictionary = new Dictionary(); foreach (var pair in dictionary) { _innerDictionary.Add(pair); } } public bool IsUndefined => _innerDictionary == null; public int Count => IsUndefined ? 0 : EnsureDictionary().Count; public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; public TValue this[TKey key] { get { if (IsUndefined) { throw new KeyNotFoundException(nameof(key)); } return EnsureDictionary()[key]; } set { EnsureDictionary()[key] = value; } } IEnumerable IReadOnlyDictionary.Keys => Keys; IEnumerable IReadOnlyDictionary.Values => Values; public IEnumerator> GetEnumerator() { if (IsUndefined) { IEnumerator> enumerateEmpty() { yield break; } return enumerateEmpty(); } return EnsureDictionary().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(KeyValuePair item) { EnsureDictionary().Add(item); } public void Clear() { EnsureDictionary().Clear(); } public bool Contains(KeyValuePair item) { if (IsUndefined) { return false; } return EnsureDictionary().Contains(item); } public void CopyTo(KeyValuePair[] array, int index) { if (IsUndefined) { return; } EnsureDictionary().CopyTo(array, index); } public bool Remove(KeyValuePair item) { if (IsUndefined) { return false; } return EnsureDictionary().Remove(item); } public void Add(TKey key, TValue value) { EnsureDictionary().Add(key, value); } public bool ContainsKey(TKey key) { if (IsUndefined) { return false; } return EnsureDictionary().ContainsKey(key); } public bool Remove(TKey key) { if (IsUndefined) { return false; } return EnsureDictionary().Remove(key); } public bool TryGetValue(TKey key, out TValue value) { if (IsUndefined) { value = default; return false; } return EnsureDictionary().TryGetValue(key, out value); } public IDictionary EnsureDictionary() { return _innerDictionary ??= new Dictionary(); } } }