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 |
|
---|
35 | using System;
|
---|
36 | using System.Collections;
|
---|
37 | using System.Collections.Generic;
|
---|
38 | using System.IO;
|
---|
39 | using System.Reflection;
|
---|
40 |
|
---|
41 | namespace 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;
|
---|
55 | private readonly int sizeLimit;
|
---|
56 |
|
---|
57 | // Type.EmptyTypes isn't present on the compact framework
|
---|
58 | private static readonly Type[] EmptyTypes = new Type[0];
|
---|
59 |
|
---|
60 | /// <summary>
|
---|
61 | /// Delegate created via reflection trickery (once per type) to create a builder
|
---|
62 | /// and read a message from a CodedInputStream with it. Note that unlike in Java,
|
---|
63 | /// there's one static field per constructed type.
|
---|
64 | /// </summary>
|
---|
65 | private static readonly Func<CodedInputStream, ExtensionRegistry, TMessage> messageReader = BuildMessageReader();
|
---|
66 |
|
---|
67 | /// <summary>
|
---|
68 | /// Any exception (within reason) thrown within messageReader is caught and rethrown in the constructor.
|
---|
69 | /// This makes life a lot simpler for the caller.
|
---|
70 | /// </summary>
|
---|
71 | private static Exception typeInitializationException;
|
---|
72 |
|
---|
73 | /// <summary>
|
---|
74 | /// Creates the delegate later used to read messages. This is only called once per type, but to
|
---|
75 | /// avoid exceptions occurring at confusing times, if this fails it will set typeInitializationException
|
---|
76 | /// to the appropriate error and return null.
|
---|
77 | /// </summary>
|
---|
78 | private static Func<CodedInputStream, ExtensionRegistry, TMessage> BuildMessageReader() {
|
---|
79 | try {
|
---|
80 | Type builderType = FindBuilderType();
|
---|
81 |
|
---|
82 | // Yes, it's redundant to find this again, but it's only the once...
|
---|
83 | MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", EmptyTypes);
|
---|
84 | Delegate builderBuilder = Delegate.CreateDelegate(
|
---|
85 | typeof(Func<>).MakeGenericType(builderType), null, createBuilderMethod);
|
---|
86 |
|
---|
87 | MethodInfo buildMethod = typeof(MessageStreamIterator<TMessage>)
|
---|
88 | .GetMethod("BuildImpl", BindingFlags.Static | BindingFlags.NonPublic)
|
---|
89 | .MakeGenericMethod(typeof(TMessage), builderType);
|
---|
90 |
|
---|
91 | return (Func<CodedInputStream, ExtensionRegistry, TMessage>)Delegate.CreateDelegate(
|
---|
92 | typeof(Func<CodedInputStream, ExtensionRegistry, TMessage>), builderBuilder, buildMethod);
|
---|
93 | }
|
---|
94 | catch (ArgumentException e) {
|
---|
95 | typeInitializationException = e;
|
---|
96 | }
|
---|
97 | catch (InvalidOperationException e) {
|
---|
98 | typeInitializationException = e;
|
---|
99 | }
|
---|
100 | catch (InvalidCastException e) {
|
---|
101 | // Can't see why this would happen, but best to know about it.
|
---|
102 | typeInitializationException = e;
|
---|
103 | }
|
---|
104 | return null;
|
---|
105 | }
|
---|
106 |
|
---|
107 | /// <summary>
|
---|
108 | /// Works out the builder type for TMessage, or throws an ArgumentException to explain why it can't.
|
---|
109 | /// </summary>
|
---|
110 | private static Type FindBuilderType() {
|
---|
111 | MethodInfo createBuilderMethod = typeof(TMessage).GetMethod("CreateBuilder", EmptyTypes);
|
---|
112 | if (createBuilderMethod == null) {
|
---|
113 | throw new ArgumentException("Message type " + typeof(TMessage).FullName + " has no CreateBuilder method.");
|
---|
114 | }
|
---|
115 | if (createBuilderMethod.ReturnType == typeof(void)) {
|
---|
116 | throw new ArgumentException("CreateBuilder method in " + typeof(TMessage).FullName + " has void return type");
|
---|
117 | }
|
---|
118 | Type builderType = createBuilderMethod.ReturnType;
|
---|
119 | Type messageInterface = typeof(IMessage<,>).MakeGenericType(typeof(TMessage), builderType);
|
---|
120 | Type builderInterface = typeof(IBuilder<,>).MakeGenericType(typeof(TMessage), builderType);
|
---|
121 | if (Array.IndexOf(typeof(TMessage).GetInterfaces(), messageInterface) == -1) {
|
---|
122 | throw new ArgumentException("Message type " + typeof(TMessage) + " doesn't implement " + messageInterface.FullName);
|
---|
123 | }
|
---|
124 | if (Array.IndexOf(builderType.GetInterfaces(), builderInterface) == -1) {
|
---|
125 | throw new ArgumentException("Builder type " + typeof(TMessage) + " doesn't implement " + builderInterface.FullName);
|
---|
126 | }
|
---|
127 | return builderType;
|
---|
128 | }
|
---|
129 |
|
---|
130 | // This is only ever fetched by reflection, so the compiler may
|
---|
131 | // complain that it's unused
|
---|
132 | #pragma warning disable 0169
|
---|
133 | /// <summary>
|
---|
134 | /// Method we'll use to build messageReader, with the first parameter fixed to TMessage.CreateBuilder. Note that we
|
---|
135 | /// have to introduce another type parameter (TMessage2) as we can't constrain TMessage for just a single method
|
---|
136 | /// (and we can't do it at the type level because we don't know TBuilder). However, by constraining TMessage2
|
---|
137 | /// to not only implement IMessage appropriately but also to derive from TMessage2, we can avoid doing a cast
|
---|
138 | /// for every message; the implicit reference conversion will be fine. In practice, TMessage2 and TMessage will
|
---|
139 | /// be the same type when we construct the generic method by reflection.
|
---|
140 | /// </summary>
|
---|
141 | private static TMessage BuildImpl<TMessage2, TBuilder>(Func<TBuilder> builderBuilder, CodedInputStream input, ExtensionRegistry registry)
|
---|
142 | where TBuilder : IBuilder<TMessage2, TBuilder>
|
---|
143 | where TMessage2 : TMessage, IMessage<TMessage2, TBuilder> {
|
---|
144 | TBuilder builder = builderBuilder();
|
---|
145 | input.ReadMessage(builder, registry);
|
---|
146 | return builder.Build();
|
---|
147 | }
|
---|
148 | #pragma warning restore 0414
|
---|
149 |
|
---|
150 | private static readonly uint ExpectedTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
|
---|
151 |
|
---|
152 | private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry, int sizeLimit) {
|
---|
153 | if (messageReader == null) {
|
---|
154 | throw typeInitializationException;
|
---|
155 | }
|
---|
156 | this.streamProvider = streamProvider;
|
---|
157 | this.extensionRegistry = extensionRegistry;
|
---|
158 | this.sizeLimit = sizeLimit;
|
---|
159 | }
|
---|
160 |
|
---|
161 | private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry)
|
---|
162 | : this(streamProvider, extensionRegistry, CodedInputStream.DefaultSizeLimit) {
|
---|
163 | }
|
---|
164 |
|
---|
165 | /// <summary>
|
---|
166 | /// Creates a new instance which uses the same stream provider as this one,
|
---|
167 | /// but the specified extension registry.
|
---|
168 | /// </summary>
|
---|
169 | public MessageStreamIterator<TMessage> WithExtensionRegistry(ExtensionRegistry newRegistry) {
|
---|
170 | return new MessageStreamIterator<TMessage>(streamProvider, newRegistry, sizeLimit);
|
---|
171 | }
|
---|
172 |
|
---|
173 | /// <summary>
|
---|
174 | /// Creates a new instance which uses the same stream provider and extension registry as this one,
|
---|
175 | /// but with the specified size limit. Note that this must be big enough for the largest message
|
---|
176 | /// and the tag and size preceding it.
|
---|
177 | /// </summary>
|
---|
178 | public MessageStreamIterator<TMessage> WithSizeLimit(int newSizeLimit) {
|
---|
179 | return new MessageStreamIterator<TMessage>(streamProvider, extensionRegistry, newSizeLimit);
|
---|
180 | }
|
---|
181 |
|
---|
182 | public static MessageStreamIterator<TMessage> FromFile(string file) {
|
---|
183 | return new MessageStreamIterator<TMessage>(() => File.OpenRead(file), ExtensionRegistry.Empty);
|
---|
184 | }
|
---|
185 |
|
---|
186 | public static MessageStreamIterator<TMessage> FromStreamProvider(StreamProvider streamProvider) {
|
---|
187 | return new MessageStreamIterator<TMessage>(streamProvider, ExtensionRegistry.Empty);
|
---|
188 | }
|
---|
189 |
|
---|
190 | public IEnumerator<TMessage> GetEnumerator() {
|
---|
191 | using (Stream stream = streamProvider()) {
|
---|
192 | CodedInputStream input = CodedInputStream.CreateInstance(stream);
|
---|
193 | input.SetSizeLimit(sizeLimit);
|
---|
194 | uint tag;
|
---|
195 | while ((tag = input.ReadTag()) != 0) {
|
---|
196 | if (tag != ExpectedTag) {
|
---|
197 | throw InvalidProtocolBufferException.InvalidMessageStreamTag();
|
---|
198 | }
|
---|
199 | yield return messageReader(input, extensionRegistry);
|
---|
200 | input.ResetSizeCounter();
|
---|
201 | }
|
---|
202 | }
|
---|
203 | }
|
---|
204 |
|
---|
205 | IEnumerator IEnumerable.GetEnumerator() {
|
---|
206 | return GetEnumerator();
|
---|
207 | }
|
---|
208 | }
|
---|
209 | }
|
---|