blob: 68519e0f6e3cf4ee4f8e9ce93834fe91b0d149e2 [file] [log] [blame]
Jon Skeet0aac0e42009-09-09 18:48:02 +01001#region Copyright notice and license
Jon Skeetad748532009-06-25 16:55:58 +01002// 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.
Jon Skeet0aac0e42009-09-09 18:48:02 +010033#endregion
34
Jon Skeet60c059b2008-10-23 21:17:56 +010035using System;
Jon Skeet68036862008-10-22 13:30:34 +010036using System.Collections.Generic;
Jon Skeet68036862008-10-22 13:30:34 +010037using System.Collections;
38using System.IO;
39using System.Reflection;
40
41namespace Google.ProtocolBuffers {
42
43 /// <summary>
44 /// Iterates over data created using a <see cref="MessageStreamWriter{T}" />.
45 /// Unlike MessageStreamWriter, this class is not usually constructed directly with
46 /// a stream; instead it is provided with a way of opening a stream when iteration
47 /// is started. The stream is closed when the iteration is completed or the enumerator
48 /// is disposed. (This occurs naturally when using <c>foreach</c>.)
49 /// </summary>
50 public class MessageStreamIterator<TMessage> : IEnumerable<TMessage>
51 where TMessage : IMessage<TMessage> {
52
53 private readonly StreamProvider streamProvider;
54 private readonly ExtensionRegistry extensionRegistry;
Jon Skeet2178b932009-06-25 07:52:07 +010055 private readonly int sizeLimit;
Jon Skeet68036862008-10-22 13:30:34 +010056
57 /// <summary>
58 /// Delegate created via reflection trickery (once per type) to create a builder
59 /// and read a message from a CodedInputStream with it. Note that unlike in Java,
60 /// there's one static field per constructed type.
61 /// </summary>
62 private static readonly Func<CodedInputStream, ExtensionRegistry, TMessage> messageReader = BuildMessageReader();
63
64 /// <summary>
65 /// Any exception (within reason) thrown within messageReader is caught and rethrown in the constructor.
66 /// This makes life a lot simpler for the caller.
67 /// </summary>
68 private static Exception typeInitializationException;
69
70 /// <summary>
71 /// Creates the delegate later used to read messages. This is only called once per type, but to
72 /// avoid exceptions occurring at confusing times, if this fails it will set typeInitializationException
73 /// to the appropriate error and return null.
74 /// </summary>
75 private static Func<CodedInputStream, ExtensionRegistry, TMessage> BuildMessageReader() {
76 try {
77 Type builderType = FindBuilderType();
78
79 // Yes, it's redundant to find this again, but it's only the once...
80 MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", Type.EmptyTypes);
81 Delegate builderBuilder = Delegate.CreateDelegate(
82 typeof(Func<>).MakeGenericType(builderType), null, createBuilderMethod);
83
84 MethodInfo buildMethod = typeof(MessageStreamIterator<TMessage>)
85 .GetMethod("BuildImpl", BindingFlags.Static | BindingFlags.NonPublic)
86 .MakeGenericMethod(typeof(TMessage), builderType);
87
88 return (Func<CodedInputStream, ExtensionRegistry, TMessage>)Delegate.CreateDelegate(
89 typeof(Func<CodedInputStream, ExtensionRegistry, TMessage>), builderBuilder, buildMethod);
90 } catch (ArgumentException e) {
91 typeInitializationException = e;
92 } catch (InvalidOperationException e) {
93 typeInitializationException = e;
94 } catch (InvalidCastException e) {
95 // Can't see why this would happen, but best to know about it.
96 typeInitializationException = e;
97 }
98 return null;
99 }
100
101 /// <summary>
102 /// Works out the builder type for TMessage, or throws an ArgumentException to explain why it can't.
Jon Skeet68036862008-10-22 13:30:34 +0100103 /// </summary>
104 private static Type FindBuilderType() {
105 MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", Type.EmptyTypes);
106 if (createBuilderMethod == null) {
107 throw new ArgumentException("Message type " + typeof(TMessage).FullName + " has no CreateBuilder method.");
108 }
109 if (createBuilderMethod.ReturnType == typeof(void)) {
110 throw new ArgumentException("CreateBuilder method in " + typeof(TMessage).FullName + " has void return type");
111 }
112 Type builderType = createBuilderMethod.ReturnType;
113 Type messageInterface = typeof(IMessage<,>).MakeGenericType(typeof(TMessage), builderType);
114 Type builderInterface = typeof(IBuilder<,>).MakeGenericType(typeof(TMessage), builderType);
115 if (Array.IndexOf(typeof(TMessage).GetInterfaces(), messageInterface) == -1) {
116 throw new ArgumentException("Message type " + typeof(TMessage) + " doesn't implement " + messageInterface.FullName);
117 }
118 if (Array.IndexOf(builderType.GetInterfaces(), builderInterface) == -1) {
119 throw new ArgumentException("Builder type " + typeof(TMessage) + " doesn't implement " + builderInterface.FullName);
120 }
121 return builderType;
122 }
123
Jon Skeetcb8644d2009-06-17 16:09:22 +0100124// This is only ever fetched by reflection, so the compiler may
125// complain that it's unused
Jon Skeet36721732009-06-17 16:23:30 +0100126#pragma warning disable 0169
Jon Skeet68036862008-10-22 13:30:34 +0100127 /// <summary>
128 /// Method we'll use to build messageReader, with the first parameter fixed to TMessage.CreateBuilder. Note that we
129 /// have to introduce another type parameter (TMessage2) as we can't constrain TMessage for just a single method
130 /// (and we can't do it at the type level because we don't know TBuilder). However, by constraining TMessage2
131 /// to not only implement IMessage appropriately but also to derive from TMessage2, we can avoid doing a cast
132 /// for every message; the implicit reference conversion will be fine. In practice, TMessage2 and TMessage will
133 /// be the same type when we construct the generic method by reflection.
134 /// </summary>
135 private static TMessage BuildImpl<TMessage2, TBuilder>(Func<TBuilder> builderBuilder, CodedInputStream input, ExtensionRegistry registry)
136 where TBuilder : IBuilder<TMessage2, TBuilder>
137 where TMessage2 : TMessage, IMessage<TMessage2, TBuilder> {
138 TBuilder builder = builderBuilder();
139 input.ReadMessage(builder, registry);
140 return builder.Build();
Jon Skeet2178b932009-06-25 07:52:07 +0100141 }
Jon Skeetcb8644d2009-06-17 16:09:22 +0100142#pragma warning restore 0414
143
Jon Skeet68036862008-10-22 13:30:34 +0100144 private static readonly uint ExpectedTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
145
Jon Skeet2178b932009-06-25 07:52:07 +0100146 private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry, int sizeLimit) {
Jon Skeet68036862008-10-22 13:30:34 +0100147 if (messageReader == null) {
148 throw typeInitializationException;
149 }
150 this.streamProvider = streamProvider;
151 this.extensionRegistry = extensionRegistry;
Jon Skeet2178b932009-06-25 07:52:07 +0100152 this.sizeLimit = sizeLimit;
153 }
154
155 private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry)
156 : this (streamProvider, extensionRegistry, CodedInputStream.DefaultSizeLimit) {
Jon Skeet68036862008-10-22 13:30:34 +0100157 }
158
159 /// <summary>
160 /// Creates a new instance which uses the same stream provider as this one,
161 /// but the specified extension registry.
162 /// </summary>
163 public MessageStreamIterator<TMessage> WithExtensionRegistry(ExtensionRegistry newRegistry) {
Jon Skeet2178b932009-06-25 07:52:07 +0100164 return new MessageStreamIterator<TMessage>(streamProvider, newRegistry, sizeLimit);
165 }
166
167 /// <summary>
168 /// Creates a new instance which uses the same stream provider and extension registry as this one,
169 /// but with the specified size limit. Note that this must be big enough for the largest message
170 /// and the tag and size preceding it.
171 /// </summary>
172 public MessageStreamIterator<TMessage> WithSizeLimit(int newSizeLimit) {
173 return new MessageStreamIterator<TMessage>(streamProvider, extensionRegistry, newSizeLimit);
Jon Skeet68036862008-10-22 13:30:34 +0100174 }
175
176 public static MessageStreamIterator<TMessage> FromFile(string file) {
177 return new MessageStreamIterator<TMessage>(() => File.OpenRead(file), ExtensionRegistry.Empty);
178 }
179
180 public static MessageStreamIterator<TMessage> FromStreamProvider(StreamProvider streamProvider) {
181 return new MessageStreamIterator<TMessage>(streamProvider, ExtensionRegistry.Empty);
182 }
183
184 public IEnumerator<TMessage> GetEnumerator() {
185 using (Stream stream = streamProvider()) {
186 CodedInputStream input = CodedInputStream.CreateInstance(stream);
Jon Skeet2178b932009-06-25 07:52:07 +0100187 input.SetSizeLimit(sizeLimit);
Jon Skeet68036862008-10-22 13:30:34 +0100188 uint tag;
189 while ((tag = input.ReadTag()) != 0) {
190 if (tag != ExpectedTag) {
191 throw InvalidProtocolBufferException.InvalidMessageStreamTag();
192 }
193 yield return messageReader(input, extensionRegistry);
Jon Skeet2178b932009-06-25 07:52:07 +0100194 input.ResetSizeCounter();
Jon Skeet68036862008-10-22 13:30:34 +0100195 }
196 }
197 }
198
199 IEnumerator IEnumerable.GetEnumerator() {
200 return GetEnumerator();
201 }
202 }
203}