Skip to content

Commit 25edf91

Browse files
authored
Merge pull request #6398 from wilzbach/fix-13880
Fix Issue 13880 - nothrow @nogc std.algorithm.reduce on fixed-size arrays
2 parents 0d45880 + ab70319 commit 25edf91

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

std/algorithm/iteration.d

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2793,7 +2793,13 @@ if (fun.length >= 1)
27932793

27942794
static if (isInputRange!R)
27952795
{
2796-
enforce(!r.empty, "Cannot reduce an empty input range w/o an explicit seed value.");
2796+
// no need to throw if range is statically known to be non-empty
2797+
static if (!__traits(compiles,
2798+
{
2799+
static assert(r.length > 0);
2800+
}))
2801+
enforce(!r.empty, "Cannot reduce an empty input range w/o an explicit seed value.");
2802+
27972803
Args result = r.front;
27982804
r.popFront();
27992805
return reduceImpl!false(r, result);
@@ -2882,8 +2888,15 @@ if (fun.length >= 1)
28822888
args[i] = f(args[i], e);
28832889
}
28842890
static if (mustInitialize)
2885-
if (!initialized)
2886-
throw new Exception("Cannot reduce an empty iterable w/o an explicit seed value.");
2891+
// no need to throw if range is statically known to be non-empty
2892+
static if (!__traits(compiles,
2893+
{
2894+
static assert(r.length > 0);
2895+
}))
2896+
{
2897+
if (!initialized)
2898+
throw new Exception("Cannot reduce an empty iterable w/o an explicit seed value.");
2899+
}
28872900

28882901
static if (Args.length == 1)
28892902
return args[0];
@@ -3165,6 +3178,19 @@ The number of seeds must be correspondingly increased.
31653178
assert(data.length == 0);
31663179
}
31673180

3181+
// https://issues.dlang.org/show_bug.cgi?id=13880
3182+
// reduce shouldn't throw if the length is statically known
3183+
pure nothrow @safe @nogc unittest
3184+
{
3185+
import std.algorithm.comparison : min;
3186+
int[5] arr;
3187+
arr[2] = -1;
3188+
assert(arr.reduce!min == -1);
3189+
3190+
int[0] arr0;
3191+
assert(reduce!min(42, arr0) == 42);
3192+
}
3193+
31683194
//Helper for Reduce
31693195
private template ReduceSeedType(E)
31703196
{

0 commit comments

Comments
 (0)