Memoize.cs 12 KB

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