Skip to content

Commit

Permalink
Merge pull request #19313 from CyrusNajmabadi/poolSha1Instances
Browse files Browse the repository at this point in the history
Pool byte array used for reading from Stream during checksum calculation
  • Loading branch information
CyrusNajmabadi authored May 8, 2017
2 parents 046597c + 05d8ee3 commit 956b17e
Showing 1 changed file with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,33 @@ internal partial class Checksum
{
public static Checksum Create(Stream stream)
{
// REVIEW: should we cache SHA1CryptoServiceProvider
using (var algorithm = SHA1.Create())
using (var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1))
{
return ComputeChecksum(stream, hash);
}
}

private static Checksum ComputeChecksum(Stream stream, IncrementalHash hash)
{
using (var pooledBuffer = SharedPools.ByteArray.GetPooledObject())
{
stream.Seek(0, SeekOrigin.Begin);
return new Checksum(algorithm.ComputeHash(stream));

var buffer = pooledBuffer.Object;
var bufferLength = buffer.Length;
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, bufferLength);
if (bytesRead > 0)
{
hash.AppendData(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);

var bytes = hash.GetHashAndReset();
return new Checksum(bytes);
}
}

Expand Down

0 comments on commit 956b17e

Please sign in to comment.