RefCountList.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // 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>(int readerCount) : IRefCountList<T>
  9. {
  10. private readonly IDictionary<int, RefCount> _list = new Dictionary<int, RefCount>();
  11. public int ReaderCount { get; set; } = readerCount;
  12. public void Clear() => _list.Clear();
  13. public int Count { get; private set; }
  14. public T this[int i]
  15. {
  16. get
  17. {
  18. Debug.Assert(i < Count);
  19. if (!_list.TryGetValue(i, out var res))
  20. throw new InvalidOperationException("Element no longer available in the buffer.");
  21. var val = res.Value;
  22. if (--res.Count == 0)
  23. {
  24. _list.Remove(i);
  25. }
  26. return val;
  27. }
  28. }
  29. public void Add(T item)
  30. {
  31. _list[Count] = new RefCount(item, ReaderCount);
  32. Count++;
  33. }
  34. public void Done(int index)
  35. {
  36. for (var i = index; i < Count; i++)
  37. {
  38. _ = this[i];
  39. }
  40. ReaderCount--;
  41. }
  42. private sealed class RefCount
  43. {
  44. public RefCount(T value, int count)
  45. {
  46. Value = value;
  47. Count = count;
  48. }
  49. public int Count { get; set; }
  50. public T Value { get; }
  51. }
  52. }
  53. }