Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.ExtLibs/HeuristicLab.ProtobufCS/2.4.1/ProtobufCS/src/ProtocolBuffers/DynamicMessage.cs @ 13656

Last change on this file since 13656 was 8295, checked in by abeham, 12 years ago

#1897:

  • Removed protocol buffers 0.9.1
  • Added protocol buffers 2.4.1
  • Updated proto processing command
File size: 18.2 KB
Line 
1#region Copyright notice and license
2
3// Protocol Buffers - Google's data interchange format
4// Copyright 2008 Google Inc.  All rights reserved.
5// http://github.com/jskeet/dotnet-protobufs/
6// Original C++/Java/Python code:
7// http://code.google.com/p/protobuf/
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions are
11// met:
12//
13//     * Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//     * Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following disclaimer
17// in the documentation and/or other materials provided with the
18// distribution.
19//     * Neither the name of Google Inc. nor the names of its
20// contributors may be used to endorse or promote products derived from
21// this software without specific prior written permission.
22//
23// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35#endregion
36
37using System;
38using System.Collections.Generic;
39using System.IO;
40using Google.ProtocolBuffers.Descriptors;
41
42namespace Google.ProtocolBuffers
43{
44    /// <summary>
45    /// An implementation of IMessage that can represent arbitrary types, given a MessageaDescriptor.
46    /// </summary>
47    public sealed partial class DynamicMessage : AbstractMessage<DynamicMessage, DynamicMessage.Builder>
48    {
49        private readonly MessageDescriptor type;
50        private readonly FieldSet fields;
51        private readonly UnknownFieldSet unknownFields;
52        private int memoizedSize = -1;
53
54        /// <summary>
55        /// Creates a DynamicMessage with the given FieldSet.
56        /// </summary>
57        /// <param name="type"></param>
58        /// <param name="fields"></param>
59        /// <param name="unknownFields"></param>
60        private DynamicMessage(MessageDescriptor type, FieldSet fields, UnknownFieldSet unknownFields)
61        {
62            this.type = type;
63            this.fields = fields;
64            this.unknownFields = unknownFields;
65        }
66
67        /// <summary>
68        /// Returns a DynamicMessage representing the default instance of the given type.
69        /// </summary>
70        /// <param name="type"></param>
71        /// <returns></returns>
72        public static DynamicMessage GetDefaultInstance(MessageDescriptor type)
73        {
74            return new DynamicMessage(type, FieldSet.DefaultInstance, UnknownFieldSet.DefaultInstance);
75        }
76
77        /// <summary>
78        /// Parses a message of the given type from the given stream.
79        /// </summary>
80        public static DynamicMessage ParseFrom(MessageDescriptor type, ICodedInputStream input)
81        {
82            Builder builder = CreateBuilder(type);
83            Builder dynamicBuilder = builder.MergeFrom(input);
84            return dynamicBuilder.BuildParsed();
85        }
86
87        /// <summary>
88        /// Parse a message of the given type from the given stream and extension registry.
89        /// </summary>
90        /// <param name="type"></param>
91        /// <param name="input"></param>
92        /// <param name="extensionRegistry"></param>
93        /// <returns></returns>
94        public static DynamicMessage ParseFrom(MessageDescriptor type, ICodedInputStream input,
95                                               ExtensionRegistry extensionRegistry)
96        {
97            Builder builder = CreateBuilder(type);
98            Builder dynamicBuilder = builder.MergeFrom(input, extensionRegistry);
99            return dynamicBuilder.BuildParsed();
100        }
101
102        /// <summary>
103        /// Parses a message of the given type from the given stream.
104        /// </summary>
105        public static DynamicMessage ParseFrom(MessageDescriptor type, Stream input)
106        {
107            Builder builder = CreateBuilder(type);
108            Builder dynamicBuilder = builder.MergeFrom(input);
109            return dynamicBuilder.BuildParsed();
110        }
111
112        /// <summary>
113        /// Parse a message of the given type from the given stream and extension registry.
114        /// </summary>
115        /// <param name="type"></param>
116        /// <param name="input"></param>
117        /// <param name="extensionRegistry"></param>
118        /// <returns></returns>
119        public static DynamicMessage ParseFrom(MessageDescriptor type, Stream input, ExtensionRegistry extensionRegistry)
120        {
121            Builder builder = CreateBuilder(type);
122            Builder dynamicBuilder = builder.MergeFrom(input, extensionRegistry);
123            return dynamicBuilder.BuildParsed();
124        }
125
126        /// <summary>
127        /// Parse <paramref name="data"/> as a message of the given type and return it.
128        /// </summary>
129        public static DynamicMessage ParseFrom(MessageDescriptor type, ByteString data)
130        {
131            Builder builder = CreateBuilder(type);
132            Builder dynamicBuilder = builder.MergeFrom(data);
133            return dynamicBuilder.BuildParsed();
134        }
135
136        /// <summary>
137        /// Parse <paramref name="data"/> as a message of the given type and return it.
138        /// </summary>
139        public static DynamicMessage ParseFrom(MessageDescriptor type, ByteString data,
140                                               ExtensionRegistry extensionRegistry)
141        {
142            Builder builder = CreateBuilder(type);
143            Builder dynamicBuilder = builder.MergeFrom(data, extensionRegistry);
144            return dynamicBuilder.BuildParsed();
145        }
146
147        /// <summary>
148        /// Parse <paramref name="data"/> as a message of the given type and return it.
149        /// </summary>
150        public static DynamicMessage ParseFrom(MessageDescriptor type, byte[] data)
151        {
152            Builder builder = CreateBuilder(type);
153            Builder dynamicBuilder = builder.MergeFrom(data);
154            return dynamicBuilder.BuildParsed();
155        }
156
157        /// <summary>
158        /// Parse <paramref name="data"/> as a message of the given type and return it.
159        /// </summary>
160        public static DynamicMessage ParseFrom(MessageDescriptor type, byte[] data, ExtensionRegistry extensionRegistry)
161        {
162            Builder builder = CreateBuilder(type);
163            Builder dynamicBuilder = builder.MergeFrom(data, extensionRegistry);
164            return dynamicBuilder.BuildParsed();
165        }
166
167        /// <summary>
168        /// Constructs a builder for the given type.
169        /// </summary>
170        public static Builder CreateBuilder(MessageDescriptor type)
171        {
172            return new Builder(type);
173        }
174
175        /// <summary>
176        /// Constructs a builder for a message of the same type as <paramref name="prototype"/>,
177        /// and initializes it with the same contents.
178        /// </summary>
179        /// <param name="prototype"></param>
180        /// <returns></returns>
181        public static Builder CreateBuilder(IMessage prototype)
182        {
183            return new Builder(prototype.DescriptorForType).MergeFrom(prototype);
184        }
185
186        // -----------------------------------------------------------------
187        // Implementation of IMessage interface.
188
189        public override MessageDescriptor DescriptorForType
190        {
191            get { return type; }
192        }
193
194        public override DynamicMessage DefaultInstanceForType
195        {
196            get { return GetDefaultInstance(type); }
197        }
198
199        public override IDictionary<FieldDescriptor, object> AllFields
200        {
201            get { return fields.AllFieldDescriptors; }
202        }
203
204        public override bool HasField(FieldDescriptor field)
205        {
206            VerifyContainingType(field);
207            return fields.HasField(field);
208        }
209
210        public override object this[FieldDescriptor field]
211        {
212            get
213            {
214                VerifyContainingType(field);
215                object result = fields[field];
216                if (result == null)
217                {
218                    result = GetDefaultInstance(field.MessageType);
219                }
220                return result;
221            }
222        }
223
224        public override int GetRepeatedFieldCount(FieldDescriptor field)
225        {
226            VerifyContainingType(field);
227            return fields.GetRepeatedFieldCount(field);
228        }
229
230        public override object this[FieldDescriptor field, int index]
231        {
232            get
233            {
234                VerifyContainingType(field);
235                return fields[field, index];
236            }
237        }
238
239        public override UnknownFieldSet UnknownFields
240        {
241            get { return unknownFields; }
242        }
243
244        public bool Initialized
245        {
246            get { return fields.IsInitializedWithRespectTo(type.Fields); }
247        }
248
249        public override void WriteTo(ICodedOutputStream output)
250        {
251            fields.WriteTo(output);
252            if (type.Options.MessageSetWireFormat)
253            {
254                unknownFields.WriteAsMessageSetTo(output);
255            }
256            else
257            {
258                unknownFields.WriteTo(output);
259            }
260        }
261
262        public override int SerializedSize
263        {
264            get
265            {
266                int size = memoizedSize;
267                if (size != -1)
268                {
269                    return size;
270                }
271
272                size = fields.SerializedSize;
273                if (type.Options.MessageSetWireFormat)
274                {
275                    size += unknownFields.SerializedSizeAsMessageSet;
276                }
277                else
278                {
279                    size += unknownFields.SerializedSize;
280                }
281
282                memoizedSize = size;
283                return size;
284            }
285        }
286
287        public override Builder CreateBuilderForType()
288        {
289            return new Builder(type);
290        }
291
292        public override Builder ToBuilder()
293        {
294            return CreateBuilderForType().MergeFrom(this);
295        }
296
297        /// <summary>
298        /// Verifies that the field is a field of this message.
299        /// </summary>
300        private void VerifyContainingType(FieldDescriptor field)
301        {
302            if (field.ContainingType != type)
303            {
304                throw new ArgumentException("FieldDescriptor does not match message type.");
305            }
306        }
307
308        /// <summary>
309        /// Builder for dynamic messages. Instances are created with DynamicMessage.CreateBuilder.
310        /// </summary>
311        public sealed partial class Builder : AbstractBuilder<DynamicMessage, Builder>
312        {
313            private readonly MessageDescriptor type;
314            private FieldSet fields;
315            private UnknownFieldSet unknownFields;
316
317            internal Builder(MessageDescriptor type)
318            {
319                this.type = type;
320                this.fields = FieldSet.CreateInstance();
321                this.unknownFields = UnknownFieldSet.DefaultInstance;
322            }
323
324            protected override Builder ThisBuilder
325            {
326                get { return this; }
327            }
328
329            public override Builder Clear()
330            {
331                fields.Clear();
332                return this;
333            }
334
335            public override Builder MergeFrom(IMessage other)
336            {
337                if (other.DescriptorForType != type)
338                {
339                    throw new ArgumentException("MergeFrom(IMessage) can only merge messages of the same type.");
340                }
341                fields.MergeFrom(other);
342                MergeUnknownFields(other.UnknownFields);
343                return this;
344            }
345
346            public override Builder MergeFrom(DynamicMessage other)
347            {
348                IMessage downcast = other;
349                return MergeFrom(downcast);
350            }
351
352            public override DynamicMessage Build()
353            {
354                if (fields != null && !IsInitialized)
355                {
356                    throw new UninitializedMessageException(new DynamicMessage(type, fields, unknownFields));
357                }
358                return BuildPartial();
359            }
360
361            /// <summary>
362            /// Helper for DynamicMessage.ParseFrom() methods to call. Throws
363            /// InvalidProtocolBufferException
364            /// </summary>
365            /// <returns></returns>
366            internal DynamicMessage BuildParsed()
367            {
368                if (!IsInitialized)
369                {
370                    throw new UninitializedMessageException(new DynamicMessage(type, fields, unknownFields)).
371                        AsInvalidProtocolBufferException();
372                }
373                return BuildPartial();
374            }
375
376            public override DynamicMessage BuildPartial()
377            {
378                if (fields == null)
379                {
380                    throw new InvalidOperationException("Build() has already been called on this Builder.");
381                }
382                fields.MakeImmutable();
383                DynamicMessage result = new DynamicMessage(type, fields, unknownFields);
384                fields = null;
385                unknownFields = null;
386                return result;
387            }
388
389            public override Builder Clone()
390            {
391                Builder result = new Builder(type);
392                result.fields.MergeFrom(fields);
393                return result;
394            }
395
396            public override bool IsInitialized
397            {
398                get { return fields.IsInitializedWithRespectTo(type.Fields); }
399            }
400
401            public override Builder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry)
402            {
403                UnknownFieldSet.Builder unknownFieldsBuilder = UnknownFieldSet.CreateBuilder(unknownFields);
404                unknownFieldsBuilder.MergeFrom(input, extensionRegistry, this);
405                unknownFields = unknownFieldsBuilder.Build();
406                return this;
407            }
408
409            public override MessageDescriptor DescriptorForType
410            {
411                get { return type; }
412            }
413
414            public override DynamicMessage DefaultInstanceForType
415            {
416                get { return GetDefaultInstance(type); }
417            }
418
419            public override IDictionary<FieldDescriptor, object> AllFields
420            {
421                get { return fields.AllFieldDescriptors; }
422            }
423
424            public override IBuilder CreateBuilderForField(FieldDescriptor field)
425            {
426                VerifyContainingType(field);
427                if (field.MappedType != MappedType.Message)
428                {
429                    throw new ArgumentException("CreateBuilderForField is only valid for fields with message type.");
430                }
431                return new Builder(field.MessageType);
432            }
433
434            public override bool HasField(FieldDescriptor field)
435            {
436                VerifyContainingType(field);
437                return fields.HasField(field);
438            }
439
440            public override object this[FieldDescriptor field, int index]
441            {
442                get
443                {
444                    VerifyContainingType(field);
445                    return fields[field, index];
446                }
447                set
448                {
449                    VerifyContainingType(field);
450                    fields[field, index] = value;
451                }
452            }
453
454            public override object this[FieldDescriptor field]
455            {
456                get
457                {
458                    VerifyContainingType(field);
459                    object result = fields[field];
460                    if (result == null)
461                    {
462                        result = GetDefaultInstance(field.MessageType);
463                    }
464                    return result;
465                }
466                set
467                {
468                    VerifyContainingType(field);
469                    fields[field] = value;
470                }
471            }
472
473            public override Builder ClearField(FieldDescriptor field)
474            {
475                VerifyContainingType(field);
476                fields.ClearField(field);
477                return this;
478            }
479
480            public override int GetRepeatedFieldCount(FieldDescriptor field)
481            {
482                VerifyContainingType(field);
483                return fields.GetRepeatedFieldCount(field);
484            }
485
486            public override Builder AddRepeatedField(FieldDescriptor field, object value)
487            {
488                VerifyContainingType(field);
489                fields.AddRepeatedField(field, value);
490                return this;
491            }
492
493            public override UnknownFieldSet UnknownFields
494            {
495                get { return unknownFields; }
496                set { unknownFields = value; }
497            }
498
499            /// <summary>
500            /// Verifies that the field is a field of this message.
501            /// </summary>
502            /// <param name="field"></param>
503            private void VerifyContainingType(FieldDescriptor field)
504            {
505                if (field.ContainingType != type)
506                {
507                    throw new ArgumentException("FieldDescriptor does not match message type.");
508                }
509            }
510        }
511    }
512}
Note: See TracBrowser for help on using the repository browser.