MessageExtensions.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.IO;
  36. using System.Linq;
  37. using System.Security;
  38. namespace Google.Protobuf
  39. {
  40. /// <summary>
  41. /// Extension methods on <see cref="IMessage"/> and <see cref="IMessage{T}"/>.
  42. /// </summary>
  43. public static class MessageExtensions
  44. {
  45. /// <summary>
  46. /// Merges data from the given byte array into an existing message.
  47. /// </summary>
  48. /// <param name="message">The message to merge the data into.</param>
  49. /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
  50. public static void MergeFrom(this IMessage message, byte[] data) =>
  51. MergeFrom(message, data, false, null);
  52. /// <summary>
  53. /// Merges data from the given byte array slice into an existing message.
  54. /// </summary>
  55. /// <param name="message">The message to merge the data into.</param>
  56. /// <param name="data">The data containing the slice to merge, which must be protobuf-encoded binary data.</param>
  57. /// <param name="offset">The offset of the slice to merge.</param>
  58. /// <param name="length">The length of the slice to merge.</param>
  59. public static void MergeFrom(this IMessage message, byte[] data, int offset, int length) =>
  60. MergeFrom(message, data, offset, length, false, null);
  61. /// <summary>
  62. /// Merges data from the given byte string into an existing message.
  63. /// </summary>
  64. /// <param name="message">The message to merge the data into.</param>
  65. /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
  66. public static void MergeFrom(this IMessage message, ByteString data) =>
  67. MergeFrom(message, data, false, null);
  68. /// <summary>
  69. /// Merges data from the given stream into an existing message.
  70. /// </summary>
  71. /// <param name="message">The message to merge the data into.</param>
  72. /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
  73. public static void MergeFrom(this IMessage message, Stream input) =>
  74. MergeFrom(message, input, false, null);
  75. /// <summary>
  76. /// Merges length-delimited data from the given stream into an existing message.
  77. /// </summary>
  78. /// <remarks>
  79. /// The stream is expected to contain a length and then the data. Only the amount of data
  80. /// specified by the length will be consumed.
  81. /// </remarks>
  82. /// <param name="message">The message to merge the data into.</param>
  83. /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
  84. public static void MergeDelimitedFrom(this IMessage message, Stream input) =>
  85. MergeDelimitedFrom(message, input, false, null);
  86. /// <summary>
  87. /// Converts the given message into a byte array in protobuf encoding.
  88. /// </summary>
  89. /// <param name="message">The message to convert.</param>
  90. /// <returns>The message data as a byte array.</returns>
  91. public static byte[] ToByteArray(this IMessage message)
  92. {
  93. ProtoPreconditions.CheckNotNull(message, "message");
  94. byte[] result = new byte[message.CalculateSize()];
  95. CodedOutputStream output = new CodedOutputStream(result);
  96. message.WriteTo(output);
  97. output.CheckNoSpaceLeft();
  98. return result;
  99. }
  100. /// <summary>
  101. /// Writes the given message data to the given stream in protobuf encoding.
  102. /// </summary>
  103. /// <param name="message">The message to write to the stream.</param>
  104. /// <param name="output">The stream to write to.</param>
  105. public static void WriteTo(this IMessage message, Stream output)
  106. {
  107. ProtoPreconditions.CheckNotNull(message, "message");
  108. ProtoPreconditions.CheckNotNull(output, "output");
  109. CodedOutputStream codedOutput = new CodedOutputStream(output);
  110. message.WriteTo(codedOutput);
  111. codedOutput.Flush();
  112. }
  113. /// <summary>
  114. /// Writes the length and then data of the given message to a stream.
  115. /// </summary>
  116. /// <param name="message">The message to write.</param>
  117. /// <param name="output">The output stream to write to.</param>
  118. public static void WriteDelimitedTo(this IMessage message, Stream output)
  119. {
  120. ProtoPreconditions.CheckNotNull(message, "message");
  121. ProtoPreconditions.CheckNotNull(output, "output");
  122. CodedOutputStream codedOutput = new CodedOutputStream(output);
  123. codedOutput.WriteRawVarint32((uint)message.CalculateSize());
  124. message.WriteTo(codedOutput);
  125. codedOutput.Flush();
  126. }
  127. /// <summary>
  128. /// Converts the given message into a byte string in protobuf encoding.
  129. /// </summary>
  130. /// <param name="message">The message to convert.</param>
  131. /// <returns>The message data as a byte string.</returns>
  132. public static ByteString ToByteString(this IMessage message)
  133. {
  134. ProtoPreconditions.CheckNotNull(message, "message");
  135. return ByteString.AttachBytes(message.ToByteArray());
  136. }
  137. /// <summary>
  138. /// Checks if all required fields in a message have values set. For proto3 messages, this returns true
  139. /// </summary>
  140. public static bool IsInitialized(this IMessage message)
  141. {
  142. if (message.Descriptor.File.Syntax == Syntax.Proto3)
  143. {
  144. return true;
  145. }
  146. if (!message.Descriptor.IsExtensionsInitialized(message))
  147. {
  148. return false;
  149. }
  150. return message.Descriptor
  151. .Fields
  152. .InDeclarationOrder()
  153. .All(f =>
  154. {
  155. if (f.IsMap)
  156. {
  157. var valueField = f.MessageType.Fields[2];
  158. if (valueField.FieldType == FieldType.Message)
  159. {
  160. var map = (IDictionary)f.Accessor.GetValue(message);
  161. return map.Values.Cast<IMessage>().All(IsInitialized);
  162. }
  163. else
  164. {
  165. return true;
  166. }
  167. }
  168. else if (f.IsRepeated && f.FieldType == FieldType.Message || f.FieldType == FieldType.Group)
  169. {
  170. var enumerable = (IEnumerable)f.Accessor.GetValue(message);
  171. return enumerable.Cast<IMessage>().All(IsInitialized);
  172. }
  173. else if (f.FieldType == FieldType.Message || f.FieldType == FieldType.Group)
  174. {
  175. if (f.Accessor.HasValue(message))
  176. {
  177. return ((IMessage)f.Accessor.GetValue(message)).IsInitialized();
  178. }
  179. else
  180. {
  181. return !f.IsRequired;
  182. }
  183. }
  184. else if (f.IsRequired)
  185. {
  186. return f.Accessor.HasValue(message);
  187. }
  188. else
  189. {
  190. return true;
  191. }
  192. });
  193. }
  194. // Implementations allowing unknown fields to be discarded.
  195. internal static void MergeFrom(this IMessage message, byte[] data, bool discardUnknownFields, ExtensionRegistry registry)
  196. {
  197. ProtoPreconditions.CheckNotNull(message, "message");
  198. ProtoPreconditions.CheckNotNull(data, "data");
  199. CodedInputStream input = new CodedInputStream(data);
  200. input.DiscardUnknownFields = discardUnknownFields;
  201. input.ExtensionRegistry = registry;
  202. message.MergeFrom(input);
  203. input.CheckReadEndOfStreamTag();
  204. }
  205. internal static void MergeFrom(this IMessage message, byte[] data, int offset, int length, bool discardUnknownFields, ExtensionRegistry registry)
  206. {
  207. ProtoPreconditions.CheckNotNull(message, "message");
  208. ProtoPreconditions.CheckNotNull(data, "data");
  209. CodedInputStream input = new CodedInputStream(data, offset, length);
  210. input.DiscardUnknownFields = discardUnknownFields;
  211. input.ExtensionRegistry = registry;
  212. message.MergeFrom(input);
  213. input.CheckReadEndOfStreamTag();
  214. }
  215. internal static void MergeFrom(this IMessage message, ByteString data, bool discardUnknownFields, ExtensionRegistry registry)
  216. {
  217. ProtoPreconditions.CheckNotNull(message, "message");
  218. ProtoPreconditions.CheckNotNull(data, "data");
  219. CodedInputStream input = data.CreateCodedInput();
  220. input.DiscardUnknownFields = discardUnknownFields;
  221. input.ExtensionRegistry = registry;
  222. message.MergeFrom(input);
  223. input.CheckReadEndOfStreamTag();
  224. }
  225. internal static void MergeFrom(this IMessage message, Stream input, bool discardUnknownFields, ExtensionRegistry registry)
  226. {
  227. ProtoPreconditions.CheckNotNull(message, "message");
  228. ProtoPreconditions.CheckNotNull(input, "input");
  229. CodedInputStream codedInput = new CodedInputStream(input);
  230. codedInput.DiscardUnknownFields = discardUnknownFields;
  231. codedInput.ExtensionRegistry = registry;
  232. message.MergeFrom(codedInput);
  233. codedInput.CheckReadEndOfStreamTag();
  234. }
  235. [SecuritySafeCritical]
  236. internal static void MergeFrom(this IMessage message, ReadOnlySequence<byte> data, bool discardUnknownFields, ExtensionRegistry registry)
  237. {
  238. ParseContext.Initialize(data, out ParseContext ctx);
  239. ctx.DiscardUnknownFields = discardUnknownFields;
  240. ctx.ExtensionRegistry = registry;
  241. ParsingPrimitivesMessages.ReadRawMessage(ref ctx, message);
  242. ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref ctx.state);
  243. }
  244. internal static void MergeDelimitedFrom(this IMessage message, Stream input, bool discardUnknownFields, ExtensionRegistry registry)
  245. {
  246. ProtoPreconditions.CheckNotNull(message, "message");
  247. ProtoPreconditions.CheckNotNull(input, "input");
  248. int size = (int) CodedInputStream.ReadRawVarint32(input);
  249. Stream limitedStream = new LimitedInputStream(input, size);
  250. MergeFrom(message, limitedStream, discardUnknownFields, registry);
  251. }
  252. }
  253. }