-
-
Save alexyakunin/6adda499e6e7d448f724b5f4879a8dc6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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