-
Notifications
You must be signed in to change notification settings - Fork 101
/
Sum.cs
290 lines (230 loc) · 12.4 KB
/
Sum.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Linq
{
public static partial class Enumerable
{
public static int Sum(this IEnumerable<int> source) => Sum<int, int>(source);
public static long Sum(this IEnumerable<long> source) => Sum<long, long>(source);
public static float Sum(this IEnumerable<float> source) => (float)Sum<float, double>(source);
public static double Sum(this IEnumerable<double> source) => Sum<double, double>(source);
public static decimal Sum(this IEnumerable<decimal> source) => Sum<decimal, decimal>(source);
private static TResult Sum<TSource, TResult>(this IEnumerable<TSource> source)
where TSource : struct, INumber<TSource>
where TResult : struct, INumber<TResult>
{
if (source.TryGetSpan(out ReadOnlySpan<TSource> span))
{
return Sum<TSource, TResult>(span);
}
TResult sum = TResult.Zero;
foreach (TSource value in source)
{
checked { sum += TResult.CreateChecked(value); }
}
return sum;
}
private static TResult Sum<T, TResult>(ReadOnlySpan<T> span)
where T : struct, INumber<T>
where TResult : struct, INumber<TResult>
{
if (typeof(T) == typeof(TResult)
&& Vector<T>.IsSupported
&& Vector.IsHardwareAccelerated
&& Vector<T>.Count > 2
&& span.Length >= Vector<T>.Count * 4)
{
// For cases where the vector may only contain two elements vectorization doesn't add any benefit
// due to the expense of overflow checking. This means that architectures where Vector<T> is 128 bit,
// such as ARM or Intel without AVX, will only vectorize spans of ints and not longs.
if (typeof(T) == typeof(long))
{
return (TResult) (object) SumSignedIntegersVectorized(MemoryMarshal.Cast<T, long>(span));
}
if (typeof(T) == typeof(int))
{
return (TResult) (object) SumSignedIntegersVectorized(MemoryMarshal.Cast<T, int>(span));
}
}
TResult sum = TResult.Zero;
foreach (T value in span)
{
checked { sum += TResult.CreateChecked(value); }
}
return sum;
}
private static T SumSignedIntegersVectorized<T>(ReadOnlySpan<T> span)
where T : struct, IBinaryInteger<T>, ISignedNumber<T>, IMinMaxValue<T>
{
Debug.Assert(span.Length >= Vector<T>.Count * 4);
Debug.Assert(Vector<T>.Count > 2);
Debug.Assert(Vector.IsHardwareAccelerated);
ref T ptr = ref MemoryMarshal.GetReference(span);
nuint length = (nuint)span.Length;
// Overflow testing for vectors is based on setting the sign bit of the overflowTracking
// vector for an element if the following are all true:
// - The two elements being summed have the same sign bit. If one element is positive
// and the other is negative then an overflow is not possible.
// - The sign bit of the sum is not the same as the sign bit of the previous accumulator.
// This indicates that the new sum wrapped around to the opposite sign.
//
// This is done by:
// overflowTracking |= (result ^ input1) & (result ^ input2);
//
// The general premise here is that we're doing signof(result) ^ signof(input1). This will produce
// a sign-bit of 1 if they differ and 0 if they are the same. We do the same with
// signof(result) ^ signof(input2), then combine both results together with a logical &.
//
// Thus, if we had a sign swap compared to both inputs, then signof(input1) == signof(input2) and
// we must have overflowed.
//
// By bitwise or-ing the overflowTracking vector for each step we can save cycles by testing
// the sign bits less often. If any iteration has the sign bit set in any element it indicates
// there was an overflow.
//
// Note: The overflow checking in this algorithm is only correct for signed integers.
// If support is ever added for unsigned integers then the overflow check should be:
// overflowTracking |= (input1 & input2) | Vector.AndNot(input1 | input2, result);
Vector<T> accumulator = Vector<T>.Zero;
// Build a test vector with only the sign bit set in each element.
Vector<T> overflowTestVector = new(T.MinValue);
// Unroll the loop to sum 4 vectors per iteration. This reduces range check
// and overflow check frequency, allows us to eliminate move operations swapping
// accumulators, and may have pipelining benefits.
nuint index = 0;
nuint limit = length - (nuint)Vector<T>.Count * 4;
do
{
// Switch accumulators with each step to avoid an additional move operation
Vector<T> data = Vector.LoadUnsafe(ref ptr, index);
Vector<T> accumulator2 = accumulator + data;
Vector<T> overflowTracking = (accumulator2 ^ accumulator) & (accumulator2 ^ data);
data = Vector.LoadUnsafe(ref ptr, index + (nuint)Vector<T>.Count);
accumulator = accumulator2 + data;
overflowTracking |= (accumulator ^ accumulator2) & (accumulator ^ data);
data = Vector.LoadUnsafe(ref ptr, index + (nuint)Vector<T>.Count * 2);
accumulator2 = accumulator + data;
overflowTracking |= (accumulator2 ^ accumulator) & (accumulator2 ^ data);
data = Vector.LoadUnsafe(ref ptr, index + (nuint)Vector<T>.Count * 3);
accumulator = accumulator2 + data;
overflowTracking |= (accumulator ^ accumulator2) & (accumulator ^ data);
if ((overflowTracking & overflowTestVector) != Vector<T>.Zero)
{
ThrowHelper.ThrowOverflowException();
}
index += (nuint)Vector<T>.Count * 4;
} while (index < limit);
// Process remaining vectors, if any, without unrolling
limit = length - (nuint)Vector<T>.Count;
if (index < limit)
{
Vector<T> overflowTracking = Vector<T>.Zero;
do
{
Vector<T> data = Vector.LoadUnsafe(ref ptr, index);
Vector<T> accumulator2 = accumulator + data;
overflowTracking |= (accumulator2 ^ accumulator) & (accumulator2 ^ data);
accumulator = accumulator2;
index += (nuint)Vector<T>.Count;
} while (index < limit);
if ((overflowTracking & overflowTestVector) != Vector<T>.Zero)
{
ThrowHelper.ThrowOverflowException();
}
}
// Add the elements in the vector horizontally.
// Vector.Sum doesn't perform overflow checking, instead add elements individually.
T result = T.Zero;
for (int i = 0; i < Vector<T>.Count; i++)
{
checked { result += accumulator[i]; }
}
// Add any remaining elements
while (index < length)
{
checked { result += Unsafe.Add(ref ptr, index); }
index++;
}
return result;
}
public static int? Sum(this IEnumerable<int?> source) => Sum<int, int>(source);
public static long? Sum(this IEnumerable<long?> source) => Sum<long, long>(source);
public static float? Sum(this IEnumerable<float?> source) => Sum<float, double>(source);
public static double? Sum(this IEnumerable<double?> source) => Sum<double, double>(source);
public static decimal? Sum(this IEnumerable<decimal?> source) => Sum<decimal, decimal>(source);
private static TSource? Sum<TSource, TAccumulator>(this IEnumerable<TSource?> source)
where TSource : struct, INumber<TSource>
where TAccumulator : struct, INumber<TAccumulator>
{
if (source is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
TAccumulator sum = TAccumulator.Zero;
foreach (TSource? value in source)
{
if (value is not null)
{
checked { sum += TAccumulator.CreateChecked(value.GetValueOrDefault()); }
}
}
return TSource.CreateTruncating(sum);
}
public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => Sum<TSource, int, int>(source, selector);
public static long Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => Sum<TSource, long, long>(source, selector);
public static float Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => Sum<TSource, float, double>(source, selector);
public static double Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => Sum<TSource, double, double>(source, selector);
public static decimal Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => Sum<TSource, decimal, decimal>(source, selector);
private static TResult Sum<TSource, TResult, TAccumulator>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
where TResult : struct, INumber<TResult>
where TAccumulator : struct, INumber<TAccumulator>
{
if (source is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (selector is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.selector);
}
TAccumulator sum = TAccumulator.Zero;
foreach (TSource value in source)
{
checked { sum += TAccumulator.CreateChecked(selector(value)); }
}
return TResult.CreateTruncating(sum);
}
public static int? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => Sum<TSource, int, int>(source, selector);
public static long? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => Sum<TSource, long, long>(source, selector);
public static float? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => Sum<TSource, float, double>(source, selector);
public static double? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => Sum<TSource, double, double>(source, selector);
public static decimal? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => Sum<TSource, decimal, decimal>(source, selector);
private static TResult? Sum<TSource, TResult, TAccumulator>(this IEnumerable<TSource> source, Func<TSource, TResult?> selector)
where TResult : struct, INumber<TResult>
where TAccumulator : struct, INumber<TAccumulator>
{
if (source is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (selector is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.selector);
}
TAccumulator sum = TAccumulator.Zero;
foreach (TSource item in source)
{
if (selector(item) is TResult selectedValue)
{
checked { sum += TAccumulator.CreateChecked(selectedValue); }
}
}
return TResult.CreateTruncating(sum);
}
}
}