MessageStreamIterator.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // http://github.com/jskeet/dotnet-protobufs/
  5. // Original C++/Java/Python code:
  6. // http://code.google.com/p/protobuf/
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions are
  10. // met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. // * Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following disclaimer
  16. // in the documentation and/or other materials provided with the
  17. // distribution.
  18. // * Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived from
  20. // this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #endregion
  34. using System;
  35. using System.Collections.Generic;
  36. using System.Collections;
  37. using System.IO;
  38. using System.Reflection;
  39. namespace Google.ProtocolBuffers {
  40. /// <summary>
  41. /// Iterates over data created using a <see cref="MessageStreamWriter{T}" />.
  42. /// Unlike MessageStreamWriter, this class is not usually constructed directly with
  43. /// a stream; instead it is provided with a way of opening a stream when iteration
  44. /// is started. The stream is closed when the iteration is completed or the enumerator
  45. /// is disposed. (This occurs naturally when using <c>foreach</c>.)
  46. /// </summary>
  47. public class MessageStreamIterator<TMessage> : IEnumerable<TMessage>
  48. where TMessage : IMessage<TMessage> {
  49. private readonly StreamProvider streamProvider;
  50. private readonly ExtensionRegistry extensionRegistry;
  51. private readonly int sizeLimit;
  52. // Type.EmptyTypes isn't present on the compact framework
  53. private static readonly Type[] EmptyTypes = new Type[0];
  54. /// <summary>
  55. /// Delegate created via reflection trickery (once per type) to create a builder
  56. /// and read a message from a CodedInputStream with it. Note that unlike in Java,
  57. /// there's one static field per constructed type.
  58. /// </summary>
  59. private static readonly Func<CodedInputStream, ExtensionRegistry, TMessage> messageReader = BuildMessageReader();
  60. /// <summary>
  61. /// Any exception (within reason) thrown within messageReader is caught and rethrown in the constructor.
  62. /// This makes life a lot simpler for the caller.
  63. /// </summary>
  64. private static Exception typeInitializationException;
  65. /// <summary>
  66. /// Creates the delegate later used to read messages. This is only called once per type, but to
  67. /// avoid exceptions occurring at confusing times, if this fails it will set typeInitializationException
  68. /// to the appropriate error and return null.
  69. /// </summary>
  70. private static Func<CodedInputStream, ExtensionRegistry, TMessage> BuildMessageReader() {
  71. try {
  72. Type builderType = FindBuilderType();
  73. // Yes, it's redundant to find this again, but it's only the once...
  74. MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", EmptyTypes);
  75. Delegate builderBuilder = Delegate.CreateDelegate(
  76. typeof(Func<>).MakeGenericType(builderType), null, createBuilderMethod);
  77. MethodInfo buildMethod = typeof(MessageStreamIterator<TMessage>)
  78. .GetMethod("BuildImpl", BindingFlags.Static | BindingFlags.NonPublic)
  79. .MakeGenericMethod(typeof(TMessage), builderType);
  80. return (Func<CodedInputStream, ExtensionRegistry, TMessage>)Delegate.CreateDelegate(
  81. typeof(Func<CodedInputStream, ExtensionRegistry, TMessage>), builderBuilder, buildMethod);
  82. } catch (ArgumentException e) {
  83. typeInitializationException = e;
  84. } catch (InvalidOperationException e) {
  85. typeInitializationException = e;
  86. } catch (InvalidCastException e) {
  87. // Can't see why this would happen, but best to know about it.
  88. typeInitializationException = e;
  89. }
  90. return null;
  91. }
  92. /// <summary>
  93. /// Works out the builder type for TMessage, or throws an ArgumentException to explain why it can't.
  94. /// </summary>
  95. private static Type FindBuilderType() {
  96. MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", EmptyTypes);
  97. if (createBuilderMethod == null) {
  98. throw new ArgumentException("Message type " + typeof(TMessage).FullName + " has no CreateBuilder method.");
  99. }
  100. if (createBuilderMethod.ReturnType == typeof(void)) {
  101. throw new ArgumentException("CreateBuilder method in " + typeof(TMessage).FullName + " has void return type");
  102. }
  103. Type builderType = createBuilderMethod.ReturnType;
  104. Type messageInterface = typeof(IMessage<,>).MakeGenericType(typeof(TMessage), builderType);
  105. Type builderInterface = typeof(IBuilder<,>).MakeGenericType(typeof(TMessage), builderType);
  106. if (Array.IndexOf(typeof(TMessage).GetInterfaces(), messageInterface) == -1) {
  107. throw new ArgumentException("Message type " + typeof(TMessage) + " doesn't implement " + messageInterface.FullName);
  108. }
  109. if (Array.IndexOf(builderType.GetInterfaces(), builderInterface) == -1) {
  110. throw new ArgumentException("Builder type " + typeof(TMessage) + " doesn't implement " + builderInterface.FullName);
  111. }
  112. return builderType;
  113. }
  114. // This is only ever fetched by reflection, so the compiler may
  115. // complain that it's unused
  116. #pragma warning disable 0169
  117. /// <summary>
  118. /// Method we'll use to build messageReader, with the first parameter fixed to TMessage.CreateBuilder. Note that we
  119. /// have to introduce another type parameter (TMessage2) as we can't constrain TMessage for just a single method
  120. /// (and we can't do it at the type level because we don't know TBuilder). However, by constraining TMessage2
  121. /// to not only implement IMessage appropriately but also to derive from TMessage2, we can avoid doing a cast
  122. /// for every message; the implicit reference conversion will be fine. In practice, TMessage2 and TMessage will
  123. /// be the same type when we construct the generic method by reflection.
  124. /// </summary>
  125. private static TMessage BuildImpl<TMessage2, TBuilder>(Func<TBuilder> builderBuilder, CodedInputStream input, ExtensionRegistry registry)
  126. where TBuilder : IBuilder<TMessage2, TBuilder>
  127. where TMessage2 : TMessage, IMessage<TMessage2, TBuilder> {
  128. TBuilder builder = builderBuilder();
  129. input.ReadMessage(builder, registry);
  130. return builder.Build();
  131. }
  132. #pragma warning restore 0414
  133. private static readonly uint ExpectedTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  134. private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry, int sizeLimit) {
  135. if (messageReader == null) {
  136. throw typeInitializationException;
  137. }
  138. this.streamProvider = streamProvider;
  139. this.extensionRegistry = extensionRegistry;
  140. this.sizeLimit = sizeLimit;
  141. }
  142. private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry)
  143. : this (streamProvider, extensionRegistry, CodedInputStream.DefaultSizeLimit) {
  144. }
  145. /// <summary>
  146. /// Creates a new instance which uses the same stream provider as this one,
  147. /// but the specified extension registry.
  148. /// </summary>
  149. public MessageStreamIterator<TMessage> WithExtensionRegistry(ExtensionRegistry newRegistry) {
  150. return new MessageStreamIterator<TMessage>(streamProvider, newRegistry, sizeLimit);
  151. }
  152. /// <summary>
  153. /// Creates a new instance which uses the same stream provider and extension registry as this one,
  154. /// but with the specified size limit. Note that this must be big enough for the largest message
  155. /// and the tag and size preceding it.
  156. /// </summary>
  157. public MessageStreamIterator<TMessage> WithSizeLimit(int newSizeLimit) {
  158. return new MessageStreamIterator<TMessage>(streamProvider, extensionRegistry, newSizeLimit);
  159. }
  160. public static MessageStreamIterator<TMessage> FromFile(string file) {
  161. return new MessageStreamIterator<TMessage>(() => File.OpenRead(file), ExtensionRegistry.Empty);
  162. }
  163. public static MessageStreamIterator<TMessage> FromStreamProvider(StreamProvider streamProvider) {
  164. return new MessageStreamIterator<TMessage>(streamProvider, ExtensionRegistry.Empty);
  165. }
  166. public IEnumerator<TMessage> GetEnumerator() {
  167. using (Stream stream = streamProvider()) {
  168. CodedInputStream input = CodedInputStream.CreateInstance(stream);
  169. input.SetSizeLimit(sizeLimit);
  170. uint tag;
  171. while ((tag = input.ReadTag()) != 0) {
  172. if (tag != ExpectedTag) {
  173. throw InvalidProtocolBufferException.InvalidMessageStreamTag();
  174. }
  175. yield return messageReader(input, extensionRegistry);
  176. input.ResetSizeCounter();
  177. }
  178. }
  179. }
  180. IEnumerator IEnumerable.GetEnumerator() {
  181. return GetEnumerator();
  182. }
  183. }
  184. }