MessageExtensions.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2015 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using Google.Protobuf.Reflection;
  33. using System.Buffers;
  34. using System.Collections;
  35. using System;
  36. using System.IO;
  37. using System.Linq;
  38. using System.Security;
  39. namespace Google.Protobuf
  40. {
  41. /// <summary>
  42. /// Extension methods on <see cref="IMessage"/> and <see cref="IMessage{T}"/>.
  43. /// </summary>
  44. public static class MessageExtensions
  45. {
  46. /// <summary>
  47. /// Merges data from the given byte array into an existing message.
  48. /// </summary>
  49. /// <param name="message">The message to merge the data into.</param>
  50. /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
  51. public static void MergeFrom(this IMessage message, byte[] data) =>
  52. MergeFrom(message, data, false, null);
  53. /// <summary>
  54. /// Merges data from the given byte array slice into an existing message.
  55. /// </summary>
  56. /// <param name="message">The message to merge the data into.</param>
  57. /// <param name="data">The data containing the slice to merge, which must be protobuf-encoded binary data.</param>
  58. /// <param name="offset">The offset of the slice to merge.</param>
  59. /// <param name="length">The length of the slice to merge.</param>
  60. public static void MergeFrom(this IMessage message, byte[] data, int offset, int length) =>
  61. MergeFrom(message, data, offset, length, false, null);
  62. /// <summary>
  63. /// Merges data from the given byte string into an existing message.
  64. /// </summary>
  65. /// <param name="message">The message to merge the data into.</param>
  66. /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
  67. public static void MergeFrom(this IMessage message, ByteString data) =>
  68. MergeFrom(message, data, false, null);
  69. /// <summary>
  70. /// Merges data from the given stream into an existing message.
  71. /// </summary>
  72. /// <param name="message">The message to merge the data into.</param>
  73. /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
  74. public static void MergeFrom(this IMessage message, Stream input) =>
  75. MergeFrom(message, input, false, null);
  76. /// <summary>
  77. /// Merges length-delimited data from the given stream into an existing message.
  78. /// </summary>
  79. /// <remarks>
  80. /// The stream is expected to contain a length and then the data. Only the amount of data
  81. /// specified by the length will be consumed.
  82. /// </remarks>
  83. /// <param name="message">The message to merge the data into.</param>
  84. /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
  85. public static void MergeDelimitedFrom(this IMessage message, Stream input) =>
  86. MergeDelimitedFrom(message, input, false, null);
  87. /// <summary>
  88. /// Converts the given message into a byte array in protobuf encoding.
  89. /// </summary>
  90. /// <param name="message">The message to convert.</param>
  91. /// <returns>The message data as a byte array.</returns>
  92. public static byte[] ToByteArray(this IMessage message)
  93. {
  94. ProtoPreconditions.CheckNotNull(message, "message");
  95. byte[] result = new byte[message.CalculateSize()];
  96. CodedOutputStream output = new CodedOutputStream(result);
  97. message.WriteTo(output);
  98. output.CheckNoSpaceLeft();
  99. return result;
  100. }
  101. /// <summary>
  102. /// Writes the given message data to the given stream in protobuf encoding.
  103. /// </summary>
  104. /// <param name="message">The message to write to the stream.</param>
  105. /// <param name="output">The stream to write to.</param>
  106. public static void WriteTo(this IMessage message, Stream output)
  107. {
  108. ProtoPreconditions.CheckNotNull(message, "message");
  109. ProtoPreconditions.CheckNotNull(output, "output");
  110. CodedOutputStream codedOutput = new CodedOutputStream(output);
  111. message.WriteTo(codedOutput);
  112. codedOutput.Flush();
  113. }
  114. /// <summary>
  115. /// Writes the length and then data of the given message to a stream.
  116. /// </summary>
  117. /// <param name="message">The message to write.</param>
  118. /// <param name="output">The output stream to write to.</param>
  119. public static void WriteDelimitedTo(this IMessage message, Stream output)
  120. {
  121. ProtoPreconditions.CheckNotNull(message, "message");
  122. ProtoPreconditions.CheckNotNull(output, "output");
  123. CodedOutputStream codedOutput = new CodedOutputStream(output);
  124. codedOutput.WriteLength(message.CalculateSize());
  125. message.WriteTo(codedOutput);
  126. codedOutput.Flush();
  127. }
  128. /// <summary>
  129. /// Converts the given message into a byte string in protobuf encoding.
  130. /// </summary>
  131. /// <param name="message">The message to convert.</param>
  132. /// <returns>The message data as a byte string.</returns>
  133. public static ByteString ToByteString(this IMessage message)
  134. {
  135. ProtoPreconditions.CheckNotNull(message, "message");
  136. return ByteString.AttachBytes(message.ToByteArray());
  137. }
  138. /// <summary>
  139. /// Writes the given message data to the given buffer writer in protobuf encoding.
  140. /// </summary>
  141. /// <param name="message">The message to write to the stream.</param>
  142. /// <param name="output">The stream to write to.</param>
  143. [SecuritySafeCritical]
  144. public static void WriteTo(this IMessage message, IBufferWriter<byte> output)
  145. {
  146. ProtoPreconditions.CheckNotNull(message, nameof(message));
  147. ProtoPreconditions.CheckNotNull(output, nameof(output));
  148. WriteContext.Initialize(output, out WriteContext ctx);
  149. WritingPrimitivesMessages.WriteRawMessage(ref ctx, message);
  150. ctx.Flush();
  151. // TODO: handling errors when IBufferWriter is used?
  152. }
  153. /// <summary>
  154. /// Writes the given message data to the given span in protobuf encoding.
  155. /// The size of the destination span needs to fit the serialized size
  156. /// of the message exactly, otherwise an exception is thrown.
  157. /// </summary>
  158. /// <param name="message">The message to write to the stream.</param>
  159. /// <param name="output">The span to write to. Size must match size of the message exactly.</param>
  160. [SecuritySafeCritical]
  161. public static void WriteTo(this IMessage message, Span<byte> output)
  162. {
  163. ProtoPreconditions.CheckNotNull(message, nameof(message));
  164. WriteContext.Initialize(ref output, out WriteContext ctx);
  165. WritingPrimitivesMessages.WriteRawMessage(ref ctx, message);
  166. ctx.CheckNoSpaceLeft();
  167. }
  168. /// <summary>
  169. /// Checks if all required fields in a message have values set. For proto3 messages, this returns true
  170. /// </summary>
  171. public static bool IsInitialized(this IMessage message)
  172. {
  173. if (message.Descriptor.File.Syntax == Syntax.Proto3)
  174. {
  175. return true;
  176. }
  177. if (!message.Descriptor.IsExtensionsInitialized(message))
  178. {
  179. return false;
  180. }
  181. return message.Descriptor
  182. .Fields
  183. .InDeclarationOrder()
  184. .All(f =>
  185. {
  186. if (f.IsMap)
  187. {
  188. var valueField = f.MessageType.Fields[2];
  189. if (valueField.FieldType == FieldType.Message)
  190. {
  191. var map = (IDictionary)f.Accessor.GetValue(message);
  192. return map.Values.Cast<IMessage>().All(IsInitialized);
  193. }
  194. else
  195. {
  196. return true;
  197. }
  198. }
  199. else if (f.IsRepeated && f.FieldType == FieldType.Message || f.FieldType == FieldType.Group)
  200. {
  201. var enumerable = (IEnumerable)f.Accessor.GetValue(message);
  202. return enumerable.Cast<IMessage>().All(IsInitialized);
  203. }
  204. else if (f.FieldType == FieldType.Message || f.FieldType == FieldType.Group)
  205. {
  206. if (f.Accessor.HasValue(message))
  207. {
  208. return ((IMessage)f.Accessor.GetValue(message)).IsInitialized();
  209. }
  210. else
  211. {
  212. return !f.IsRequired;
  213. }
  214. }
  215. else if (f.IsRequired)
  216. {
  217. return f.Accessor.HasValue(message);
  218. }
  219. else
  220. {
  221. return true;
  222. }
  223. });
  224. }
  225. // Implementations allowing unknown fields to be discarded.
  226. internal static void MergeFrom(this IMessage message, byte[] data, bool discardUnknownFields, ExtensionRegistry registry)
  227. {
  228. ProtoPreconditions.CheckNotNull(message, "message");
  229. ProtoPreconditions.CheckNotNull(data, "data");
  230. CodedInputStream input = new CodedInputStream(data);
  231. input.DiscardUnknownFields = discardUnknownFields;
  232. input.ExtensionRegistry = registry;
  233. message.MergeFrom(input);
  234. input.CheckReadEndOfStreamTag();
  235. }
  236. internal static void MergeFrom(this IMessage message, byte[] data, int offset, int length, bool discardUnknownFields, ExtensionRegistry registry)
  237. {
  238. ProtoPreconditions.CheckNotNull(message, "message");
  239. ProtoPreconditions.CheckNotNull(data, "data");
  240. CodedInputStream input = new CodedInputStream(data, offset, length);
  241. input.DiscardUnknownFields = discardUnknownFields;
  242. input.ExtensionRegistry = registry;
  243. message.MergeFrom(input);
  244. input.CheckReadEndOfStreamTag();
  245. }
  246. internal static void MergeFrom(this IMessage message, ByteString data, bool discardUnknownFields, ExtensionRegistry registry)
  247. {
  248. ProtoPreconditions.CheckNotNull(message, "message");
  249. ProtoPreconditions.CheckNotNull(data, "data");
  250. CodedInputStream input = data.CreateCodedInput();
  251. input.DiscardUnknownFields = discardUnknownFields;
  252. input.ExtensionRegistry = registry;
  253. message.MergeFrom(input);
  254. input.CheckReadEndOfStreamTag();
  255. }
  256. internal static void MergeFrom(this IMessage message, Stream input, bool discardUnknownFields, ExtensionRegistry registry)
  257. {
  258. ProtoPreconditions.CheckNotNull(message, "message");
  259. ProtoPreconditions.CheckNotNull(input, "input");
  260. CodedInputStream codedInput = new CodedInputStream(input);
  261. codedInput.DiscardUnknownFields = discardUnknownFields;
  262. codedInput.ExtensionRegistry = registry;
  263. message.MergeFrom(codedInput);
  264. codedInput.CheckReadEndOfStreamTag();
  265. }
  266. [SecuritySafeCritical]
  267. internal static void MergeFrom(this IMessage message, ReadOnlySequence<byte> data, bool discardUnknownFields, ExtensionRegistry registry)
  268. {
  269. ParseContext.Initialize(data, out ParseContext ctx);
  270. ctx.DiscardUnknownFields = discardUnknownFields;
  271. ctx.ExtensionRegistry = registry;
  272. ParsingPrimitivesMessages.ReadRawMessage(ref ctx, message);
  273. ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref ctx.state);
  274. }
  275. internal static void MergeDelimitedFrom(this IMessage message, Stream input, bool discardUnknownFields, ExtensionRegistry registry)
  276. {
  277. ProtoPreconditions.CheckNotNull(message, "message");
  278. ProtoPreconditions.CheckNotNull(input, "input");
  279. int size = (int) CodedInputStream.ReadRawVarint32(input);
  280. Stream limitedStream = new LimitedInputStream(input, size);
  281. MergeFrom(message, limitedStream, discardUnknownFields, registry);
  282. }
  283. }
  284. }