diff --git a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs index 08f4129d52..1c77e121d3 100644 --- a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs @@ -275,6 +275,32 @@ namespace Google.Protobuf 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(); + 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] public void EncodeZigZag32() diff --git a/csharp/src/Google.Protobuf/WriteBufferHelper.cs b/csharp/src/Google.Protobuf/WriteBufferHelper.cs index 9bd5061da4..f6617c9dce 100644 --- a/csharp/src/Google.Protobuf/WriteBufferHelper.cs +++ b/csharp/src/Google.Protobuf/WriteBufferHelper.cs @@ -153,11 +153,13 @@ namespace Google.Protobuf } 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.position = 0; state.limit = 0; buffer = default; // invalidate the current buffer - // TODO: add a test when we flush and then try to write more data } } }