MinMax.Generated.tt 22 KB

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