RefCountList.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. namespace System.Linq
  7. {
  8. internal sealed class RefCountList<T> : IRefCountList<T>
  9. {
  10. private readonly IDictionary<int, RefCount> _list;
  11. public RefCountList(int readerCount)
  12. {
  13. ReaderCount = readerCount;
  14. _list = new Dictionary<int, RefCount>();
  15. }
  16. public int ReaderCount { get; set; }
  17. public void Clear() => _list.Clear();
  18. public int Count { get; private set; }
  19. public T this[int i]
  20. {
  21. get
  22. {
  23. Debug.Assert(i < Count);
  24. if (!_list.TryGetValue(i, out var res))
  25. throw new InvalidOperationException("Element no longer available in the buffer.");
  26. var val = res.Value;
  27. if (--res.Count == 0)
  28. {
  29. _list.Remove(i);
  30. }
  31. return val;
  32. }
  33. }
  34. public void Add(T item)
  35. {
  36. _list[Count] = new RefCount { Value = item, Count = ReaderCount };
  37. Count++;
  38. }
  39. public void Done(int index)
  40. {
  41. for (var i = index; i < Count; i++)
  42. {
  43. _ = this[i];
  44. }
  45. ReaderCount--;
  46. }
  47. private sealed class RefCount
  48. {
  49. public int Count;
  50. public T Value;
  51. }
  52. }
  53. }