Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.ExtLibs/HeuristicLab.ProtobufCS/0.9.1/ProtobufCS/src/ProtocolBuffers/AbstractMessage.cs @ 6206

Last change on this file since 6206 was 3857, checked in by abeham, 15 years ago

#866

  • Added protobuf-csharp-port project source to ExtLibs
File size: 9.1 KB
Line 
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
35using System.Collections;
36using System.Collections.Generic;
37using System.IO;
38using Google.ProtocolBuffers.Collections;
39using Google.ProtocolBuffers.Descriptors;
40
41namespace Google.ProtocolBuffers {
42  /// <summary>
43  /// Implementation of the non-generic IMessage interface as far as possible.
44  /// </summary>
45  public abstract class AbstractMessage<TMessage, TBuilder> : IMessage<TMessage, TBuilder>
46      where TMessage : AbstractMessage<TMessage, TBuilder>
47      where TBuilder : AbstractBuilder<TMessage, TBuilder> {
48    /// <summary>
49    /// The serialized size if it's already been computed, or null
50    /// if we haven't computed it yet.
51    /// </summary>
52    private int? memoizedSize = null;
53
54    #region Unimplemented members of IMessage
55    public abstract MessageDescriptor DescriptorForType { get; }
56    public abstract IDictionary<FieldDescriptor, object> AllFields { get; }
57    public abstract bool HasField(FieldDescriptor field);
58    public abstract object this[FieldDescriptor field] { get; }
59    public abstract int GetRepeatedFieldCount(FieldDescriptor field);
60    public abstract object this[FieldDescriptor field, int index] { get; }
61    public abstract UnknownFieldSet UnknownFields { get; }
62    public abstract TMessage DefaultInstanceForType { get; }
63    public abstract TBuilder CreateBuilderForType();
64    public abstract TBuilder ToBuilder();
65    #endregion
66   
67    public IBuilder WeakCreateBuilderForType() {
68      return CreateBuilderForType();
69    }
70
71    public IBuilder WeakToBuilder() {
72      return ToBuilder();
73    }
74
75    public IMessage WeakDefaultInstanceForType {
76      get { return DefaultInstanceForType; }
77    }
78
79    public virtual bool IsInitialized {
80      get {
81        // Check that all required fields are present.
82        foreach (FieldDescriptor field in DescriptorForType.Fields) {
83          if (field.IsRequired && !HasField(field)) {
84            return false;
85          }
86        }
87
88        // Check that embedded messages are initialized.
89        foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) {
90          FieldDescriptor field = entry.Key;
91          if (field.MappedType == MappedType.Message) {
92            if (field.IsRepeated) {
93              // We know it's an IList<T>, but not the exact type - so
94              // IEnumerable is the best we can do. (C# generics aren't covariant yet.)
95              foreach (IMessage element in (IEnumerable) entry.Value) {
96                if (!element.IsInitialized) {
97                  return false;
98                }
99              }
100            } else {
101              if (!((IMessage)entry.Value).IsInitialized) {
102                return false;
103              }
104            }
105          }
106        }
107        return true;
108      }
109    }
110
111    public sealed override string ToString() {
112      return TextFormat.PrintToString(this);
113    }
114
115    public virtual void WriteTo(CodedOutputStream output) {
116      foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) {
117        FieldDescriptor field = entry.Key;
118        if (field.IsRepeated) {
119          // We know it's an IList<T>, but not the exact type - so
120          // IEnumerable is the best we can do. (C# generics aren't covariant yet.)
121          IEnumerable valueList = (IEnumerable) entry.Value;
122          if (field.IsPacked) {
123            output.WriteTag(field.FieldNumber, WireFormat.WireType.LengthDelimited);
124            int dataSize = 0;
125            foreach (object element in valueList) {
126              dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
127            }
128            output.WriteRawVarint32((uint)dataSize);
129            foreach (object element in valueList) {
130              output.WriteFieldNoTag(field.FieldType, element);
131            }
132          } else {
133            foreach (object element in valueList) {
134              output.WriteField(field.FieldType, field.FieldNumber, element);
135            }
136          }
137        } else {
138          output.WriteField(field.FieldType, field.FieldNumber, entry.Value);
139        }
140      }
141
142      UnknownFieldSet unknownFields = UnknownFields;
143      if (DescriptorForType.Options.MessageSetWireFormat) {
144        unknownFields.WriteAsMessageSetTo(output);
145      } else {
146        unknownFields.WriteTo(output);
147      }
148    }
149
150    public virtual int SerializedSize {
151      get {
152        if (memoizedSize != null) {
153          return memoizedSize.Value;
154        }
155
156        int size = 0;
157        foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) {
158          FieldDescriptor field = entry.Key;
159          if (field.IsRepeated) {
160            IEnumerable valueList = (IEnumerable) entry.Value;
161            if (field.IsPacked) {
162              int dataSize = 0;
163              foreach (object element in valueList) {
164                dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
165              }
166              size += dataSize;
167              size += CodedOutputStream.ComputeTagSize(field.FieldNumber);
168              size += CodedOutputStream.ComputeRawVarint32Size((uint)dataSize);
169            } else {
170              foreach (object element in valueList) {
171                size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element);
172              }
173            }
174          } else {
175            size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, entry.Value);
176          }
177        }
178
179        UnknownFieldSet unknownFields = UnknownFields;
180        if (DescriptorForType.Options.MessageSetWireFormat) {
181          size += unknownFields.SerializedSizeAsMessageSet;
182        } else {
183          size += unknownFields.SerializedSize;
184        }
185
186        memoizedSize = size;
187        return size;
188      }
189    }
190
191    public ByteString ToByteString() {
192      ByteString.CodedBuilder output = new ByteString.CodedBuilder(SerializedSize);
193      WriteTo(output.CodedOutput);
194      return output.Build();
195    }
196
197    public byte[] ToByteArray() {
198      byte[] result = new byte[SerializedSize];
199      CodedOutputStream output = CodedOutputStream.CreateInstance(result);
200      WriteTo(output);
201      output.CheckNoSpaceLeft();
202      return result;
203    }
204
205    public void WriteTo(Stream output) {
206      CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
207      WriteTo(codedOutput);
208      codedOutput.Flush();
209    }
210
211    public void WriteDelimitedTo(Stream output) {
212      CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
213      codedOutput.WriteRawVarint32((uint) SerializedSize);
214      WriteTo(codedOutput);
215      codedOutput.Flush();
216    }
217
218    public override bool Equals(object other) {
219      if (other == this) {
220        return true;
221      }
222      IMessage otherMessage = other as IMessage;
223      if (otherMessage == null || otherMessage.DescriptorForType != DescriptorForType) {
224        return false;
225      }
226      return Dictionaries.Equals(AllFields, otherMessage.AllFields) && UnknownFields.Equals(otherMessage.UnknownFields);
227    }
228
229    public override int GetHashCode() {
230      int hash = 41;
231      hash = (19 * hash) + DescriptorForType.GetHashCode();
232      hash = (53 * hash) + Dictionaries.GetHashCode(AllFields);
233      hash = (29 * hash) + UnknownFields.GetHashCode();
234      return hash;
235    }
236  }
237}
Note: See TracBrowser for help on using the repository browser.