AbstractMessage.cs 12 KB

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