Skip to content

Instantly share code, notes, and snippets.

@alexyakunin
Created July 31, 2019 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexyakunin/6adda499e6e7d448f724b5f4879a8dc6 to your computer and use it in GitHub Desktop.
Save alexyakunin/6adda499e6e7d448f724b5f4879a8dc6 to your computer and use it in GitHub Desktop.
public static long ComputeSum(string fileName,
Func<ReadOnlyMemory<byte>, long, int, (long, int)> sumComputer)
{
using var fs = new FileStream(fileName, FileMode.Open);
using var lease = MemoryPool<byte>.Shared.Rent(MinBufferSize);
var buffer = lease.Memory;
long sum = 0;
int n = 0;
while (true) {
var count = fs.Read(buffer.Span);
if (count == 0)
return sum + n;
(sum, n) = sumComputer(buffer.Slice(0, count), sum, n);
}
}
private static (long, int) ComputeSum(ReadOnlyMemory<byte> buffer, long sum, int n)
{
var span = buffer.Span;
foreach (var b in span) {
if (b < 128)
n = (n << 7) + b;
else {
sum += (n << 7) + b - 128;
n = 0;
}
}
return (sum, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment