Memoize.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. namespace System.Linq
  8. {
  9. public static partial class EnumerableEx
  10. {
  11. /// <summary>
  12. /// Creates a buffer with a view over the source sequence, causing each enumerator to obtain access to all of the
  13. /// sequence's elements without causing multiple enumerations over the source.
  14. /// </summary>
  15. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  16. /// <param name="source">Source sequence.</param>
  17. /// <returns>
  18. /// Buffer enabling each enumerator to retrieve all elements from the shared source sequence, without duplicating
  19. /// source enumeration side-effects.
  20. /// </returns>
  21. /// <example>
  22. /// var rng = Enumerable.Range(0, 10).Do(x => Console.WriteLine(x)).Memoize();
  23. /// var e1 = rng.GetEnumerator();
  24. /// Assert.IsTrue(e1.MoveNext()); // Prints 0
  25. /// Assert.AreEqual(0, e1.Current);
  26. /// Assert.IsTrue(e1.MoveNext()); // Prints 1
  27. /// Assert.AreEqual(1, e1.Current);
  28. /// var e2 = rng.GetEnumerator();
  29. /// Assert.IsTrue(e2.MoveNext()); // Doesn't print anything; the side-effect of Do
  30. /// Assert.AreEqual(0, e2.Current); // has already taken place during e1's iteration.
  31. /// Assert.IsTrue(e1.MoveNext()); // Prints 2
  32. /// Assert.AreEqual(2, e1.Current);
  33. /// </example>
  34. public static IBuffer<TSource> Memoize<TSource>(this IEnumerable<TSource> source)
  35. {
  36. if (source == null)
  37. throw new ArgumentNullException(nameof(source));
  38. return new MemoizedBuffer<TSource>(source.GetEnumerator());
  39. }
  40. /// <summary>
  41. /// Memoizes the source sequence within a selector function where each enumerator can get access to all of the
  42. /// sequence's elements without causing multiple enumerations over the source.
  43. /// </summary>
  44. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  45. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  46. /// <param name="source">Source sequence.</param>
  47. /// <param name="selector">Selector function with memoized access to the source sequence for each enumerator.</param>
  48. /// <returns>Sequence resulting from applying the selector function to the memoized view over the source sequence.</returns>
  49. public static IEnumerable<TResult> Memoize<TSource, TResult>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
  50. {
  51. if (source == null)
  52. throw new ArgumentNullException(nameof(source));
  53. if (selector == null)
  54. throw new ArgumentNullException(nameof(selector));
  55. return Create(() => selector(source.Memoize()).GetEnumerator());
  56. }
  57. /// <summary>
  58. /// Creates a buffer with a view over the source sequence, causing a specified number of enumerators to obtain access
  59. /// to all of the sequence's elements without causing multiple enumerations over the source.
  60. /// </summary>
  61. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  62. /// <param name="source">Source sequence.</param>
  63. /// <param name="readerCount">
  64. /// Number of enumerators that can access the underlying buffer. Once every enumerator has
  65. /// obtained an element from the buffer, the element is removed from the buffer.
  66. /// </param>
  67. /// <returns>
  68. /// Buffer enabling a specified number of enumerators to retrieve all elements from the shared source sequence,
  69. /// without duplicating source enumeration side-effects.
  70. /// </returns>
  71. public static IBuffer<TSource> Memoize<TSource>(this IEnumerable<TSource> source, int readerCount)
  72. {
  73. if (source == null)
  74. throw new ArgumentNullException(nameof(source));
  75. if (readerCount <= 0)
  76. throw new ArgumentOutOfRangeException(nameof(readerCount));
  77. return new MemoizedBuffer<TSource>(source.GetEnumerator(), readerCount);
  78. }
  79. /// <summary>
  80. /// Memoizes the source sequence within a selector function where a specified number of enumerators can get access to
  81. /// all of the sequence's elements without causing multiple enumerations over the source.
  82. /// </summary>
  83. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  84. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  85. /// <param name="source">Source sequence.</param>
  86. /// <param name="readerCount">
  87. /// Number of enumerators that can access the underlying buffer. Once every enumerator has
  88. /// obtained an element from the buffer, the element is removed from the buffer.
  89. /// </param>
  90. /// <param name="selector">
  91. /// Selector function with memoized access to the source sequence for a specified number of
  92. /// enumerators.
  93. /// </param>
  94. /// <returns>Sequence resulting from applying the selector function to the memoized view over the source sequence.</returns>
  95. public static IEnumerable<TResult> Memoize<TSource, TResult>(this IEnumerable<TSource> source, int readerCount, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector)
  96. {
  97. if (source == null)
  98. throw new ArgumentNullException(nameof(source));
  99. if (readerCount <= 0)
  100. throw new ArgumentOutOfRangeException(nameof(readerCount));
  101. if (selector == null)
  102. throw new ArgumentNullException(nameof(selector));
  103. return Create(() => selector(source.Memoize(readerCount)).GetEnumerator());
  104. }
  105. private sealed class MemoizedBuffer<T> : IBuffer<T>
  106. {
  107. private IRefCountList<T> _buffer;
  108. private bool _disposed;
  109. private Exception _error;
  110. private IEnumerator<T> _source;
  111. private bool _stopped;
  112. public MemoizedBuffer(IEnumerator<T> source)
  113. : this(source, new MaxRefCountList<T>())
  114. {
  115. }
  116. public MemoizedBuffer(IEnumerator<T> source, int readerCount)
  117. : this(source, new RefCountList<T>(readerCount))
  118. {
  119. }
  120. private MemoizedBuffer(IEnumerator<T> source, IRefCountList<T> buffer)
  121. {
  122. _source = source;
  123. _buffer = buffer;
  124. }
  125. public IEnumerator<T> GetEnumerator()
  126. {
  127. if (_disposed)
  128. throw new ObjectDisposedException("");
  129. return GetEnumerator_();
  130. }
  131. IEnumerator IEnumerable.GetEnumerator()
  132. {
  133. if (_disposed)
  134. throw new ObjectDisposedException("");
  135. return GetEnumerator();
  136. }
  137. public void Dispose()
  138. {
  139. lock (_source)
  140. {
  141. if (!_disposed)
  142. {
  143. _source.Dispose();
  144. _source = null;
  145. _buffer.Clear();
  146. _buffer = null;
  147. }
  148. _disposed = true;
  149. }
  150. }
  151. private IEnumerator<T> GetEnumerator_()
  152. {
  153. var i = 0;
  154. try
  155. {
  156. while (true)
  157. {
  158. if (_disposed)
  159. throw new ObjectDisposedException("");
  160. var hasValue = default(bool);
  161. var current = default(T);
  162. lock (_source)
  163. {
  164. if (i >= _buffer.Count)
  165. {
  166. if (!_stopped)
  167. {
  168. try
  169. {
  170. hasValue = _source.MoveNext();
  171. if (hasValue)
  172. current = _source.Current;
  173. }
  174. catch (Exception ex)
  175. {
  176. _stopped = true;
  177. _error = ex;
  178. _source.Dispose();
  179. }
  180. }
  181. if (_stopped)
  182. {
  183. if (_error != null)
  184. throw _error;
  185. else
  186. break;
  187. }
  188. if (hasValue)
  189. {
  190. _buffer.Add(current);
  191. }
  192. }
  193. else
  194. {
  195. hasValue = true;
  196. }
  197. }
  198. if (hasValue)
  199. yield return _buffer[i];
  200. else
  201. break;
  202. i++;
  203. }
  204. }
  205. finally
  206. {
  207. if (_buffer != null)
  208. _buffer.Done(i + 1);
  209. }
  210. }
  211. }
  212. }
  213. internal interface IRefCountList<T>
  214. {
  215. void Clear();
  216. int Count { get; }
  217. T this[int i]
  218. {
  219. get;
  220. }
  221. void Add(T item);
  222. void Done(int index);
  223. }
  224. internal sealed class MaxRefCountList<T> : IRefCountList<T>
  225. {
  226. private IList<T> _list = new List<T>();
  227. public void Clear()
  228. {
  229. _list.Clear();
  230. }
  231. public int Count
  232. {
  233. get { return _list.Count; }
  234. }
  235. public T this[int i]
  236. {
  237. get { return _list[i]; }
  238. }
  239. public void Add(T item)
  240. {
  241. _list.Add(item);
  242. }
  243. public void Done(int index)
  244. {
  245. }
  246. }
  247. internal sealed class RefCountList<T> : IRefCountList<T>
  248. {
  249. private int _readerCount;
  250. private readonly IDictionary<int, RefCount> _list;
  251. private int _count;
  252. public RefCountList(int readerCount)
  253. {
  254. _readerCount = readerCount;
  255. _list = new Dictionary<int, RefCount>();
  256. }
  257. public int ReaderCount
  258. {
  259. get
  260. {
  261. return _readerCount;
  262. }
  263. set
  264. {
  265. _readerCount = value;
  266. }
  267. }
  268. public void Clear()
  269. {
  270. _list.Clear();
  271. }
  272. public int Count
  273. {
  274. get { return _count; }
  275. }
  276. public T this[int i]
  277. {
  278. get
  279. {
  280. Debug.Assert(i < _count);
  281. if (!_list.TryGetValue(i, out var res))
  282. throw new InvalidOperationException("Element no longer available in the buffer.");
  283. var val = res.Value;
  284. if (--res.Count == 0)
  285. _list.Remove(i);
  286. return val;
  287. }
  288. }
  289. public void Add(T item)
  290. {
  291. _list[_count] = new RefCount { Value = item, Count = _readerCount };
  292. _count++;
  293. }
  294. public void Done(int index)
  295. {
  296. for (int i = index; i < _count; i++)
  297. {
  298. var ignore = this[i];
  299. }
  300. _readerCount--;
  301. }
  302. private sealed class RefCount
  303. {
  304. public int Count;
  305. public T Value;
  306. }
  307. }
  308. }