Skip to content

Commit

Permalink
Improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
JanKrivanek committed Oct 10, 2023
1 parent ca0013f commit e53346e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
/// This is not supposed to bring performance benefits, but it allows to avoid nondeterministic
/// GZipStream output for the identical input.
/// </summary>
public class GreedyBufferedStream : Stream
public class ChunkedBufferStream : Stream
{
private readonly Stream _stream;
private readonly byte[] _buffer;
private int _position;

public GreedyBufferedStream(Stream stream, int bufferSize)
public ChunkedBufferStream(Stream stream, int bufferSize)
{
_stream = stream;
_buffer = new byte[bufferSize];
Expand Down
2 changes: 1 addition & 1 deletion src/DotUtils.StreamUtils/CleanupScope.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace DotUtils.StreamUtils;

internal class CleanupScope : IDisposable
internal readonly struct CleanupScope : IDisposable
{
private readonly Action _disposeAction;

Expand Down
32 changes: 31 additions & 1 deletion src/DotUtils.StreamUtils/StreamExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Buffers;
using System.Diagnostics;

namespace DotUtils.StreamUtils;

Expand Down Expand Up @@ -29,6 +30,35 @@ public static int ReadAtLeast(this Stream stream, byte[] buffer, int offset, int
return totalRead;
}

public static int SkipBytes(this Stream stream, int bytesCount, bool throwOnEndOfStream)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
using var _ = new CleanupScope(() => ArrayPool<byte>.Shared.Return(buffer));
return SkipBytes(stream, bytesCount, throwOnEndOfStream, buffer);
}

public static int SkipBytes(this Stream stream, int bytesCount, bool throwOnEndOfStream, byte[] buffer)
{
int totalRead = 0;
while (totalRead < bytesCount)
{
int read = stream.Read(buffer, 0, Math.Min(bytesCount - totalRead, buffer.Length));
if (read == 0)
{
if (throwOnEndOfStream)
{
throw new InvalidDataException("Unexpected end of stream.");
}

return totalRead;
}

totalRead += read;
}

return totalRead;
}

public static Stream ToReadableSeekableStream(this Stream stream)
{
return TransparentReadStream.CreateSeekableStream(stream);
Expand Down

0 comments on commit e53346e

Please sign in to comment.