MinMax.Generated.tt 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <#@ template debug="false" hostspecific="false" language="C#" #>
  2. <#@ assembly name="System.Core" #>
  3. <#@ import namespace="System.Linq" #>
  4. <#@ import namespace="System.Text" #>
  5. <#@ import namespace="System.Collections.Generic" #>
  6. <#@ output extension=".cs" #>
  7. // Licensed to the .NET Foundation under one or more agreements.
  8. // The .NET Foundation licenses this file to you under the MIT license.
  9. // See the LICENSE file in the project root for more information.
  10. using System.Collections.Generic;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace System.Linq
  14. {
  15. public static partial class AsyncEnumerable
  16. {
  17. <#
  18. foreach (var m in new[] { "Max", "Min" })
  19. {
  20. var comparison = m == "Max" ? ">" : "<";
  21. var extremum = m == "Max" ? "maximum" : "minimum";
  22. foreach (var t in new[] { "int", "int?", "long", "long?", "float", "float?", "double", "double?", "decimal", "decimal?" })
  23. {
  24. var isFloatingPoint = t.StartsWith("float") || t.StartsWith("double");
  25. var isInteger = t.StartsWith("int") || t.StartsWith("long");
  26. var isNullable = t.EndsWith("?");
  27. var shortCircuit = t.StartsWith("decimal");
  28. var typeStr = t;
  29. if (isNullable) {
  30. typeStr = "Nullable{" + t.Substring(0, 1).ToUpper() + t.Substring(1, t.Length - 2) + "}";
  31. }
  32. #>
  33. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  34. /// <summary>
  35. /// Returns the <#=extremum#> value in an async-enumerable sequence of <see cref="<#=typeStr#>" /> values.
  36. /// </summary>
  37. /// <param name="source">A sequence of <see cref="<#=typeStr#>" /> values to determine the <#=extremum#> value of.</param>
  38. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  39. /// <returns>A ValueTask containing a single element with the <#=extremum#> value in the source sequence.</returns>
  40. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  41. public static ValueTask<<#=t#>> <#=m#>Async(this IAsyncEnumerable<<#=t#>> source, CancellationToken cancellationToken = default)
  42. {
  43. if (source == null)
  44. throw Error.ArgumentNull(nameof(source));
  45. return Core(source, cancellationToken);
  46. static async ValueTask<<#=t#>> Core(IAsyncEnumerable<<#=t#>> source, CancellationToken cancellationToken)
  47. {
  48. <#
  49. if (!isNullable)
  50. {
  51. #>
  52. <#=t#> value;
  53. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  54. {
  55. if (!await e.MoveNextAsync())
  56. {
  57. throw Error.NoElements();
  58. }
  59. value = e.Current;
  60. <#
  61. if (isFloatingPoint && m == "Max")
  62. {
  63. #>
  64. // NaN is ordered less than all other values. We need to do explicit checks
  65. // to ensure this, but once we've found a value that is not NaN we need no
  66. // longer worry about it, so first loop until such a value is found (or not,
  67. // as the case may be).
  68. while (<#=t#>.IsNaN(value))
  69. {
  70. if (!await e.MoveNextAsync())
  71. {
  72. return value;
  73. }
  74. value = e.Current;
  75. }
  76. <#
  77. }
  78. #>
  79. while (await e.MoveNextAsync())
  80. {
  81. var x = e.Current;
  82. if (x <#=comparison#> value)
  83. {
  84. value = x;
  85. }
  86. <#
  87. if (isFloatingPoint && m == "Min")
  88. {
  89. #>
  90. else
  91. {
  92. // Normally NaN < anything is false, as is anything < NaN
  93. // However, this leads to some irksome outcomes in Min and Max.
  94. // If we use those semantics then Min(NaN, 5.0) is NaN, but
  95. // Min(5.0, NaN) is 5.0! To fix this, we impose a total
  96. // ordering where NaN is smaller than every value, including
  97. // negative infinity.
  98. // Not testing for NaN therefore isn't an option, but since we
  99. // can't find a smaller value, we can short-circuit.
  100. if (<#=t#>.IsNaN(x))
  101. {
  102. return x;
  103. }
  104. }
  105. <#
  106. }
  107. #>
  108. }
  109. }
  110. return value;
  111. <#
  112. }
  113. else
  114. {
  115. #>
  116. <#=t#> value = null;
  117. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  118. {
  119. // Start off knowing that we've a non-null value (or exit here, knowing we don't)
  120. // so we don't have to keep testing for nullity.
  121. do
  122. {
  123. if (!await e.MoveNextAsync())
  124. {
  125. return value;
  126. }
  127. value = e.Current;
  128. }
  129. while (!value.HasValue);
  130. // Keep hold of the wrapped value, and do comparisons on that, rather than
  131. // using the lifted operation each time.
  132. var valueVal = value.GetValueOrDefault();
  133. <#
  134. if (isInteger && m == "Max")
  135. {
  136. #>
  137. if (valueVal >= 0)
  138. {
  139. // We can fast-path this case where we know HasValue will
  140. // never affect the outcome, without constantly checking
  141. // if we're in such a state. Similar fast-paths could
  142. // be done for other cases, but as all-positive or mostly-
  143. // positive integer values are quite common in real-world
  144. // uses, it's only been done for int? and long?.
  145. while (await e.MoveNextAsync())
  146. {
  147. var cur = e.Current;
  148. var x = cur.GetValueOrDefault();
  149. if (x <#=comparison#> valueVal)
  150. {
  151. valueVal = x;
  152. value = cur;
  153. }
  154. }
  155. }
  156. else
  157. {
  158. while (await e.MoveNextAsync())
  159. {
  160. var cur = e.Current;
  161. var x = cur.GetValueOrDefault();
  162. // Do not replace & with &&. The branch prediction cost outweighs the extra operation
  163. // unless nulls either never happen or always happen.
  164. if (cur.HasValue & x <#=comparison#> valueVal)
  165. {
  166. valueVal = x;
  167. value = cur;
  168. }
  169. }
  170. }
  171. <#
  172. }
  173. else if (isFloatingPoint && m == "Min")
  174. {
  175. #>
  176. while (await e.MoveNextAsync())
  177. {
  178. var cur = e.Current;
  179. if (cur.HasValue)
  180. {
  181. var x = cur.GetValueOrDefault();
  182. if (x <#=comparison#> valueVal)
  183. {
  184. valueVal = x;
  185. value = cur;
  186. }
  187. else
  188. {
  189. // Normally NaN < anything is false, as is anything < NaN
  190. // However, this leads to some irksome outcomes in Min and Max.
  191. // If we use those semantics then Min(NaN, 5.0) is NaN, but
  192. // Min(5.0, NaN) is 5.0! To fix this, we impose a total
  193. // ordering where NaN is smaller than every value, including
  194. // negative infinity.
  195. // Not testing for NaN therefore isn't an option, but since we
  196. // can't find a smaller value, we can short-circuit.
  197. if (<#=t.TrimEnd('?')#>.IsNaN(x))
  198. {
  199. return cur;
  200. }
  201. }
  202. }
  203. }
  204. <#
  205. }
  206. else
  207. {
  208. if (isFloatingPoint && m == "Max")
  209. {
  210. #>
  211. // NaN is ordered less than all other values. We need to do explicit checks
  212. // to ensure this, but once we've found a value that is not NaN we need no
  213. // longer worry about it, so first loop until such a value is found (or not,
  214. // as the case may be).
  215. while (<#=t.TrimEnd('?')#>.IsNaN(valueVal))
  216. {
  217. if (!await e.MoveNextAsync())
  218. {
  219. return value;
  220. }
  221. var cur = e.Current;
  222. if (cur.HasValue)
  223. {
  224. valueVal = (value = cur).GetValueOrDefault();
  225. }
  226. }
  227. <#
  228. }
  229. #>
  230. while (await e.MoveNextAsync())
  231. {
  232. var cur = e.Current;
  233. var x = cur.GetValueOrDefault();
  234. <#
  235. if (shortCircuit)
  236. {
  237. #>
  238. if (cur.HasValue && x <#=comparison#> valueVal)
  239. <#
  240. }
  241. else
  242. {
  243. #>
  244. // Do not replace & with &&. The branch prediction cost outweighs the extra operation
  245. // unless nulls either never happen or always happen.
  246. if (cur.HasValue & x <#=comparison#> valueVal)
  247. <#
  248. }
  249. #>
  250. {
  251. valueVal = x;
  252. value = cur;
  253. }
  254. }
  255. <#
  256. }
  257. #>
  258. }
  259. return value;
  260. <#
  261. }
  262. #>
  263. }
  264. }
  265. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  266. <#
  267. foreach (var overload in new[] {
  268. new { selector = "Func<TSource, " + t + ">", invoke = "selector(e.Current)" },
  269. new { selector = "Func<TSource, ValueTask<" + t + ">>", invoke = "await selector(e.Current).ConfigureAwait(false)" },
  270. new { selector = "Func<TSource, CancellationToken, ValueTask<" + t + ">>", invoke = "await selector(e.Current, cancellationToken).ConfigureAwait(false)" },
  271. })
  272. {
  273. var isAsync = overload.invoke.StartsWith("await");
  274. var isDeepCancellation = overload.selector.Contains("CancellationToken");
  275. var suffix = isAsync ? "Await" : "";
  276. var visibility = isAsync ? "private" : "public";
  277. var core = isAsync ? "Core" : "";
  278. if (isDeepCancellation)
  279. {
  280. suffix += "WithCancellation";
  281. #>
  282. #if !NO_DEEP_CANCELLATION
  283. [GenerateAsyncOverload]
  284. <#
  285. } else if (isAsync)
  286. {
  287. #>
  288. /// <summary>
  289. /// Invokes and awaits a transform function on each element of a sequence and returns the maximum <see cref="<#=typeStr#>"/> value.
  290. /// </summary>
  291. /// <typeparam name="TSource">Type of elements in the source sequence.</typeparam>
  292. /// <param name="source">The source sequence.</param>
  293. /// <param name="selector">An asynchronous transform function to invoke and await on each element of the source.</param>
  294. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  295. /// <returns>A ValueTask containing the maximum value in the sequence.</returns>
  296. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="selector"/> is <see langword="null"/>.</exception>
  297. [GenerateAsyncOverload]
  298. <#
  299. }
  300. if (isDeepCancellation || isAsync)
  301. {
  302. #>
  303. [Obsolete("Use <#=m#>ByAsync. IAsyncEnumerable LINQ is now in System.Linq.AsyncEnumerable, and the functionality previously provided by <#=m#><#=suffix#>Async now exists as an overload of <#=m#>ByAsync.")]
  304. <#
  305. } else {
  306. #>
  307. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  308. <#
  309. }
  310. #>
  311. <#=visibility#> static ValueTask<<#=t#>> <#=m#><#=suffix#>Async<#=core#><TSource>(this IAsyncEnumerable<TSource> source, <#=overload.selector#> selector, CancellationToken cancellationToken = default)
  312. {
  313. if (source == null)
  314. throw Error.ArgumentNull(nameof(source));
  315. if (selector == null)
  316. throw Error.ArgumentNull(nameof(selector));
  317. return Core(source, selector, cancellationToken);
  318. static async ValueTask<<#=t#>> Core(IAsyncEnumerable<TSource> source, <#=overload.selector#> selector, CancellationToken cancellationToken)
  319. {
  320. <#
  321. if (!isNullable)
  322. {
  323. #>
  324. <#=t#> value;
  325. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  326. {
  327. if (!await e.MoveNextAsync())
  328. {
  329. throw Error.NoElements();
  330. }
  331. value = <#=overload.invoke#>;
  332. <#
  333. if (isFloatingPoint && m == "Max")
  334. {
  335. #>
  336. // NaN is ordered less than all other values. We need to do explicit checks
  337. // to ensure this, but once we've found a value that is not NaN we need no
  338. // longer worry about it, so first loop until such a value is found (or not,
  339. // as the case may be).
  340. while (<#=t#>.IsNaN(value))
  341. {
  342. if (!await e.MoveNextAsync())
  343. {
  344. return value;
  345. }
  346. value = <#=overload.invoke#>;
  347. }
  348. <#
  349. }
  350. #>
  351. while (await e.MoveNextAsync())
  352. {
  353. var x = <#=overload.invoke#>;
  354. if (x <#=comparison#> value)
  355. {
  356. value = x;
  357. }
  358. <#
  359. if (isFloatingPoint && m == "Min")
  360. {
  361. #>
  362. else
  363. {
  364. // Normally NaN < anything is false, as is anything < NaN
  365. // However, this leads to some irksome outcomes in Min and Max.
  366. // If we use those semantics then Min(NaN, 5.0) is NaN, but
  367. // Min(5.0, NaN) is 5.0! To fix this, we impose a total
  368. // ordering where NaN is smaller than every value, including
  369. // negative infinity.
  370. // Not testing for NaN therefore isn't an option, but since we
  371. // can't find a smaller value, we can short-circuit.
  372. if (<#=t#>.IsNaN(x))
  373. {
  374. return x;
  375. }
  376. }
  377. <#
  378. }
  379. #>
  380. }
  381. }
  382. return value;
  383. <#
  384. }
  385. else
  386. {
  387. #>
  388. <#=t#> value = null;
  389. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  390. {
  391. // Start off knowing that we've a non-null value (or exit here, knowing we don't)
  392. // so we don't have to keep testing for nullity.
  393. do
  394. {
  395. if (!await e.MoveNextAsync())
  396. {
  397. return value;
  398. }
  399. value = <#=overload.invoke#>;
  400. }
  401. while (!value.HasValue);
  402. // Keep hold of the wrapped value, and do comparisons on that, rather than
  403. // using the lifted operation each time.
  404. var valueVal = value.GetValueOrDefault();
  405. <#
  406. if (isInteger && m == "Max")
  407. {
  408. #>
  409. if (valueVal >= 0)
  410. {
  411. // We can fast-path this case where we know HasValue will
  412. // never affect the outcome, without constantly checking
  413. // if we're in such a state. Similar fast-paths could
  414. // be done for other cases, but as all-positive or mostly-
  415. // positive integer values are quite common in real-world
  416. // uses, it's only been done for int? and long?.
  417. while (await e.MoveNextAsync())
  418. {
  419. var cur = <#=overload.invoke#>;
  420. var x = cur.GetValueOrDefault();
  421. if (x <#=comparison#> valueVal)
  422. {
  423. valueVal = x;
  424. value = cur;
  425. }
  426. }
  427. }
  428. else
  429. {
  430. while (await e.MoveNextAsync())
  431. {
  432. var cur = <#=overload.invoke#>;
  433. var x = cur.GetValueOrDefault();
  434. // Do not replace & with &&. The branch prediction cost outweighs the extra operation
  435. // unless nulls either never happen or always happen.
  436. if (cur.HasValue & x <#=comparison#> valueVal)
  437. {
  438. valueVal = x;
  439. value = cur;
  440. }
  441. }
  442. }
  443. <#
  444. }
  445. else if (isFloatingPoint && m == "Min")
  446. {
  447. #>
  448. while (await e.MoveNextAsync())
  449. {
  450. var cur = <#=overload.invoke#>;
  451. if (cur.HasValue)
  452. {
  453. var x = cur.GetValueOrDefault();
  454. if (x <#=comparison#> valueVal)
  455. {
  456. valueVal = x;
  457. value = cur;
  458. }
  459. else
  460. {
  461. // Normally NaN < anything is false, as is anything < NaN
  462. // However, this leads to some irksome outcomes in Min and Max.
  463. // If we use those semantics then Min(NaN, 5.0) is NaN, but
  464. // Min(5.0, NaN) is 5.0! To fix this, we impose a total
  465. // ordering where NaN is smaller than every value, including
  466. // negative infinity.
  467. // Not testing for NaN therefore isn't an option, but since we
  468. // can't find a smaller value, we can short-circuit.
  469. if (<#=t.TrimEnd('?')#>.IsNaN(x))
  470. {
  471. return cur;
  472. }
  473. }
  474. }
  475. }
  476. <#
  477. }
  478. else
  479. {
  480. if (isFloatingPoint && m == "Max")
  481. {
  482. #>
  483. // NaN is ordered less than all other values. We need to do explicit checks
  484. // to ensure this, but once we've found a value that is not NaN we need no
  485. // longer worry about it, so first loop until such a value is found (or not,
  486. // as the case may be).
  487. while (<#=t.TrimEnd('?')#>.IsNaN(valueVal))
  488. {
  489. if (!await e.MoveNextAsync())
  490. {
  491. return value;
  492. }
  493. var cur = <#=overload.invoke#>;
  494. if (cur.HasValue)
  495. {
  496. valueVal = (value = cur).GetValueOrDefault();
  497. }
  498. }
  499. <#
  500. }
  501. #>
  502. while (await e.MoveNextAsync())
  503. {
  504. var cur = <#=overload.invoke#>;
  505. var x = cur.GetValueOrDefault();
  506. <#
  507. if (shortCircuit)
  508. {
  509. #>
  510. if (cur.HasValue && x <#=comparison#> valueVal)
  511. <#
  512. }
  513. else
  514. {
  515. #>
  516. // Do not replace & with &&. The branch prediction cost outweighs the extra operation
  517. // unless nulls either never happen or always happen.
  518. if (cur.HasValue & x <#=comparison#> valueVal)
  519. <#
  520. }
  521. #>
  522. {
  523. valueVal = x;
  524. value = cur;
  525. }
  526. }
  527. <#
  528. }
  529. #>
  530. }
  531. return value;
  532. <#
  533. }
  534. #>
  535. }
  536. }
  537. <#
  538. if (isDeepCancellation)
  539. {
  540. #>
  541. #endif
  542. <#
  543. }
  544. if (!(isDeepCancellation || isAsync))
  545. {
  546. #>
  547. #endif
  548. <#
  549. }
  550. }
  551. #>
  552. <#
  553. }
  554. }
  555. #>
  556. }
  557. }