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