You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Feb 25, 2026. It is now read-only.
Repository navigation
This repository was archived by the owner on Feb 25, 2026. It is now read-only.
MemoryStream.ValidatePosition throws when Position == length #3536
If you read to the end of the MemoryStream, Position == length. If you then try to
call mstrm.Postion = mstrm.Position, it throws an ArgOutOfRangeException
varfoo=newbyte[10];varrom=newReadOnlyMemory<byte>(foo);using(varstream=rom.AsStream()){for(inti=0;i<foof.Length;i++){varb=newbyte[1];stream.Read(b,0,1);Console.WriteLine(stream.Position);}//Throws out of range exceptionstream.Position=stream.Position;}
In MemoryStream.cs, should probably be '>' rather than '>=' to be consistent with the behavior of other streams
Hello Kyaa,
Not sure what else I can provide. The issue I entered has code to reproduce the error and even where I think the problem might be.
So, unlike other streams, you are unable to set the Position of the Microsoft.Toolkit.HighPerformance.Streams.MemoryStream equal to its Length. You also are unable to seek to the end of the stream either. Both throw an out of range exception.
The snippet of code I provided demonstrates reading to the end of the stream so that stream.Position == stream.Length. But if you then try to set the stream’s position to the value it already has it throws. I believe it throws because the ValidatePosition(long position, int length) compares position to length with a >= when it should be strictly >. In other words, setting Postion equal to Length for a stream should not throw.
Hope this helps.
Hey @tombarry25, thanks for the detailed issue and repro, and for spotting the bug! 😄
You were absolutely correct, the stream shouldn't throw an exception when seeking to the end.
Added a fix and a new unit test including the repro you provided, along with further validation for other seeking APIs.
Activity
Kyaa-dost commentedon Oct 21, 2020
@tombarry25 Can you please provide detailed information and expected behavior? Screenshots/gifs are highly recommended. Thanks!
tombarry25 commentedon Oct 21, 2020
michael-hawker commentedon Oct 22, 2020
@Sergio0694 this one's for you! 🙂
Sergio0694 commentedon Oct 22, 2020
Hey @tombarry25, thanks for the detailed issue and repro, and for spotting the bug! 😄
You were absolutely correct, the stream shouldn't throw an exception when seeking to the end.
Added a fix and a new unit test including the repro you provided, along with further validation for other seeking APIs.
tombarry25 commentedon Oct 22, 2020
Fixed MemoryStream seek to end validation (#3543)
Fixed MemoryStream seek to end validation (#3543)