Przeglądaj źródła

test WriteContext writing with multiple flushes

Jan Tattermusch 5 lat temu
rodzic
commit
19c0d73fb9

+ 26 - 0
csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs

@@ -275,6 +275,32 @@ namespace Google.Protobuf
                 Assert.AreEqual(rawBytes, bufferWriter.WrittenSpan.ToArray()); 
                 Assert.AreEqual(rawBytes, bufferWriter.WrittenSpan.ToArray()); 
             }
             }
         }
         }
+
+        [Test]
+        public void WriteContext_WritesWithFlushes()
+        {
+            TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
+
+            MemoryStream expectedOutput = new MemoryStream();
+            CodedOutputStream output = new CodedOutputStream(expectedOutput);
+            output.WriteMessage(message);
+            output.Flush();
+            byte[] expectedBytes1 = expectedOutput.ToArray();
+
+            output.WriteMessage(message);
+            output.Flush();
+            byte[] expectedBytes2 = expectedOutput.ToArray();
+
+            var bufferWriter = new ArrayBufferWriter<byte>();
+            WriteContext.Initialize(bufferWriter, out WriteContext ctx);
+            ctx.WriteMessage(message);
+            ctx.Flush();
+            Assert.AreEqual(expectedBytes1, bufferWriter.WrittenSpan.ToArray());
+
+            ctx.WriteMessage(message);
+            ctx.Flush();
+            Assert.AreEqual(expectedBytes2, bufferWriter.WrittenSpan.ToArray());
+        }
         
         
         [Test]
         [Test]
         public void EncodeZigZag32()
         public void EncodeZigZag32()

+ 3 - 1
csharp/src/Google.Protobuf/WriteBufferHelper.cs

@@ -153,11 +153,13 @@ namespace Google.Protobuf
             }
             }
             else if (state.writeBufferHelper.bufferWriter != null)
             else if (state.writeBufferHelper.bufferWriter != null)
             {
             {
+                // calling Advance invalidates the current buffer and we must not continue writing to it,
+                // so we set the current buffer to point to an empty Span. If any subsequent writes happen,
+                // the first subsequent write will trigger refresing of the buffer.
                 state.writeBufferHelper.bufferWriter.Advance(state.position);
                 state.writeBufferHelper.bufferWriter.Advance(state.position);
                 state.position = 0;
                 state.position = 0;
                 state.limit = 0;
                 state.limit = 0;
                 buffer = default;  // invalidate the current buffer
                 buffer = default;  // invalidate the current buffer
-                // TODO: add a test when we flush and then try to write more data
             }
             }
         }
         }
     }
     }