AbstractMessage.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. using System.Collections;
  35. using System.Collections.Generic;
  36. using System.IO;
  37. using System.Text;
  38. using Google.ProtocolBuffers.Collections;
  39. using Google.ProtocolBuffers.Descriptors;
  40. namespace Google.ProtocolBuffers
  41. {
  42. /// <summary>
  43. /// Implementation of the non-generic IMessage interface as far as possible.
  44. /// </summary>
  45. public abstract partial class AbstractMessage<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>,
  46. IMessage<TMessage, TBuilder>
  47. where TMessage : AbstractMessage<TMessage, TBuilder>
  48. where TBuilder : AbstractBuilder<TMessage, TBuilder>
  49. {
  50. /// <summary>
  51. /// The serialized size if it's already been computed, or null
  52. /// if we haven't computed it yet.
  53. /// </summary>
  54. private int? memoizedSize = null;
  55. #region Unimplemented members of IMessage
  56. public abstract MessageDescriptor DescriptorForType { get; }
  57. public abstract IDictionary<FieldDescriptor, object> AllFields { get; }
  58. public abstract bool HasField(FieldDescriptor field);
  59. public abstract bool HasOneof(OneofDescriptor oneof);
  60. public abstract FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof);
  61. public abstract object this[FieldDescriptor field] { get; }
  62. public abstract int GetRepeatedFieldCount(FieldDescriptor field);
  63. public abstract object this[FieldDescriptor field, int index] { get; }
  64. public abstract UnknownFieldSet UnknownFields { get; }
  65. #endregion
  66. /// <summary>
  67. /// Returns true iff all required fields in the message and all embedded
  68. /// messages are set.
  69. /// </summary>
  70. public override bool IsInitialized
  71. {
  72. get
  73. {
  74. // Check that all required fields are present.
  75. foreach (FieldDescriptor field in DescriptorForType.Fields)
  76. {
  77. if (field.IsRequired && !HasField(field))
  78. {
  79. return false;
  80. }
  81. }
  82. // Check that embedded messages are initialized.
  83. foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
  84. {
  85. FieldDescriptor field = entry.Key;
  86. if (field.MappedType == MappedType.Message)
  87. {
  88. if (field.IsRepeated)
  89. {
  90. // We know it's an IList<T>, but not the exact type - so
  91. // IEnumerable is the best we can do. (C# generics aren't covariant yet.)
  92. foreach (IMessageLite element in (IEnumerable) entry.Value)
  93. {
  94. if (!element.IsInitialized)
  95. {
  96. return false;
  97. }
  98. }
  99. }
  100. else
  101. {
  102. if (!((IMessageLite) entry.Value).IsInitialized)
  103. {
  104. return false;
  105. }
  106. }
  107. }
  108. }
  109. return true;
  110. }
  111. }
  112. public override sealed string ToString()
  113. {
  114. return TextFormat.PrintToString(this);
  115. }
  116. public override sealed void PrintTo(TextWriter writer)
  117. {
  118. TextFormat.Print(this, writer);
  119. }
  120. /// <summary>
  121. /// Serializes the message and writes it to the given output stream.
  122. /// This does not flush or close the stream.
  123. /// </summary>
  124. /// <remarks>
  125. /// Protocol Buffers are not self-delimiting. Therefore, if you write
  126. /// any more data to the stream after the message, you must somehow ensure
  127. /// that the parser on the receiving end does not interpret this as being
  128. /// part of the protocol message. One way of doing this is by writing the size
  129. /// of the message before the data, then making sure you limit the input to
  130. /// that size when receiving the data. Alternatively, use WriteDelimitedTo(Stream).
  131. /// </remarks>
  132. public override void WriteTo(ICodedOutputStream output)
  133. {
  134. foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
  135. {
  136. FieldDescriptor field = entry.Key;
  137. if (field.IsRepeated)
  138. {
  139. // We know it's an IList<T>, but not the exact type - so
  140. // IEnumerable is the best we can do. (C# generics aren't covariant yet.)
  141. IEnumerable valueList = (IEnumerable) entry.Value;
  142. if (field.IsPacked)
  143. {
  144. output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList);
  145. }
  146. else
  147. {
  148. output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList);
  149. }
  150. }
  151. else
  152. {
  153. output.WriteField(field.FieldType, field.FieldNumber, field.Name, entry.Value);
  154. }
  155. }
  156. UnknownFieldSet unknownFields = UnknownFields;
  157. if (DescriptorForType.Options.MessageSetWireFormat)
  158. {
  159. unknownFields.WriteAsMessageSetTo(output);
  160. }
  161. else
  162. {
  163. unknownFields.WriteTo(output);
  164. }
  165. }
  166. /// <summary>
  167. /// Returns the number of bytes required to encode this message.
  168. /// The result is only computed on the first call and memoized after that.
  169. /// </summary>
  170. public override int SerializedSize
  171. {
  172. get
  173. {
  174. if (memoizedSize != null)
  175. {
  176. return memoizedSize.Value;
  177. }
  178. int size = 0;
  179. foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
  180. {
  181. FieldDescriptor field = entry.Key;
  182. if (field.IsRepeated)
  183. {
  184. IEnumerable valueList = (IEnumerable) entry.Value;
  185. if (field.IsPacked)
  186. {
  187. int dataSize = 0;
  188. foreach (object element in valueList)
  189. {
  190. dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
  191. }
  192. size += dataSize;
  193. size += CodedOutputStream.ComputeTagSize(field.FieldNumber);
  194. size += CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);
  195. }
  196. else
  197. {
  198. foreach (object element in valueList)
  199. {
  200. size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element);
  201. }
  202. }
  203. }
  204. else
  205. {
  206. size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, entry.Value);
  207. }
  208. }
  209. UnknownFieldSet unknownFields = UnknownFields;
  210. if (DescriptorForType.Options.MessageSetWireFormat)
  211. {
  212. size += unknownFields.SerializedSizeAsMessageSet;
  213. }
  214. else
  215. {
  216. size += unknownFields.SerializedSize;
  217. }
  218. memoizedSize = size;
  219. return size;
  220. }
  221. }
  222. /// <summary>
  223. /// Compares the specified object with this message for equality.
  224. /// Returns true iff the given object is a message of the same type
  225. /// (as defined by DescriptorForType) and has identical values
  226. /// for all its fields.
  227. /// </summary>
  228. public override bool Equals(object other)
  229. {
  230. if (other == this)
  231. {
  232. return true;
  233. }
  234. IMessage otherMessage = other as IMessage;
  235. if (otherMessage == null || otherMessage.DescriptorForType != DescriptorForType)
  236. {
  237. return false;
  238. }
  239. return Dictionaries.Equals(AllFields, otherMessage.AllFields) &&
  240. UnknownFields.Equals(otherMessage.UnknownFields);
  241. }
  242. /// <summary>
  243. /// Returns the hash code value for this message.
  244. /// TODO(jonskeet): Specify the hash algorithm, but better than the Java one!
  245. /// </summary>
  246. public override int GetHashCode()
  247. {
  248. int hash = 41;
  249. hash = (19*hash) + DescriptorForType.GetHashCode();
  250. hash = (53*hash) + Dictionaries.GetHashCode(AllFields);
  251. hash = (29*hash) + UnknownFields.GetHashCode();
  252. return hash;
  253. }
  254. #region Explicit Members
  255. IBuilder IMessage.WeakCreateBuilderForType()
  256. {
  257. return CreateBuilderForType();
  258. }
  259. IBuilder IMessage.WeakToBuilder()
  260. {
  261. return ToBuilder();
  262. }
  263. IMessage IMessage.WeakDefaultInstanceForType
  264. {
  265. get { return DefaultInstanceForType; }
  266. }
  267. #endregion
  268. }
  269. }