Skip to content

Commit

Permalink
Merge pull request #6 from DomCR/StreamIO-async
Browse files Browse the repository at this point in the history
Stream io async
  • Loading branch information
DomCR authored Feb 19, 2024
2 parents 9ba1dc2 + 3cf1b56 commit 833d0fa
Showing 1 changed file with 52 additions and 4 deletions.
56 changes: 52 additions & 4 deletions CSUtilities/IO/StreamIO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CSUtilities.IO
{
Expand Down Expand Up @@ -67,13 +69,17 @@ public StreamIO(Stream stream, bool createCopy, bool resetPosition)
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
_stream = (Stream)new MemoryStream(buffer);

if (resetPosition)
//Reset the position to the begining
_stream.Position = 0L;
}
else
{
this._stream = stream;
}

if (resetPosition)
{
//Reset the position to the begining
_stream.Position = 0L;
}

stream.Position = position;
}
Expand Down Expand Up @@ -121,6 +127,26 @@ public byte[] GetBytes(int offset, int length)
return buffer;
}

public async Task<byte[]> GetBytesAsync(int offset, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException("Length cannot be negative.");

//Save the current position
long save = this.Position;
//Set the position to the begining
this.Position = offset;

byte[] buffer = await this.ReadBytesAsync(length);
//if (this.m_stream.Read(buffer, offset, length) < length)
// throw new EndOfStreamException();

//Reset the position
this.Position = save;

return buffer;
}

/// <summary>
/// Look into a byte without moving the position of the stream.
/// </summary>
Expand Down Expand Up @@ -156,6 +182,15 @@ public virtual byte ReadByte()
return b;
}

public virtual async Task<byte> ReadByteAsync(CancellationToken cancellationToken = default)
{
byte[] arr = new byte[1];
byte b = await _stream.ReadAsync(arr, 0, 1, cancellationToken) == 1 ?
arr[0] : throw new EndOfStreamException();

return b;
}

/// <summary>
/// Read a character from the stream
/// </summary>
Expand Down Expand Up @@ -186,6 +221,19 @@ public virtual byte[] ReadBytes(int length)
return buffer;
}

public virtual async Task<byte[]> ReadBytesAsync(int length, CancellationToken cancellationToken = default)
{
if (length < 0)
throw new ArgumentOutOfRangeException("Length cannot be negative.");

byte[] buffer = new byte[length];

if (await this._stream.ReadAsync(buffer, 0, length, cancellationToken) < length)
throw new EndOfStreamException();

return buffer;
}

/// <summary>
/// Read the stream as a string until it finds the match character
/// </summary>
Expand Down

0 comments on commit 833d0fa

Please sign in to comment.