-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
introduce Stream.ReadExactly extension methods
fixes Frame.FromStream messing up when stream read less than requested
- Loading branch information
1 parent
c43cc39
commit f13d43f
Showing
2 changed files
with
36 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
|
||
using System.IO; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace SwebSocket; | ||
|
||
internal static class StreamHelper | ||
{ | ||
public static async Task ReadExactly(this Stream stream, byte[] buffer, CancellationToken token) | ||
{ | ||
if (buffer.Length == 0) return; | ||
|
||
int alreadyRead = 0; | ||
int toBeRead = buffer.Length; | ||
|
||
while (alreadyRead != toBeRead) | ||
{ | ||
var actuallyRead = await stream.ReadAsync(buffer, alreadyRead, toBeRead - alreadyRead, token); | ||
if (actuallyRead == 0) throw new EndOfStreamException(); | ||
alreadyRead += actuallyRead; | ||
} | ||
} | ||
|
||
public static async Task<byte[]> ReadExactly(this Stream stream, int bytes, CancellationToken token) | ||
{ | ||
var buffer = new byte[bytes]; | ||
await ReadExactly(stream, buffer, token); | ||
|
||
return buffer; | ||
} | ||
} |