MinMax.Generated.tt 20 KB

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