FIx SequenceReader Rewind(0) state corruption (#86070)
authorhrrrrustic <hrrrrustic@gmail.com>
Fri, 7 Jul 2023 16:46:19 +0000 (19:46 +0300)
committerGitHub <noreply@github.com>
Fri, 7 Jul 2023 16:46:19 +0000 (18:46 +0200)
* Add zero check

* Drop few redundant readonly

* Add test

src/libraries/System.Memory/src/System/Buffers/SequenceReader.cs
src/libraries/System.Memory/tests/SequenceReader/Rewind.cs

index abbe97c..78de8a5 100644 (file)
@@ -44,7 +44,7 @@ namespace System.Buffers
         /// <summary>
         /// The underlying <see cref="ReadOnlySequence{T}"/> for the reader.
         /// </summary>
-        public readonly ReadOnlySequence<T> Sequence { get; }
+        public ReadOnlySequence<T> Sequence { get; }
 
         /// <summary>
         /// Gets the unread portion of the <see cref="Sequence"/>.
@@ -63,12 +63,12 @@ namespace System.Buffers
         /// <summary>
         /// The current segment in the <see cref="Sequence"/> as a span.
         /// </summary>
-        public ReadOnlySpan<T> CurrentSpan { readonly get; private set; }
+        public ReadOnlySpan<T> CurrentSpan { get; private set; }
 
         /// <summary>
         /// The index in the <see cref="CurrentSpan"/>.
         /// </summary>
-        public int CurrentSpanIndex { readonly get; private set; }
+        public int CurrentSpanIndex { get; private set; }
 
         /// <summary>
         /// The unread portion of the <see cref="CurrentSpan"/>.
@@ -82,7 +82,7 @@ namespace System.Buffers
         /// <summary>
         /// The total number of <typeparamref name="T"/>'s processed by the reader.
         /// </summary>
-        public long Consumed { readonly get; private set; }
+        public long Consumed { get; private set; }
 
         /// <summary>
         /// Remaining <typeparamref name="T"/>'s in the reader's <see cref="Sequence"/>.
@@ -223,6 +223,11 @@ namespace System.Buffers
                 ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
             }
 
+            if (count == 0)
+            {
+                return;
+            }
+
             Consumed -= count;
 
             if (CurrentSpanIndex >= count)
index fd5a296..1181937 100644 (file)
@@ -120,5 +120,20 @@ namespace System.Memory.Tests.SequenceReader
             reader.Rewind(2);
             Assert.Equal(new byte[] { 1, 2 }, reader.CurrentSpan.ToArray());
         }
+
+        [Fact]
+        public void RewindZero_DoesNothing()
+        {
+            var emptySeq = ReadOnlySequence<byte>.Empty;
+            var reader = new SequenceReader<byte>(emptySeq);
+
+            Assert.True(reader.End);
+            Assert.False(reader.TryRead(out byte _));
+
+            reader.Rewind(0);
+
+            Assert.True(reader.End);
+            Assert.False(reader.TryRead(out byte _));
+        }
     }
 }