OrderedAsyncEnumerable.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. // NB: Large portions of the implementation are based on https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/OrderedEnumerable.cs.
  12. internal abstract class OrderedAsyncEnumerable<TElement> : AsyncIterator<TElement>, IOrderedAsyncEnumerable<TElement>, IAsyncPartition<TElement>
  13. {
  14. protected readonly IAsyncEnumerable<TElement> _source;
  15. private TElement[] _buffer;
  16. private int[] _indexes;
  17. private int _index;
  18. protected OrderedAsyncEnumerable(IAsyncEnumerable<TElement> source)
  19. {
  20. Debug.Assert(source != null);
  21. _source = source;
  22. }
  23. IOrderedAsyncEnumerable<TElement> IOrderedAsyncEnumerable<TElement>.CreateOrderedEnumerable<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending)
  24. {
  25. return new OrderedAsyncEnumerable<TElement, TKey>(_source, keySelector, comparer, descending, this);
  26. }
  27. IOrderedAsyncEnumerable<TElement> IOrderedAsyncEnumerable<TElement>.CreateOrderedEnumerable<TKey>(Func<TElement, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending)
  28. {
  29. return new OrderedAsyncEnumerableWithTask<TElement, TKey>(_source, keySelector, comparer, descending, this);
  30. }
  31. IOrderedAsyncEnumerable<TElement> IOrderedAsyncEnumerable<TElement>.CreateOrderedEnumerable<TKey>(Func<TElement, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending)
  32. {
  33. return new OrderedAsyncEnumerableWithTaskAndCancellation<TElement, TKey>(_source, keySelector, comparer, descending, this);
  34. }
  35. protected override async ValueTask<bool> MoveNextCore()
  36. {
  37. switch (_state)
  38. {
  39. case AsyncIteratorState.Allocated:
  40. _buffer = await _source.ToArrayAsync(_cancellationToken).ConfigureAwait(false); // TODO: Use buffer.
  41. var sorter = GetAsyncEnumerableSorter(_cancellationToken);
  42. _indexes = await sorter.Sort(_buffer, _buffer.Length).ConfigureAwait(false);
  43. _index = 0;
  44. _state = AsyncIteratorState.Iterating;
  45. goto case AsyncIteratorState.Iterating;
  46. case AsyncIteratorState.Iterating:
  47. if (_index < _buffer.Length)
  48. {
  49. _current = _buffer[_indexes[_index++]];
  50. return true;
  51. }
  52. await DisposeAsync().ConfigureAwait(false);
  53. break;
  54. }
  55. return false;
  56. }
  57. public override async ValueTask DisposeAsync()
  58. {
  59. _buffer = null;
  60. _indexes = null;
  61. await base.DisposeAsync().ConfigureAwait(false);
  62. }
  63. internal abstract AsyncEnumerableSorter<TElement> GetAsyncEnumerableSorter(AsyncEnumerableSorter<TElement> next, CancellationToken cancellationToken);
  64. internal AsyncEnumerableSorter<TElement> GetAsyncEnumerableSorter(CancellationToken cancellationToken) => GetAsyncEnumerableSorter(next: null, cancellationToken);
  65. public async ValueTask<TElement[]> ToArrayAsync(CancellationToken cancellationToken)
  66. {
  67. var elements = await AsyncEnumerableHelpers.ToArrayWithLength(_source, cancellationToken).ConfigureAwait(false);
  68. var count = elements.Length;
  69. if (count == 0)
  70. {
  71. #if NO_ARRAY_EMPTY
  72. return EmptyArray<TElement>.Value;
  73. #else
  74. return Array.Empty<TElement>();
  75. #endif
  76. }
  77. var array = elements.Array;
  78. var map = await SortedMap(array, count, cancellationToken).ConfigureAwait(false);
  79. var result = new TElement[count];
  80. for (var i = 0; i < result.Length; i++)
  81. {
  82. result[i] = array[map[i]];
  83. }
  84. return result;
  85. }
  86. internal async ValueTask<TElement[]> ToArrayAsync(int minIndexInclusive, int maxIndexInclusive, CancellationToken cancellationToken)
  87. {
  88. var elements = await AsyncEnumerableHelpers.ToArrayWithLength(_source, cancellationToken).ConfigureAwait(false);
  89. var count = elements.Length;
  90. if (count <= minIndexInclusive)
  91. {
  92. #if NO_ARRAY_EMPTY
  93. return EmptyArray<TElement>.Value;
  94. #else
  95. return Array.Empty<TElement>();
  96. #endif
  97. }
  98. if (count <= maxIndexInclusive)
  99. {
  100. maxIndexInclusive = count - 1;
  101. }
  102. var array = elements.Array;
  103. if (minIndexInclusive == maxIndexInclusive)
  104. {
  105. var sorter = GetAsyncEnumerableSorter(cancellationToken);
  106. var element = await sorter.ElementAt(array, count, minIndexInclusive).ConfigureAwait(false);
  107. return new TElement[] { element };
  108. }
  109. var map = await SortedMap(array, count, minIndexInclusive, maxIndexInclusive, cancellationToken).ConfigureAwait(false);
  110. var result = new TElement[maxIndexInclusive - minIndexInclusive + 1];
  111. for (var i = 0; minIndexInclusive <= maxIndexInclusive; i++)
  112. {
  113. result[i] = array[map[minIndexInclusive++]];
  114. }
  115. return result;
  116. }
  117. public async ValueTask<List<TElement>> ToListAsync(CancellationToken cancellationToken)
  118. {
  119. var elements = await AsyncEnumerableHelpers.ToArrayWithLength(_source, cancellationToken).ConfigureAwait(false);
  120. var count = elements.Length;
  121. if (count == 0)
  122. {
  123. return new List<TElement>(capacity: 0);
  124. }
  125. var array = elements.Array;
  126. var map = await SortedMap(array, count, cancellationToken).ConfigureAwait(false);
  127. var result = new List<TElement>(count);
  128. for (var i = 0; i < count; i++)
  129. {
  130. result.Add(array[map[i]]);
  131. }
  132. return result;
  133. }
  134. internal async ValueTask<List<TElement>> ToListAsync(int minIndexInclusive, int maxIndexInclusive, CancellationToken cancellationToken)
  135. {
  136. var elements = await AsyncEnumerableHelpers.ToArrayWithLength(_source, cancellationToken).ConfigureAwait(false);
  137. var count = elements.Length;
  138. if (count <= minIndexInclusive)
  139. {
  140. return new List<TElement>(0);
  141. }
  142. if (count <= maxIndexInclusive)
  143. {
  144. maxIndexInclusive = count - 1;
  145. }
  146. var array = elements.Array;
  147. if (minIndexInclusive == maxIndexInclusive)
  148. {
  149. var sorter = GetAsyncEnumerableSorter(cancellationToken);
  150. var element = await sorter.ElementAt(array, count, minIndexInclusive).ConfigureAwait(false);
  151. return new List<TElement>(1) { element };
  152. }
  153. var map = await SortedMap(array, count, minIndexInclusive, maxIndexInclusive, cancellationToken).ConfigureAwait(false);
  154. var list = new List<TElement>(maxIndexInclusive - minIndexInclusive + 1);
  155. while (minIndexInclusive <= maxIndexInclusive)
  156. {
  157. list.Add(array[map[minIndexInclusive++]]);
  158. }
  159. return list;
  160. }
  161. public async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  162. {
  163. if (_source is IAsyncIListProvider<TElement> listProv)
  164. {
  165. var count = await listProv.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  166. }
  167. return !onlyIfCheap || _source is ICollection<TElement> || _source is ICollection ? await _source.CountAsync(cancellationToken).ConfigureAwait(false) : -1;
  168. }
  169. internal async ValueTask<int> GetCountAsync(int minIndexInclusive, int maxIndexInclusive, bool onlyIfCheap, CancellationToken cancellationToken)
  170. {
  171. var count = await GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(false);
  172. if (count <= 0)
  173. {
  174. return count;
  175. }
  176. if (count <= minIndexInclusive)
  177. {
  178. return 0;
  179. }
  180. return (count <= maxIndexInclusive ? count : maxIndexInclusive + 1) - minIndexInclusive;
  181. }
  182. private ValueTask<int[]> SortedMap(TElement[] elements, int count, CancellationToken cancellationToken)
  183. {
  184. var sorter = GetAsyncEnumerableSorter(cancellationToken);
  185. return sorter.Sort(elements, count);
  186. }
  187. private ValueTask<int[]> SortedMap(TElement[] elements, int count, int minIndexInclusive, int maxIndexInclusive, CancellationToken cancellationToken)
  188. {
  189. var sorter = GetAsyncEnumerableSorter(cancellationToken);
  190. return sorter.Sort(elements, count, minIndexInclusive, maxIndexInclusive);
  191. }
  192. private AsyncCachingComparer<TElement> GetComparer() => GetComparer(childComparer: null);
  193. internal abstract AsyncCachingComparer<TElement> GetComparer(AsyncCachingComparer<TElement> childComparer);
  194. public async ValueTask<Maybe<TElement>> TryGetFirstAsync(CancellationToken cancellationToken)
  195. {
  196. #if CSHARP8
  197. await using (IAsyncEnumerator<TElement> e = _source.GetAsyncEnumerator(cancellationToken).ConfigureAwait(false))
  198. {
  199. if (!await e.MoveNextAsync())
  200. {
  201. return new Maybe<TElement>();
  202. }
  203. var value = e.Current;
  204. var comparer = GetComparer();
  205. await comparer.SetElement(value, cancellationToken).ConfigureAwait(false);
  206. while (await e.MoveNextAsync())
  207. {
  208. var x = e.Current;
  209. if (await comparer.Compare(x, cacheLower: true, cancellationToken).ConfigureAwait(false) < 0)
  210. {
  211. value = x;
  212. }
  213. }
  214. return new Maybe<TElement>(value);
  215. }
  216. #else
  217. IAsyncEnumerator<TElement> e = _source.GetAsyncEnumerator(cancellationToken);
  218. try
  219. {
  220. if (!await e.MoveNextAsync().ConfigureAwait(false))
  221. {
  222. return new Maybe<TElement>();
  223. }
  224. TElement value = e.Current;
  225. AsyncCachingComparer<TElement> comparer = GetComparer();
  226. await comparer.SetElement(value, cancellationToken).ConfigureAwait(false);
  227. while (await e.MoveNextAsync().ConfigureAwait(false))
  228. {
  229. TElement x = e.Current;
  230. if (await comparer.Compare(x, cacheLower: true, cancellationToken).ConfigureAwait(false) < 0)
  231. {
  232. value = x;
  233. }
  234. }
  235. return new Maybe<TElement>(value);
  236. }
  237. finally
  238. {
  239. await e.DisposeAsync().ConfigureAwait(false);
  240. }
  241. #endif
  242. }
  243. public async ValueTask<Maybe<TElement>> TryGetLastAsync(CancellationToken cancellationToken)
  244. {
  245. #if CSHARP8
  246. await using (IAsyncEnumerator<TElement> e = _source.GetAsyncEnumerator(cancellationToken).ConfigureAwait(false))
  247. {
  248. if (!await e.MoveNextAsync())
  249. {
  250. return new Maybe<TElement>();
  251. }
  252. var value = e.Current;
  253. var comparer = GetComparer();
  254. await comparer.SetElement(value, cancellationToken).ConfigureAwait(false);
  255. while (await e.MoveNextAsync())
  256. {
  257. var current = e.Current;
  258. if (await comparer.Compare(current, cacheLower: false, cancellationToken).ConfigureAwait(false) >= 0)
  259. {
  260. value = current;
  261. }
  262. }
  263. return new Maybe<TElement>(value);
  264. }
  265. #else
  266. IAsyncEnumerator<TElement> e = _source.GetAsyncEnumerator(cancellationToken);
  267. try
  268. {
  269. if (!await e.MoveNextAsync().ConfigureAwait(false))
  270. {
  271. return new Maybe<TElement>();
  272. }
  273. TElement value = e.Current;
  274. AsyncCachingComparer<TElement> comparer = GetComparer();
  275. await comparer.SetElement(value, cancellationToken).ConfigureAwait(false);
  276. while (await e.MoveNextAsync().ConfigureAwait(false))
  277. {
  278. TElement current = e.Current;
  279. if (await comparer.Compare(current, cacheLower: false, cancellationToken).ConfigureAwait(false) >= 0)
  280. {
  281. value = current;
  282. }
  283. }
  284. return new Maybe<TElement>(value);
  285. }
  286. finally
  287. {
  288. await e.DisposeAsync().ConfigureAwait(false);
  289. }
  290. #endif
  291. }
  292. internal async ValueTask<Maybe<TElement>> TryGetLastAsync(int minIndexInclusive, int maxIndexInclusive, CancellationToken cancellationToken)
  293. {
  294. var elements = await AsyncEnumerableHelpers.ToArrayWithLength(_source, cancellationToken).ConfigureAwait(false);
  295. var count = elements.Length;
  296. if (minIndexInclusive >= count)
  297. {
  298. return new Maybe<TElement>();
  299. }
  300. var array = elements.Array;
  301. TElement last;
  302. if (maxIndexInclusive < count - 1)
  303. {
  304. var sorter = GetAsyncEnumerableSorter(cancellationToken);
  305. last = await sorter.ElementAt(array, count, maxIndexInclusive).ConfigureAwait(false);
  306. }
  307. else
  308. {
  309. last = await Last(array, count, cancellationToken).ConfigureAwait(false);
  310. }
  311. return new Maybe<TElement>(last);
  312. }
  313. private async ValueTask<TElement> Last(TElement[] items, int count, CancellationToken cancellationToken)
  314. {
  315. var value = items[0];
  316. var comparer = GetComparer();
  317. await comparer.SetElement(value, cancellationToken).ConfigureAwait(false);
  318. for (var i = 1; i != count; ++i)
  319. {
  320. var x = items[i];
  321. if (await comparer.Compare(x, cacheLower: false, cancellationToken).ConfigureAwait(false) >= 0)
  322. {
  323. value = x;
  324. }
  325. }
  326. return value;
  327. }
  328. public IAsyncPartition<TElement> Skip(int count) => new OrderedAsyncPartition<TElement>(this, count, int.MaxValue);
  329. public IAsyncPartition<TElement> Take(int count) => new OrderedAsyncPartition<TElement>(this, 0, count - 1);
  330. public ValueTask<Maybe<TElement>> TryGetElementAtAsync(int index, CancellationToken cancellationToken)
  331. {
  332. if (index == 0)
  333. {
  334. return TryGetFirstAsync(cancellationToken);
  335. }
  336. if (index > 0)
  337. {
  338. return Core();
  339. async ValueTask<Maybe<TElement>> Core()
  340. {
  341. var elements = await AsyncEnumerableHelpers.ToArrayWithLength(_source, cancellationToken).ConfigureAwait(false);
  342. var count = elements.Length;
  343. if (index < count)
  344. {
  345. var sorter = GetAsyncEnumerableSorter(cancellationToken);
  346. var element = await sorter.ElementAt(elements.Array, count, index).ConfigureAwait(false);
  347. return new Maybe<TElement>(element);
  348. }
  349. return new Maybe<TElement>();
  350. }
  351. }
  352. return new ValueTask<Maybe<TElement>>(new Maybe<TElement>());
  353. }
  354. }
  355. internal sealed class OrderedAsyncEnumerable<TElement, TKey> : OrderedAsyncEnumerable<TElement>
  356. {
  357. private readonly IComparer<TKey> _comparer;
  358. private readonly bool _descending;
  359. private readonly Func<TElement, TKey> _keySelector;
  360. private readonly OrderedAsyncEnumerable<TElement> _parent;
  361. public OrderedAsyncEnumerable(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, OrderedAsyncEnumerable<TElement> parent)
  362. : base(source)
  363. {
  364. Debug.Assert(keySelector != null);
  365. _keySelector = keySelector;
  366. _comparer = comparer ?? Comparer<TKey>.Default;
  367. _descending = descending;
  368. _parent = parent;
  369. }
  370. public override AsyncIteratorBase<TElement> Clone()
  371. {
  372. return new OrderedAsyncEnumerable<TElement, TKey>(_source, _keySelector, _comparer, _descending, _parent);
  373. }
  374. internal override AsyncEnumerableSorter<TElement> GetAsyncEnumerableSorter(AsyncEnumerableSorter<TElement> next, CancellationToken cancellationToken)
  375. {
  376. var sorter = new SyncKeySelectorAsyncEnumerableSorter<TElement, TKey>(_keySelector, _comparer, _descending, next);
  377. if (_parent != null)
  378. {
  379. return _parent.GetAsyncEnumerableSorter(sorter, cancellationToken);
  380. }
  381. return sorter;
  382. }
  383. internal override AsyncCachingComparer<TElement> GetComparer(AsyncCachingComparer<TElement> childComparer)
  384. {
  385. AsyncCachingComparer<TElement> cmp = childComparer == null
  386. ? new AsyncCachingComparer<TElement, TKey>(_keySelector, _comparer, _descending)
  387. : new AsyncCachingComparerWithChild<TElement, TKey>(_keySelector, _comparer, _descending, childComparer);
  388. return _parent != null ? _parent.GetComparer(cmp) : cmp;
  389. }
  390. }
  391. internal sealed class OrderedAsyncEnumerableWithTask<TElement, TKey> : OrderedAsyncEnumerable<TElement>
  392. {
  393. private readonly IComparer<TKey> _comparer;
  394. private readonly bool _descending;
  395. private readonly Func<TElement, ValueTask<TKey>> _keySelector;
  396. private readonly OrderedAsyncEnumerable<TElement> _parent;
  397. public OrderedAsyncEnumerableWithTask(IAsyncEnumerable<TElement> source, Func<TElement, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending, OrderedAsyncEnumerable<TElement> parent)
  398. : base(source)
  399. {
  400. Debug.Assert(keySelector != null);
  401. _keySelector = keySelector;
  402. _comparer = comparer ?? Comparer<TKey>.Default;
  403. _descending = descending;
  404. _parent = parent;
  405. }
  406. public override AsyncIteratorBase<TElement> Clone()
  407. {
  408. return new OrderedAsyncEnumerableWithTask<TElement, TKey>(_source, _keySelector, _comparer, _descending, _parent);
  409. }
  410. internal override AsyncEnumerableSorter<TElement> GetAsyncEnumerableSorter(AsyncEnumerableSorter<TElement> next, CancellationToken cancellationToken)
  411. {
  412. var sorter = new AsyncKeySelectorAsyncEnumerableSorter<TElement, TKey>(_keySelector, _comparer, _descending, next);
  413. if (_parent != null)
  414. {
  415. return _parent.GetAsyncEnumerableSorter(sorter, cancellationToken);
  416. }
  417. return sorter;
  418. }
  419. internal override AsyncCachingComparer<TElement> GetComparer(AsyncCachingComparer<TElement> childComparer)
  420. {
  421. AsyncCachingComparer<TElement> cmp = childComparer == null
  422. ? new AsyncCachingComparerWithTask<TElement, TKey>(_keySelector, _comparer, _descending)
  423. : new AsyncCachingComparerWithTaskAndChild<TElement, TKey>(_keySelector, _comparer, _descending, childComparer);
  424. return _parent != null ? _parent.GetComparer(cmp) : cmp;
  425. }
  426. }
  427. #if !NO_DEEP_CANCELLATION
  428. internal sealed class OrderedAsyncEnumerableWithTaskAndCancellation<TElement, TKey> : OrderedAsyncEnumerable<TElement>
  429. {
  430. private readonly IComparer<TKey> _comparer;
  431. private readonly bool _descending;
  432. private readonly Func<TElement, CancellationToken, ValueTask<TKey>> _keySelector;
  433. private readonly OrderedAsyncEnumerable<TElement> _parent;
  434. public OrderedAsyncEnumerableWithTaskAndCancellation(IAsyncEnumerable<TElement> source, Func<TElement, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending, OrderedAsyncEnumerable<TElement> parent)
  435. : base(source)
  436. {
  437. Debug.Assert(keySelector != null);
  438. _keySelector = keySelector;
  439. _comparer = comparer ?? Comparer<TKey>.Default;
  440. _descending = descending;
  441. _parent = parent;
  442. }
  443. public override AsyncIteratorBase<TElement> Clone()
  444. {
  445. return new OrderedAsyncEnumerableWithTaskAndCancellation<TElement, TKey>(_source, _keySelector, _comparer, _descending, _parent);
  446. }
  447. internal override AsyncEnumerableSorter<TElement> GetAsyncEnumerableSorter(AsyncEnumerableSorter<TElement> next, CancellationToken cancellationToken)
  448. {
  449. var sorter = new AsyncKeySelectorAsyncEnumerableSorterWithCancellation<TElement, TKey>(_keySelector, _comparer, _descending, next, cancellationToken);
  450. if (_parent != null)
  451. {
  452. return _parent.GetAsyncEnumerableSorter(sorter, cancellationToken);
  453. }
  454. return sorter;
  455. }
  456. internal override AsyncCachingComparer<TElement> GetComparer(AsyncCachingComparer<TElement> childComparer)
  457. {
  458. AsyncCachingComparer<TElement> cmp = childComparer == null
  459. ? new AsyncCachingComparerWithTaskAndCancellation<TElement, TKey>(_keySelector, _comparer, _descending)
  460. : new AsyncCachingComparerWithTaskAndCancellationAndChild<TElement, TKey>(_keySelector, _comparer, _descending, childComparer);
  461. return _parent != null ? _parent.GetComparer(cmp) : cmp;
  462. }
  463. }
  464. #endif
  465. internal abstract class AsyncEnumerableSorter<TElement>
  466. {
  467. internal abstract ValueTask ComputeKeys(TElement[] elements, int count);
  468. internal abstract int CompareAnyKeys(int index1, int index2);
  469. public async ValueTask<int[]> Sort(TElement[] elements, int count)
  470. {
  471. var map = await ComputeMap(elements, count).ConfigureAwait(false);
  472. QuickSort(map, 0, count - 1);
  473. return map;
  474. }
  475. public async ValueTask<int[]> Sort(TElement[] elements, int count, int minIndexInclusive, int maxIndexInclusive)
  476. {
  477. var map = await ComputeMap(elements, count).ConfigureAwait(false);
  478. PartialQuickSort(map, 0, count - 1, minIndexInclusive, maxIndexInclusive);
  479. return map;
  480. }
  481. public async ValueTask<TElement> ElementAt(TElement[] elements, int count, int index)
  482. {
  483. var map = await ComputeMap(elements, count).ConfigureAwait(false);
  484. return index == 0 ?
  485. elements[Min(map, count)] :
  486. elements[QuickSelect(map, count - 1, index)];
  487. }
  488. private async ValueTask<int[]> ComputeMap(TElement[] elements, int count)
  489. {
  490. await ComputeKeys(elements, count).ConfigureAwait(false);
  491. var map = new int[count];
  492. for (var i = 0; i < count; i++)
  493. {
  494. map[i] = i;
  495. }
  496. return map;
  497. }
  498. protected abstract void QuickSort(int[] map, int left, int right);
  499. protected abstract void PartialQuickSort(int[] map, int left, int right, int minIndexInclusive, int maxIndexInclusive);
  500. protected abstract int QuickSelect(int[] map, int right, int idx);
  501. protected abstract int Min(int[] map, int count);
  502. }
  503. internal abstract class AsyncEnumerableSorterBase<TElement, TKey> : AsyncEnumerableSorter<TElement>
  504. {
  505. private readonly IComparer<TKey> _comparer;
  506. private readonly bool _descending;
  507. protected readonly AsyncEnumerableSorter<TElement> _next;
  508. protected TKey[] _keys;
  509. public AsyncEnumerableSorterBase(IComparer<TKey> comparer, bool descending, AsyncEnumerableSorter<TElement> next)
  510. {
  511. _comparer = comparer;
  512. _descending = descending;
  513. _next = next;
  514. }
  515. internal sealed override int CompareAnyKeys(int index1, int index2)
  516. {
  517. var c = _comparer.Compare(_keys[index1], _keys[index2]);
  518. if (c == 0)
  519. {
  520. return _next == null ? index1 - index2 : _next.CompareAnyKeys(index1, index2);
  521. }
  522. else
  523. {
  524. return (_descending != (c > 0)) ? 1 : -1;
  525. }
  526. }
  527. private int CompareKeys(int index1, int index2) => index1 == index2 ? 0 : CompareAnyKeys(index1, index2);
  528. protected override void QuickSort(int[] map, int left, int right)
  529. {
  530. // REVIEW: Consider using Array.Sort, see https://github.com/dotnet/corefx/commit/a6aff797a33e606a60ec0c9ca034a161c609620f#diff-d90239bd8284188e2bd210790483f5ca.
  531. do
  532. {
  533. var i = left;
  534. var j = right;
  535. var x = map[i + ((j - i) >> 1)];
  536. do
  537. {
  538. while (i < map.Length && CompareKeys(x, map[i]) > 0)
  539. {
  540. i++;
  541. }
  542. while (j >= 0 && CompareKeys(x, map[j]) < 0)
  543. {
  544. j--;
  545. }
  546. if (i > j)
  547. {
  548. break;
  549. }
  550. if (i < j)
  551. {
  552. var temp = map[i];
  553. map[i] = map[j];
  554. map[j] = temp;
  555. }
  556. i++;
  557. j--;
  558. }
  559. while (i <= j);
  560. if (j - left <= right - i)
  561. {
  562. if (left < j)
  563. {
  564. QuickSort(map, left, j);
  565. }
  566. left = i;
  567. }
  568. else
  569. {
  570. if (i < right)
  571. {
  572. QuickSort(map, i, right);
  573. }
  574. right = j;
  575. }
  576. }
  577. while (left < right);
  578. }
  579. protected override void PartialQuickSort(int[] map, int left, int right, int minIndexInclusive, int maxIndexInclusive)
  580. {
  581. do
  582. {
  583. var i = left;
  584. var j = right;
  585. var x = map[i + ((j - i) >> 1)];
  586. do
  587. {
  588. while (i < map.Length && CompareKeys(x, map[i]) > 0)
  589. {
  590. i++;
  591. }
  592. while (j >= 0 && CompareKeys(x, map[j]) < 0)
  593. {
  594. j--;
  595. }
  596. if (i > j)
  597. {
  598. break;
  599. }
  600. if (i < j)
  601. {
  602. var temp = map[i];
  603. map[i] = map[j];
  604. map[j] = temp;
  605. }
  606. i++;
  607. j--;
  608. }
  609. while (i <= j);
  610. if (minIndexInclusive >= i)
  611. {
  612. left = i + 1;
  613. }
  614. else if (maxIndexInclusive <= j)
  615. {
  616. right = j - 1;
  617. }
  618. if (j - left <= right - i)
  619. {
  620. if (left < j)
  621. {
  622. PartialQuickSort(map, left, j, minIndexInclusive, maxIndexInclusive);
  623. }
  624. left = i;
  625. }
  626. else
  627. {
  628. if (i < right)
  629. {
  630. PartialQuickSort(map, i, right, minIndexInclusive, maxIndexInclusive);
  631. }
  632. right = j;
  633. }
  634. }
  635. while (left < right);
  636. }
  637. protected override int QuickSelect(int[] map, int right, int idx)
  638. {
  639. var left = 0;
  640. do
  641. {
  642. var i = left;
  643. var j = right;
  644. var x = map[i + ((j - i) >> 1)];
  645. do
  646. {
  647. while (i < map.Length && CompareKeys(x, map[i]) > 0)
  648. {
  649. i++;
  650. }
  651. while (j >= 0 && CompareKeys(x, map[j]) < 0)
  652. {
  653. j--;
  654. }
  655. if (i > j)
  656. {
  657. break;
  658. }
  659. if (i < j)
  660. {
  661. var temp = map[i];
  662. map[i] = map[j];
  663. map[j] = temp;
  664. }
  665. i++;
  666. j--;
  667. }
  668. while (i <= j);
  669. if (i <= idx)
  670. {
  671. left = i + 1;
  672. }
  673. else
  674. {
  675. right = j - 1;
  676. }
  677. if (j - left <= right - i)
  678. {
  679. if (left < j)
  680. {
  681. right = j;
  682. }
  683. left = i;
  684. }
  685. else
  686. {
  687. if (i < right)
  688. {
  689. left = i;
  690. }
  691. right = j;
  692. }
  693. }
  694. while (left < right);
  695. return map[idx];
  696. }
  697. protected override int Min(int[] map, int count)
  698. {
  699. var index = 0;
  700. for (var i = 1; i < count; i++)
  701. {
  702. if (CompareKeys(map[i], map[index]) < 0)
  703. {
  704. index = i;
  705. }
  706. }
  707. return map[index];
  708. }
  709. }
  710. internal sealed class SyncKeySelectorAsyncEnumerableSorter<TElement, TKey> : AsyncEnumerableSorterBase<TElement, TKey>
  711. {
  712. private readonly Func<TElement, TKey> _keySelector;
  713. public SyncKeySelectorAsyncEnumerableSorter(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, AsyncEnumerableSorter<TElement> next)
  714. : base(comparer, descending, next)
  715. {
  716. _keySelector = keySelector;
  717. }
  718. internal override async ValueTask ComputeKeys(TElement[] elements, int count)
  719. {
  720. _keys = new TKey[count];
  721. for (var i = 0; i < count; i++)
  722. {
  723. _keys[i] = _keySelector(elements[i]);
  724. }
  725. if (_next != null)
  726. {
  727. await _next.ComputeKeys(elements, count).ConfigureAwait(false);
  728. }
  729. }
  730. }
  731. internal sealed class AsyncKeySelectorAsyncEnumerableSorter<TElement, TKey> : AsyncEnumerableSorterBase<TElement, TKey>
  732. {
  733. private readonly Func<TElement, ValueTask<TKey>> _keySelector;
  734. public AsyncKeySelectorAsyncEnumerableSorter(Func<TElement, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending, AsyncEnumerableSorter<TElement> next)
  735. : base(comparer, descending, next)
  736. {
  737. _keySelector = keySelector;
  738. }
  739. internal override async ValueTask ComputeKeys(TElement[] elements, int count)
  740. {
  741. _keys = new TKey[count];
  742. for (var i = 0; i < count; i++)
  743. {
  744. _keys[i] = await _keySelector(elements[i]).ConfigureAwait(false);
  745. }
  746. if (_next != null)
  747. {
  748. await _next.ComputeKeys(elements, count).ConfigureAwait(false);
  749. }
  750. }
  751. }
  752. #if !NO_DEEP_CANCELLATION
  753. internal sealed class AsyncKeySelectorAsyncEnumerableSorterWithCancellation<TElement, TKey> : AsyncEnumerableSorterBase<TElement, TKey>
  754. {
  755. private readonly Func<TElement, CancellationToken, ValueTask<TKey>> _keySelector;
  756. private readonly CancellationToken _cancellationToken;
  757. public AsyncKeySelectorAsyncEnumerableSorterWithCancellation(Func<TElement, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending, AsyncEnumerableSorter<TElement> next, CancellationToken cancellationToken)
  758. : base(comparer, descending, next)
  759. {
  760. _keySelector = keySelector;
  761. _cancellationToken = cancellationToken;
  762. }
  763. internal override async ValueTask ComputeKeys(TElement[] elements, int count)
  764. {
  765. _keys = new TKey[count];
  766. for (var i = 0; i < count; i++)
  767. {
  768. _keys[i] = await _keySelector(elements[i], _cancellationToken).ConfigureAwait(false);
  769. }
  770. if (_next != null)
  771. {
  772. await _next.ComputeKeys(elements, count).ConfigureAwait(false);
  773. }
  774. }
  775. }
  776. #endif
  777. internal sealed class OrderedAsyncPartition<TElement> : AsyncIterator<TElement>, IAsyncPartition<TElement>
  778. {
  779. private readonly OrderedAsyncEnumerable<TElement> _source;
  780. private readonly int _minIndexInclusive;
  781. private readonly int _maxIndexInclusive;
  782. public OrderedAsyncPartition(OrderedAsyncEnumerable<TElement> source, int minIndexInclusive, int maxIndexInclusive)
  783. {
  784. _source = source;
  785. _minIndexInclusive = minIndexInclusive;
  786. _maxIndexInclusive = maxIndexInclusive;
  787. }
  788. public override AsyncIteratorBase<TElement> Clone() => new OrderedAsyncPartition<TElement>(_source, _minIndexInclusive, _maxIndexInclusive);
  789. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken) =>
  790. _source.GetCountAsync(_minIndexInclusive, _maxIndexInclusive, onlyIfCheap, cancellationToken);
  791. public IAsyncPartition<TElement> Skip(int count)
  792. {
  793. var minIndex = unchecked(_minIndexInclusive + count);
  794. if (unchecked((uint)minIndex > (uint)_maxIndexInclusive))
  795. {
  796. return AsyncEnumerable.EmptyAsyncIterator<TElement>.Instance;
  797. }
  798. return new OrderedAsyncPartition<TElement>(_source, minIndex, _maxIndexInclusive);
  799. }
  800. public IAsyncPartition<TElement> Take(int count)
  801. {
  802. var maxIndex = unchecked(_minIndexInclusive + count - 1);
  803. if (unchecked((uint)maxIndex >= (uint)_maxIndexInclusive))
  804. {
  805. return this;
  806. }
  807. return new OrderedAsyncPartition<TElement>(_source, _minIndexInclusive, maxIndex);
  808. }
  809. public ValueTask<TElement[]> ToArrayAsync(CancellationToken cancellationToken) =>
  810. _source.ToArrayAsync(_minIndexInclusive, _maxIndexInclusive, cancellationToken);
  811. public ValueTask<List<TElement>> ToListAsync(CancellationToken cancellationToken) =>
  812. _source.ToListAsync(_minIndexInclusive, _maxIndexInclusive, cancellationToken);
  813. public ValueTask<Maybe<TElement>> TryGetElementAtAsync(int index, CancellationToken cancellationToken)
  814. {
  815. if (unchecked((uint)index <= (uint)(_maxIndexInclusive - _minIndexInclusive)))
  816. {
  817. return _source.TryGetElementAtAsync(index + _minIndexInclusive, cancellationToken);
  818. }
  819. return new ValueTask<Maybe<TElement>>(new Maybe<TElement>());
  820. }
  821. public ValueTask<Maybe<TElement>> TryGetFirstAsync(CancellationToken cancellationToken) =>
  822. _source.TryGetElementAtAsync(_minIndexInclusive, cancellationToken);
  823. public ValueTask<Maybe<TElement>> TryGetLastAsync(CancellationToken cancellationToken) =>
  824. _source.TryGetLastAsync(_minIndexInclusive, _maxIndexInclusive, cancellationToken);
  825. // REVIEW: Consider to tear off an iterator object rather than storing this state here?
  826. private TElement[] _buffer;
  827. private int[] _indexes;
  828. private int _minIndexIterator;
  829. private int _maxIndexIterator;
  830. protected override async ValueTask<bool> MoveNextCore()
  831. {
  832. switch (_state)
  833. {
  834. case AsyncIteratorState.Allocated:
  835. _buffer = await _source.ToArrayAsync(_cancellationToken).ConfigureAwait(false); // TODO: Use buffer.
  836. _minIndexIterator = _minIndexInclusive;
  837. _maxIndexIterator = _maxIndexInclusive;
  838. var count = _buffer.Length;
  839. if (count > _minIndexIterator)
  840. {
  841. if (count <= _maxIndexIterator)
  842. {
  843. _maxIndexIterator = count - 1;
  844. }
  845. var sorter = _source.GetAsyncEnumerableSorter(_cancellationToken);
  846. if (_minIndexIterator == _maxIndexIterator)
  847. {
  848. _current = await sorter.ElementAt(_buffer, _buffer.Length, _minIndexIterator).ConfigureAwait(false);
  849. _minIndexIterator = int.MaxValue;
  850. _maxIndexIterator = int.MinValue;
  851. _state = AsyncIteratorState.Iterating;
  852. return true;
  853. }
  854. else
  855. {
  856. _indexes = await sorter.Sort(_buffer, _buffer.Length, _minIndexIterator, _maxIndexIterator).ConfigureAwait(false);
  857. }
  858. _state = AsyncIteratorState.Iterating;
  859. goto case AsyncIteratorState.Iterating;
  860. }
  861. await DisposeAsync();
  862. break;
  863. case AsyncIteratorState.Iterating:
  864. if (_minIndexIterator <= _maxIndexIterator)
  865. {
  866. _current = _buffer[_indexes[_minIndexIterator++]];
  867. return true;
  868. }
  869. await DisposeAsync().ConfigureAwait(false);
  870. break;
  871. }
  872. return false;
  873. }
  874. public override async ValueTask DisposeAsync()
  875. {
  876. _buffer = null;
  877. _indexes = null;
  878. await base.DisposeAsync().ConfigureAwait(false);
  879. }
  880. }
  881. internal abstract class AsyncCachingComparer<TElement>
  882. {
  883. internal abstract ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken);
  884. internal abstract ValueTask SetElement(TElement element, CancellationToken cancellationToken);
  885. }
  886. internal class AsyncCachingComparer<TElement, TKey> : AsyncCachingComparer<TElement>
  887. {
  888. protected readonly Func<TElement, TKey> _keySelector;
  889. protected readonly IComparer<TKey> _comparer;
  890. protected readonly bool _descending;
  891. protected TKey _lastKey;
  892. public AsyncCachingComparer(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending)
  893. {
  894. _keySelector = keySelector;
  895. _comparer = comparer;
  896. _descending = descending;
  897. }
  898. internal override ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken)
  899. {
  900. var newKey = _keySelector(element);
  901. var cmp = _descending ? _comparer.Compare(_lastKey, newKey) : _comparer.Compare(newKey, _lastKey);
  902. if (cacheLower == cmp < 0)
  903. {
  904. _lastKey = newKey;
  905. }
  906. return new ValueTask<int>(cmp);
  907. }
  908. internal override ValueTask SetElement(TElement element, CancellationToken cancellationToken)
  909. {
  910. _lastKey = _keySelector(element);
  911. return new ValueTask();
  912. }
  913. }
  914. internal sealed class AsyncCachingComparerWithChild<TElement, TKey> : AsyncCachingComparer<TElement, TKey>
  915. {
  916. private readonly AsyncCachingComparer<TElement> _child;
  917. public AsyncCachingComparerWithChild(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, AsyncCachingComparer<TElement> child)
  918. : base(keySelector, comparer, descending)
  919. {
  920. _child = child;
  921. }
  922. internal override async ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken)
  923. {
  924. var newKey = _keySelector(element);
  925. var cmp = _descending ? _comparer.Compare(_lastKey, newKey) : _comparer.Compare(newKey, _lastKey);
  926. if (cmp == 0)
  927. {
  928. return await _child.Compare(element, cacheLower, cancellationToken).ConfigureAwait(false);
  929. }
  930. if (cacheLower == cmp < 0)
  931. {
  932. _lastKey = newKey;
  933. await _child.SetElement(element, cancellationToken).ConfigureAwait(false);
  934. }
  935. return cmp;
  936. }
  937. internal override async ValueTask SetElement(TElement element, CancellationToken cancellationToken)
  938. {
  939. await base.SetElement(element, cancellationToken).ConfigureAwait(false);
  940. await _child.SetElement(element, cancellationToken).ConfigureAwait(false);
  941. }
  942. }
  943. internal class AsyncCachingComparerWithTask<TElement, TKey> : AsyncCachingComparer<TElement>
  944. {
  945. protected readonly Func<TElement, ValueTask<TKey>> _keySelector;
  946. protected readonly IComparer<TKey> _comparer;
  947. protected readonly bool _descending;
  948. protected TKey _lastKey;
  949. public AsyncCachingComparerWithTask(Func<TElement, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending)
  950. {
  951. _keySelector = keySelector;
  952. _comparer = comparer;
  953. _descending = descending;
  954. }
  955. internal override async ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken)
  956. {
  957. var newKey = await _keySelector(element).ConfigureAwait(false);
  958. var cmp = _descending ? _comparer.Compare(_lastKey, newKey) : _comparer.Compare(newKey, _lastKey);
  959. if (cacheLower == cmp < 0)
  960. {
  961. _lastKey = newKey;
  962. }
  963. return cmp;
  964. }
  965. internal override async ValueTask SetElement(TElement element, CancellationToken cancellationToken)
  966. {
  967. _lastKey = await _keySelector(element).ConfigureAwait(false);
  968. }
  969. }
  970. internal sealed class AsyncCachingComparerWithTaskAndChild<TElement, TKey> : AsyncCachingComparerWithTask<TElement, TKey>
  971. {
  972. private readonly AsyncCachingComparer<TElement> _child;
  973. public AsyncCachingComparerWithTaskAndChild(Func<TElement, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending, AsyncCachingComparer<TElement> child)
  974. : base(keySelector, comparer, descending)
  975. {
  976. _child = child;
  977. }
  978. internal override async ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken)
  979. {
  980. var newKey = await _keySelector(element).ConfigureAwait(false);
  981. var cmp = _descending ? _comparer.Compare(_lastKey, newKey) : _comparer.Compare(newKey, _lastKey);
  982. if (cmp == 0)
  983. {
  984. return await _child.Compare(element, cacheLower, cancellationToken).ConfigureAwait(false);
  985. }
  986. if (cacheLower == cmp < 0)
  987. {
  988. _lastKey = newKey;
  989. await _child.SetElement(element, cancellationToken).ConfigureAwait(false);
  990. }
  991. return cmp;
  992. }
  993. internal override async ValueTask SetElement(TElement element, CancellationToken cancellationToken)
  994. {
  995. await base.SetElement(element, cancellationToken).ConfigureAwait(false);
  996. await _child.SetElement(element, cancellationToken).ConfigureAwait(false);
  997. }
  998. }
  999. #if !NO_DEEP_CANCELLATION
  1000. internal class AsyncCachingComparerWithTaskAndCancellation<TElement, TKey> : AsyncCachingComparer<TElement>
  1001. {
  1002. protected readonly Func<TElement, CancellationToken, ValueTask<TKey>> _keySelector;
  1003. protected readonly IComparer<TKey> _comparer;
  1004. protected readonly bool _descending;
  1005. protected TKey _lastKey;
  1006. public AsyncCachingComparerWithTaskAndCancellation(Func<TElement, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending)
  1007. {
  1008. _keySelector = keySelector;
  1009. _comparer = comparer;
  1010. _descending = descending;
  1011. }
  1012. internal override async ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken)
  1013. {
  1014. var newKey = await _keySelector(element, cancellationToken).ConfigureAwait(false);
  1015. var cmp = _descending ? _comparer.Compare(_lastKey, newKey) : _comparer.Compare(newKey, _lastKey);
  1016. if (cacheLower == cmp < 0)
  1017. {
  1018. _lastKey = newKey;
  1019. }
  1020. return cmp;
  1021. }
  1022. internal override async ValueTask SetElement(TElement element, CancellationToken cancellationToken)
  1023. {
  1024. _lastKey = await _keySelector(element, cancellationToken).ConfigureAwait(false);
  1025. }
  1026. }
  1027. internal sealed class AsyncCachingComparerWithTaskAndCancellationAndChild<TElement, TKey> : AsyncCachingComparerWithTaskAndCancellation<TElement, TKey>
  1028. {
  1029. private readonly AsyncCachingComparer<TElement> _child;
  1030. public AsyncCachingComparerWithTaskAndCancellationAndChild(Func<TElement, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, bool descending, AsyncCachingComparer<TElement> child)
  1031. : base(keySelector, comparer, descending)
  1032. {
  1033. _child = child;
  1034. }
  1035. internal override async ValueTask<int> Compare(TElement element, bool cacheLower, CancellationToken cancellationToken)
  1036. {
  1037. var newKey = await _keySelector(element, cancellationToken).ConfigureAwait(false);
  1038. var cmp = _descending ? _comparer.Compare(_lastKey, newKey) : _comparer.Compare(newKey, _lastKey);
  1039. if (cmp == 0)
  1040. {
  1041. return await _child.Compare(element, cacheLower, cancellationToken).ConfigureAwait(false);
  1042. }
  1043. if (cacheLower == cmp < 0)
  1044. {
  1045. _lastKey = newKey;
  1046. await _child.SetElement(element, cancellationToken).ConfigureAwait(false);
  1047. }
  1048. return cmp;
  1049. }
  1050. internal override async ValueTask SetElement(TElement element, CancellationToken cancellationToken)
  1051. {
  1052. await base.SetElement(element, cancellationToken).ConfigureAwait(false);
  1053. await _child.SetElement(element, cancellationToken).ConfigureAwait(false);
  1054. }
  1055. }
  1056. #endif
  1057. }