Fix buffering bugs in TextFieldParser (#59487)
authorStephen Toub <stoub@microsoft.com>
Wed, 22 Sep 2021 23:57:52 +0000 (19:57 -0400)
committerGitHub <noreply@github.com>
Wed, 22 Sep 2021 23:57:52 +0000 (19:57 -0400)
commita65f8368166a2817dbf4f974ad497d0f8fe2d2eb
tree87c0a1d2b376af837739d93dccd3bb63394216ab
parent5181e1cd5b3fde9da15fe3f8d3eceaa9d3f64e01
Fix buffering bugs in TextFieldParser (#59487)

Three bugs being fixed here:
1. The SlideCursorToStartOfBuffer method is incorrectly assuming that the buffer is filled to its end (that m_Buffer.Length = m_CharsRead).  As a result, two things happen.  First, we copy more data than is needed to the temporary buffer; that's just unnecessary but not harmful.  But second, when it issues a read to fill the remainder of the buffer, it does so at the wrong position, both leaving zeros in the buffer that end up getting parsed as real data and losing real data from the end.
2. IncreaseBufferSize assumes m_CharsRead = m_Buffer.Length, which may not be the case.  As with (1), this can result in it reading into the wrong part of the array and leaving garbage that gets processed.
3. IncreaseBufferSize is always increasing the buffer size, even if only a small portion of the buffer is used.  This can then result in the whole operation failing when it repeatedly increases the buffer size and ends up failing due to ticking over the max buffer threshold.

(1) doesn't exist in .NET Framework 4.8 but (2) and (3) do.  (1) is easily triggered by a stream that sporadically doesn't produce all the data requested; (2) and (3) end up needing a stream that frequently produces much less than requested.  This PR fixes all three.
src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileIO/TextFieldParser.vb
src/libraries/Microsoft.VisualBasic.Core/tests/Microsoft/VisualBasic/FileIO/TextFieldParserTests.cs