Background and motivation
The Adler32 checksum algorithm is used in many popular compression formats, like the ZLib envelope format around DEFLATE data. It is faster than CRC32, albeit less reliable on shorter messages. The algorithm is specified in RFC1950
API Proposal
namespace System.IO.Hashing;
public sealed partial class Adler32 : System.IO.Hashing.NonCryptographicHashAlgorithm
{
public Adler32();
public override void Append(System.ReadOnlySpan<byte> source);
public Adler32 Clone();
public uint GetCurrentHashAsUInt32();
protected override void GetCurrentHashCore(System.Span<byte> destination);
protected override void GetHashAndResetCore(System.Span<byte> destination);
public static byte[] Hash(byte[] source);
public static byte[] Hash(System.ReadOnlySpan<byte> source);
public static int Hash(System.ReadOnlySpan<byte> source, System.Span<byte> destination);
public static uint HashToUInt32(System.ReadOnlySpan<byte> source);
public override void Reset();
public static bool TryHash(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesWritten);
}
API Usage
sealed class MyZlibStream : Stream
{
private Stream innerStream;
private Adler32 rollingHash = new();
private DeflateStream compressor = new DeflateStream(innerStream);
public MyZlibStream(Stream innerStream)
{
this.innerStream = innerStream;
compressor = new DeflateStream(innerStream);
// Write ZLib header.
}
public override void Write (byte[] buffer, int offset, int count)
{
compressor.Write(buffer, offset, count);
rollingHash.Append(buffer.AsSpan().Slice(offset, count));
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _stream != null)
{
try
{
Flush();
innerStream.Write(rollingHash.GetCurrentHash());
}
finally
{
_stream.Dispose();
}
}
}
finally
{
_stream = null;
_buffer = null;
_writePos = 0; // WriteByte hot path relies on this
// Call base.Dispose(bool) to cleanup async IO resources
base.Dispose(disposing);
}
}
}
Alternative Designs
No response
Risks
No response
Background and motivation
The Adler32 checksum algorithm is used in many popular compression formats, like the ZLib envelope format around DEFLATE data. It is faster than CRC32, albeit less reliable on shorter messages. The algorithm is specified in RFC1950
API Proposal
API Usage
Alternative Designs
No response
Risks
No response