MessageParser.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 System;
  33. using System.IO;
  34. namespace Google.Protobuf
  35. {
  36. /// <summary>
  37. /// A general message parser, typically used by reflection-based code as all the methods
  38. /// return simple <see cref="IMessage"/>.
  39. /// </summary>
  40. public class MessageParser
  41. {
  42. private Func<IMessage> factory;
  43. internal MessageParser(Func<IMessage> factory)
  44. {
  45. this.factory = factory;
  46. }
  47. /// <summary>
  48. /// Creates a template instance ready for population.
  49. /// </summary>
  50. /// <returns>An empty message.</returns>
  51. internal IMessage CreateTemplate()
  52. {
  53. return factory();
  54. }
  55. /// <summary>
  56. /// Parses a message from a byte array.
  57. /// </summary>
  58. /// <param name="data">The byte array containing the message. Must not be null.</param>
  59. /// <returns>The newly parsed message.</returns>
  60. public IMessage ParseFrom(byte[] data)
  61. {
  62. IMessage message = factory();
  63. message.MergeFrom(data);
  64. return message;
  65. }
  66. /// <summary>
  67. /// Parses a message from a byte array slice.
  68. /// </summary>
  69. /// <param name="data">The byte array containing the message. Must not be null.</param>
  70. /// <param name="offset">The offset of the slice to parse.</param>
  71. /// <param name="length">The length of the slice to parse.</param>
  72. /// <returns>The newly parsed message.</returns>
  73. public IMessage ParseFrom(byte[] data, int offset, int length)
  74. {
  75. IMessage message = factory();
  76. message.MergeFrom(data, offset, length);
  77. return message;
  78. }
  79. /// <summary>
  80. /// Parses a message from the given byte string.
  81. /// </summary>
  82. /// <param name="data">The data to parse.</param>
  83. /// <returns>The parsed message.</returns>
  84. public IMessage ParseFrom(ByteString data)
  85. {
  86. IMessage message = factory();
  87. message.MergeFrom(data);
  88. return message;
  89. }
  90. /// <summary>
  91. /// Parses a message from the given stream.
  92. /// </summary>
  93. /// <param name="input">The stream to parse.</param>
  94. /// <returns>The parsed message.</returns>
  95. public IMessage ParseFrom(Stream input)
  96. {
  97. IMessage message = factory();
  98. message.MergeFrom(input);
  99. return message;
  100. }
  101. /// <summary>
  102. /// Parses a length-delimited message from the given stream.
  103. /// </summary>
  104. /// <remarks>
  105. /// The stream is expected to contain a length and then the data. Only the amount of data
  106. /// specified by the length will be consumed.
  107. /// </remarks>
  108. /// <param name="input">The stream to parse.</param>
  109. /// <returns>The parsed message.</returns>
  110. public IMessage ParseDelimitedFrom(Stream input)
  111. {
  112. IMessage message = factory();
  113. message.MergeDelimitedFrom(input);
  114. return message;
  115. }
  116. /// <summary>
  117. /// Parses a message from the given coded input stream.
  118. /// </summary>
  119. /// <param name="input">The stream to parse.</param>
  120. /// <returns>The parsed message.</returns>
  121. public IMessage ParseFrom(CodedInputStream input)
  122. {
  123. IMessage message = factory();
  124. message.MergeFrom(input);
  125. return message;
  126. }
  127. /// <summary>
  128. /// Parses a message from the given JSON.
  129. /// </summary>
  130. /// <param name="json">The JSON to parse.</param>
  131. /// <returns>The parsed message.</returns>
  132. /// <exception cref="InvalidJsonException">The JSON does not comply with RFC 7159</exception>
  133. /// <exception cref="InvalidProtocolBufferException">The JSON does not represent a Protocol Buffers message correctly</exception>
  134. public IMessage ParseJson(string json)
  135. {
  136. IMessage message = factory();
  137. JsonParser.Default.Merge(message, json);
  138. return message;
  139. }
  140. }
  141. /// <summary>
  142. /// A parser for a specific message type.
  143. /// </summary>
  144. /// <remarks>
  145. /// <p>
  146. /// This delegates most behavior to the
  147. /// <see cref="IMessage.MergeFrom"/> implementation within the original type, but
  148. /// provides convenient overloads to parse from a variety of sources.
  149. /// </p>
  150. /// <p>
  151. /// Most applications will never need to create their own instances of this type;
  152. /// instead, use the static <c>Parser</c> property of a generated message type to obtain a
  153. /// parser for that type.
  154. /// </p>
  155. /// </remarks>
  156. /// <typeparam name="T">The type of message to be parsed.</typeparam>
  157. public sealed class MessageParser<T> : MessageParser where T : IMessage<T>
  158. {
  159. // Implementation note: all the methods here *could* just delegate up to the base class and cast the result.
  160. // The current implementation avoids a virtual method call and a cast, which *may* be significant in some cases.
  161. // Benchmarking work is required to measure the significance - but it's only a few lines of code in any case.
  162. // The API wouldn't change anyway - just the implementation - so this work can be deferred.
  163. private readonly Func<T> factory;
  164. /// <summary>
  165. /// Creates a new parser.
  166. /// </summary>
  167. /// <remarks>
  168. /// The factory method is effectively an optimization over using a generic constraint
  169. /// to require a parameterless constructor: delegates are significantly faster to execute.
  170. /// </remarks>
  171. /// <param name="factory">Function to invoke when a new, empty message is required.</param>
  172. public MessageParser(Func<T> factory) : base(() => factory())
  173. {
  174. this.factory = factory;
  175. }
  176. /// <summary>
  177. /// Creates a template instance ready for population.
  178. /// </summary>
  179. /// <returns>An empty message.</returns>
  180. internal new T CreateTemplate()
  181. {
  182. return factory();
  183. }
  184. /// <summary>
  185. /// Parses a message from a byte array.
  186. /// </summary>
  187. /// <param name="data">The byte array containing the message. Must not be null.</param>
  188. /// <returns>The newly parsed message.</returns>
  189. public new T ParseFrom(byte[] data)
  190. {
  191. T message = factory();
  192. message.MergeFrom(data);
  193. return message;
  194. }
  195. /// <summary>
  196. /// Parses a message from a byte array slice.
  197. /// </summary>
  198. /// <param name="data">The byte array containing the message. Must not be null.</param>
  199. /// <param name="offset">The offset of the slice to parse.</param>
  200. /// <param name="length">The length of the slice to parse.</param>
  201. /// <returns>The newly parsed message.</returns>
  202. public new T ParseFrom(byte[] data, int offset, int length)
  203. {
  204. T message = factory();
  205. message.MergeFrom(data, offset, length);
  206. return message;
  207. }
  208. /// <summary>
  209. /// Parses a message from the given byte string.
  210. /// </summary>
  211. /// <param name="data">The data to parse.</param>
  212. /// <returns>The parsed message.</returns>
  213. public new T ParseFrom(ByteString data)
  214. {
  215. T message = factory();
  216. message.MergeFrom(data);
  217. return message;
  218. }
  219. /// <summary>
  220. /// Parses a message from the given stream.
  221. /// </summary>
  222. /// <param name="input">The stream to parse.</param>
  223. /// <returns>The parsed message.</returns>
  224. public new T ParseFrom(Stream input)
  225. {
  226. T message = factory();
  227. message.MergeFrom(input);
  228. return message;
  229. }
  230. /// <summary>
  231. /// Parses a length-delimited message from the given stream.
  232. /// </summary>
  233. /// <remarks>
  234. /// The stream is expected to contain a length and then the data. Only the amount of data
  235. /// specified by the length will be consumed.
  236. /// </remarks>
  237. /// <param name="input">The stream to parse.</param>
  238. /// <returns>The parsed message.</returns>
  239. public new T ParseDelimitedFrom(Stream input)
  240. {
  241. T message = factory();
  242. message.MergeDelimitedFrom(input);
  243. return message;
  244. }
  245. /// <summary>
  246. /// Parses a message from the given coded input stream.
  247. /// </summary>
  248. /// <param name="input">The stream to parse.</param>
  249. /// <returns>The parsed message.</returns>
  250. public new T ParseFrom(CodedInputStream input)
  251. {
  252. T message = factory();
  253. message.MergeFrom(input);
  254. return message;
  255. }
  256. /// <summary>
  257. /// Parses a message from the given JSON.
  258. /// </summary>
  259. /// <param name="json">The JSON to parse.</param>
  260. /// <returns>The parsed message.</returns>
  261. /// <exception cref="InvalidJsonException">The JSON does not comply with RFC 7159</exception>
  262. /// <exception cref="InvalidProtocolBufferException">The JSON does not represent a Protocol Buffers message correctly</exception>
  263. public new T ParseJson(string json)
  264. {
  265. T message = factory();
  266. JsonParser.Default.Merge(message, json);
  267. return message;
  268. }
  269. }
  270. }