diff --git a/csharp/src/Google.Protobuf.Test/MessageExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/MessageExtensionsTest.cs new file mode 100644 index 0000000000000..e217881419d21 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/MessageExtensionsTest.cs @@ -0,0 +1,22 @@ +using System.IO; +using Google.Protobuf.Buffers; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf; + +public class MessageExtensionsTest +{ + [Test] + public void TestWriteDelimitedToRoundTripWithBufferWriter() + { + TestWellKnownTypes message = new() { Int32Field = 25 }; + + TestArrayBufferWriter buffer = new(); + message.WriteDelimitedTo(buffer); + + Assert.That( + TestWellKnownTypes.Parser.ParseDelimitedFrom(new MemoryStream(buffer.WrittenSpan.ToArray())), + Is.EqualTo(message)); + } +} \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/MessageExtensions.cs b/csharp/src/Google.Protobuf/MessageExtensions.cs index 910c40ff96df9..aec47415b8b9f 100644 --- a/csharp/src/Google.Protobuf/MessageExtensions.cs +++ b/csharp/src/Google.Protobuf/MessageExtensions.cs @@ -157,6 +157,23 @@ public static void WriteTo(this IMessage message, IBufferWriter output) ctx.Flush(); } + /// + /// Writes the length and then data of the given message to a buffer writer. + /// + /// The message to write. + /// The buffer writer. + [SecuritySafeCritical] + public static void WriteDelimitedTo(this IMessage message, IBufferWriter output) + { + ProtoPreconditions.CheckNotNull(message, nameof(message)); + ProtoPreconditions.CheckNotNull(output, nameof(output)); + + WriteContext.Initialize(output, out WriteContext ctx); + ctx.WriteLength(message.CalculateSize()); + WritingPrimitivesMessages.WriteRawMessage(ref ctx, message); + ctx.Flush(); + } + /// /// Writes the given message data to the given span in protobuf encoding. /// The size of the destination span needs to fit the serialized size