From c2c1b3acb41184f368d59d93d8a14dd6d95efc95 Mon Sep 17 00:00:00 2001 From: DomCR Date: Thu, 7 Dec 2023 10:11:35 +0100 Subject: [PATCH] async ops --- CSUtilities/IO/StreamIO.cs | 56 +++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/CSUtilities/IO/StreamIO.cs b/CSUtilities/IO/StreamIO.cs index fabead3..a62c642 100644 --- a/CSUtilities/IO/StreamIO.cs +++ b/CSUtilities/IO/StreamIO.cs @@ -2,6 +2,8 @@ using System; using System.IO; using System.Text; +using System.Threading; +using System.Threading.Tasks; namespace CSUtilities.IO { @@ -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; } @@ -121,6 +127,26 @@ public byte[] GetBytes(int offset, int length) return buffer; } + public async Task 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; + } + /// /// Look into a byte without moving the position of the stream. /// @@ -156,6 +182,15 @@ public virtual byte ReadByte() return b; } + public virtual async Task 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; + } + /// /// Read a character from the stream /// @@ -186,6 +221,19 @@ public virtual byte[] ReadBytes(int length) return buffer; } + public virtual async Task 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; + } + /// /// Read the stream as a string until it finds the match character ///