Bug 34169 - BinaryStream.PeekChar is not preserving the stream position with Unicode encoding.
Summary: BinaryStream.PeekChar is not preserving the stream position with Unicode enco...
Alias: None
Product: Class Libraries
Classification: Mono
Component: System ()
Version: 4.0.0
Hardware: All All
: --- normal
Target Milestone: Untriaged
Assignee: Marek Safar
Depends on:
Reported: 2015-09-22 11:48 UTC by rubarax
Modified: 2015-09-24 05:51 UTC (History)
2 users (show)

Is this bug a regression?: ---
Last known good build:

nunit test case to reproduce the issue (491 bytes, text/plain)
2015-09-22 11:48 UTC, rubarax

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description rubarax 2015-09-22 11:48:48 UTC
Created attachment 13020 [details]
nunit test case to reproduce the issue

** Test code **

            using(MemoryStream stream = new MemoryStream())
            using(BinaryWriter writer = new BinaryWriter(stream))
            using(BinaryReader reader = new BinaryReader(stream, Encoding.Unicode))
                stream.Position = 0;
                Assert.AreEqual (0, stream.Position); // the position is 1 instead of 0!!

** Problem description **

The number of bytes read by the BinaryReader.ReadCharBytes method is not correctly updated when the encoding is Unicode (and an extra byte is read). Thus, the PeekChar method does not restore the stream to the original position, because the out value 'bcount' was not correctly updated.

The issue was added in the following commit: https://github.com/mono/mono/commit/ed1d3ec5260b613849b9af27c9dbcb6566c1637c

** Possible solution **

I think that increasing the 'chars_read' value after reading the new byte would do the fix.

	if (m_encoding is UnicodeEncoding) {
		CheckBuffer (pos + 1);
		read_byte = m_stream.ReadByte();
---->		chars_read ++;
		if (read_byte != -1) {
			m_buffer [pos++] = (byte)read_byte;
Comment 1 Marek Safar 2015-09-24 05:30:00 UTC
Already fixed in Mono 4.2
Comment 2 rubarax 2015-09-24 05:36:07 UTC
Won't you integrate the fix in the current stable branch 4.0?
Comment 3 Marek Safar 2015-09-24 05:51:20 UTC
No, 4.0 is opened for security/critical fixes only