| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | |
| | | 7 | | namespace System.Collections.Generic |
| | | 8 | | { |
| | | 9 | | internal sealed class BidirectionalDictionary<T1, T2> : IEnumerable<KeyValuePair<T1, T2>> |
| | | 10 | | where T1 : notnull |
| | | 11 | | where T2 : notnull |
| | | 12 | | { |
| | | 13 | | private readonly Dictionary<T1, T2> _forward; |
| | | 14 | | private readonly Dictionary<T2, T1> _backward; |
| | | 15 | | |
| | 0 | 16 | | public BidirectionalDictionary(int capacity) |
| | 0 | 17 | | { |
| | 0 | 18 | | _forward = new Dictionary<T1, T2>(capacity); |
| | 0 | 19 | | _backward = new Dictionary<T2, T1>(capacity); |
| | 0 | 20 | | } |
| | | 21 | | |
| | | 22 | | public int Count |
| | | 23 | | { |
| | | 24 | | get |
| | 0 | 25 | | { |
| | 0 | 26 | | Debug.Assert(_forward.Count == _backward.Count, "both the dictionaries must have the same number of elem |
| | 0 | 27 | | return _forward.Count; |
| | 0 | 28 | | } |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public void Add(T1 item1, T2 item2) |
| | 0 | 32 | | { |
| | 0 | 33 | | Debug.Assert(!_backward.ContainsKey(item2), "No added item1 should ever have existing item2"); |
| | 0 | 34 | | _forward.Add(item1, item2); |
| | 0 | 35 | | _backward.Add(item2, item1); |
| | 0 | 36 | | } |
| | | 37 | | |
| | | 38 | | public bool TryGetForward(T1 item1, [MaybeNullWhen(false)] out T2 item2) |
| | 0 | 39 | | { |
| | 0 | 40 | | return _forward.TryGetValue(item1, out item2); |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | public bool TryGetBackward(T2 item2, [MaybeNullWhen(false)] out T1 item1) |
| | 0 | 44 | | { |
| | 0 | 45 | | return _backward.TryGetValue(item2, out item1); |
| | 0 | 46 | | } |
| | | 47 | | |
| | | 48 | | public Dictionary<T1, T2>.Enumerator GetEnumerator() |
| | 0 | 49 | | { |
| | 0 | 50 | | return _forward.GetEnumerator(); |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | IEnumerator<KeyValuePair<T1, T2>> IEnumerable<KeyValuePair<T1, T2>>.GetEnumerator() |
| | 0 | 54 | | { |
| | 0 | 55 | | return GetEnumerator(); |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | IEnumerator IEnumerable.GetEnumerator() |
| | 0 | 59 | | { |
| | 0 | 60 | | return GetEnumerator(); |
| | 0 | 61 | | } |
| | | 62 | | } |
| | | 63 | | } |
| | | 64 | | |