| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using Google.Protobuf; |
| | 4 | | using System.Buffers; |
| | 5 | | using System.Buffers.Binary; |
| | 6 | | using System.IO.Pipelines; |
| | 7 | |
|
| | 8 | | namespace IceRpc.Protobuf.Internal; |
| | 9 | |
|
| | 10 | | /// <summary>Provides an extension method for <see cref="IMessage" />.</summary> |
| | 11 | | internal static class MessageExtensions |
| | 12 | | { |
| | 13 | | /// <summary>Encodes an <see cref="IMessage"/> as a length-prefixed message, using the Protobuf encoding.</summary> |
| | 14 | | /// <param name="message">The <see cref="IMessage" /> to encode.</param> |
| | 15 | | /// <param name="pipeOptions">The options used to create the pipe.</param> |
| | 16 | | /// <returns>A <see cref="PipeReader" /> containing the length-prefixed message.</returns> |
| | 17 | | internal static PipeReader EncodeAsLengthPrefixedMessage(this IMessage message, PipeOptions pipeOptions) |
| 54 | 18 | | { |
| 54 | 19 | | var pipe = new Pipe(pipeOptions); |
| 54 | 20 | | pipe.Writer.Write(new Span<byte>([0])); // Not compressed |
| 54 | 21 | | Span<byte> lengthPlaceholder = pipe.Writer.GetSpan(4); |
| 54 | 22 | | pipe.Writer.Advance(4); |
| 54 | 23 | | message.WriteTo(pipe.Writer); |
| 54 | 24 | | int length = checked((int)pipe.Writer.UnflushedBytes); |
| 54 | 25 | | BinaryPrimitives.WriteInt32BigEndian(lengthPlaceholder, length - 5); |
| 54 | 26 | | pipe.Writer.Complete(); |
| 54 | 27 | | return pipe.Reader; |
| 54 | 28 | | } |
| | 29 | | } |