Skip to content

Commit

Permalink
Optimize Read to use Math.Min
Browse files Browse the repository at this point in the history
Math.Min can be optimized to a single instruction on some CPU
architectures and avoid a branch. This also makes the method smaller.
  • Loading branch information
brantburnett committed Jul 12, 2024
1 parent 08094ad commit b3c550b
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions Snappier/Internal/SnappyDecompressor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -613,24 +613,15 @@ private static void AppendFromSelf(ref byte op, ref byte buffer, ref byte buffer

public int Read(Span<byte> destination)
{
int unreadBytes = UnreadBytes;
if (unreadBytes == 0)
var bytesToRead = Math.Min(destination.Length, UnreadBytes);
if (bytesToRead <= 0)
{
return 0;
}

if (unreadBytes >= destination.Length)
{
_lookbackBuffer.Span.Slice(_readPosition, destination.Length).CopyTo(destination);
_readPosition += destination.Length;
return destination.Length;
}
else
{
_lookbackBuffer.Span.Slice(_readPosition, unreadBytes).CopyTo(destination);
_readPosition += unreadBytes;
return unreadBytes;
}
_lookbackBuffer.Span.Slice(_readPosition, bytesToRead).CopyTo(destination);
_readPosition += bytesToRead;
return bytesToRead;
}

/// <summary>
Expand Down

0 comments on commit b3c550b

Please sign in to comment.