Memoize.cs 13 KB

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