MessageExtensions.cs 12 KB

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