FieldSet.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://github.com/jskeet/dotnet-protobufs/
  4. // Original C++/Java/Python code:
  5. // http://code.google.com/p/protobuf/
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following disclaimer
  15. // in the documentation and/or other materials provided with the
  16. // distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived from
  19. // this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. using System;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using Google.ProtocolBuffers.Collections;
  36. using Google.ProtocolBuffers.Descriptors;
  37. namespace Google.ProtocolBuffers {
  38. /// <summary>
  39. /// A class which represents an arbitrary set of fields of some message type.
  40. /// This is used to implement DynamicMessage, and also to represent extensions
  41. /// in GeneratedMessage. This class is internal, since outside users should probably
  42. /// be using DynamicMessage.
  43. ///
  44. /// As in the Java implementation, this class goes against the rest of the framework
  45. /// in terms of mutability. Instead of having a mutable Builder class and an immutable
  46. /// FieldSet class, FieldSet just has a MakeImmutable() method. This is safe so long as
  47. /// all callers are careful not to let a mutable FieldSet escape into the open. This would
  48. /// be impossible to guarantee if this were a public class, of course.
  49. ///
  50. /// All repeated fields are stored as IList[object] even
  51. /// TODO(jonskeet): Finish this comment!
  52. /// </summary>
  53. internal sealed class FieldSet {
  54. private static readonly FieldSet defaultInstance = new FieldSet(new Dictionary<FieldDescriptor, object>()).MakeImmutable();
  55. private IDictionary<FieldDescriptor, object> fields;
  56. private FieldSet(IDictionary<FieldDescriptor, object> fields) {
  57. this.fields = fields;
  58. }
  59. public static FieldSet CreateInstance() {
  60. // Use SortedList to keep fields in the canonical order
  61. return new FieldSet(new SortedList<FieldDescriptor, object>());
  62. }
  63. /// <summary>
  64. /// Makes this FieldSet immutable, and returns it for convenience. Any
  65. /// mutable repeated fields are made immutable, as well as the map itself.
  66. /// </summary>
  67. internal FieldSet MakeImmutable() {
  68. // First check if we have any repeated values
  69. bool hasRepeats = false;
  70. foreach (object value in fields.Values) {
  71. IList<object> list = value as IList<object>;
  72. if (list != null && !list.IsReadOnly) {
  73. hasRepeats = true;
  74. break;
  75. }
  76. }
  77. if (hasRepeats) {
  78. var tmp = new SortedList<FieldDescriptor, object>();
  79. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  80. IList<object> list = entry.Value as IList<object>;
  81. tmp[entry.Key] = list == null ? entry.Value : Lists.AsReadOnly(list);
  82. }
  83. fields = tmp;
  84. }
  85. fields = Dictionaries.AsReadOnly(fields);
  86. return this;
  87. }
  88. /// <summary>
  89. /// Returns the default, immutable instance with no fields defined.
  90. /// </summary>
  91. internal static FieldSet DefaultInstance {
  92. get { return defaultInstance; }
  93. }
  94. /// <summary>
  95. /// Returns an immutable mapping of fields. Note that although the mapping itself
  96. /// is immutable, the entries may not be (i.e. any repeated values are represented by
  97. /// mutable lists). The behaviour is not specified if the contents are mutated.
  98. /// </summary>
  99. internal IDictionary<FieldDescriptor, object> AllFields {
  100. get { return Dictionaries.AsReadOnly(fields); }
  101. }
  102. /// <summary>
  103. /// See <see cref="IMessage.HasField"/>.
  104. /// </summary>
  105. public bool HasField(FieldDescriptor field) {
  106. if (field.IsRepeated) {
  107. throw new ArgumentException("HasField() can only be called on non-repeated fields.");
  108. }
  109. return fields.ContainsKey(field);
  110. }
  111. /// <summary>
  112. /// Clears all fields.
  113. /// </summary>
  114. internal void Clear() {
  115. fields.Clear();
  116. }
  117. /// <summary>
  118. /// See <see cref="IMessage.Item(FieldDescriptor)"/>
  119. /// </summary>
  120. /// <remarks>
  121. /// If the field is not set, the behaviour when fetching this property varies by field type:
  122. /// <list>
  123. /// <item>For singular message values, null is returned.</item>
  124. /// <item>For singular non-message values, the default value of the field is returned.</item>
  125. /// <item>For repeated values, an empty immutable list is returned. This will be compatible
  126. /// with IList[object], regardless of the type of the repeated item.</item>
  127. /// </list>
  128. /// This method returns null if the field is a singular message type
  129. /// and is not set; in this case it is up to the caller to fetch the
  130. /// message's default instance. For repeated fields of message types,
  131. /// an empty collection is returned. For repeated fields of non-message
  132. /// types, null is returned.
  133. /// <para />
  134. /// When setting this property, any list values are copied, and each element is checked
  135. /// to ensure it is of an appropriate type.
  136. /// </remarks>
  137. ///
  138. internal object this[FieldDescriptor field] {
  139. get {
  140. object result;
  141. if (fields.TryGetValue(field, out result)) {
  142. return result;
  143. }
  144. if (field.MappedType == MappedType.Message) {
  145. if (field.IsRepeated) {
  146. return new List<object>();
  147. } else {
  148. return null;
  149. }
  150. }
  151. return field.DefaultValue;
  152. }
  153. set {
  154. if (field.IsRepeated) {
  155. List<object> list = value as List<object>;
  156. if (list == null) {
  157. throw new ArgumentException("Wrong object type used with protocol message reflection.");
  158. }
  159. // Wrap the contents in a new list so that the caller cannot change
  160. // the list's contents after setting it.
  161. List<object> newList = new List<object>(list);
  162. foreach (object element in newList) {
  163. VerifyType(field, element);
  164. }
  165. value = newList;
  166. }
  167. else {
  168. VerifyType(field, value);
  169. }
  170. fields[field] = value;
  171. }
  172. }
  173. /// <summary>
  174. /// See <see cref="IMessage.Item(FieldDescriptor,int)" />
  175. /// </summary>
  176. internal object this[FieldDescriptor field, int index] {
  177. get {
  178. if (!field.IsRepeated) {
  179. throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
  180. }
  181. return ((IList<object>) this[field])[index];
  182. }
  183. set {
  184. if (!field.IsRepeated) {
  185. throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
  186. }
  187. VerifyType(field, value);
  188. object list;
  189. if (!fields.TryGetValue(field, out list)) {
  190. throw new ArgumentOutOfRangeException();
  191. }
  192. ((IList<object>) list)[index] = value;
  193. }
  194. }
  195. /// <summary>
  196. /// See <see cref="IBuilder{TMessage, TBuilder}.AddRepeatedField" />
  197. /// </summary>
  198. internal void AddRepeatedField(FieldDescriptor field, object value) {
  199. if (!field.IsRepeated) {
  200. throw new ArgumentException("AddRepeatedField can only be called on repeated fields.");
  201. }
  202. VerifyType(field, value);
  203. object list;
  204. if (!fields.TryGetValue(field, out list)) {
  205. list = new List<object>();
  206. fields[field] = list;
  207. }
  208. ((IList<object>) list).Add(value);
  209. }
  210. /// <summary>
  211. /// Returns an enumerator for the field map. Used to write the fields out.
  212. /// </summary>
  213. internal IEnumerator<KeyValuePair<FieldDescriptor, object>> GetEnumerator() {
  214. return fields.GetEnumerator();
  215. }
  216. /// <summary>
  217. /// See <see cref="IMessage.IsInitialized" />
  218. /// </summary>
  219. /// <remarks>
  220. /// Since FieldSet itself does not have any way of knowing about
  221. /// required fields that aren't actually present in the set, it is up
  222. /// to the caller to check for genuinely required fields. This property
  223. /// merely checks that any messages present are themselves initialized.
  224. /// </remarks>
  225. internal bool IsInitialized {
  226. get {
  227. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  228. FieldDescriptor field = entry.Key;
  229. if (field.MappedType == MappedType.Message) {
  230. if (field.IsRepeated) {
  231. foreach(IMessage message in (IEnumerable) entry.Value) {
  232. if (!message.IsInitialized) {
  233. return false;
  234. }
  235. }
  236. } else {
  237. if (!((IMessage) entry.Value).IsInitialized) {
  238. return false;
  239. }
  240. }
  241. }
  242. }
  243. return true;
  244. }
  245. }
  246. /// <summary>
  247. /// Verifies whether all the required fields in the specified message
  248. /// descriptor are present in this field set, as well as whether
  249. /// all the embedded messages are themselves initialized.
  250. /// </summary>
  251. internal bool IsInitializedWithRespectTo(MessageDescriptor type) {
  252. foreach (FieldDescriptor field in type.Fields) {
  253. if (field.IsRequired && !HasField(field)) {
  254. return false;
  255. }
  256. }
  257. return IsInitialized;
  258. }
  259. /// <summary>
  260. /// See <see cref="IBuilder{TMessage, TBuilder}.ClearField" />
  261. /// </summary>
  262. public void ClearField(FieldDescriptor field) {
  263. fields.Remove(field);
  264. }
  265. /// <summary>
  266. /// See <see cref="IMessage.GetRepeatedFieldCount" />
  267. /// </summary>
  268. public int GetRepeatedFieldCount(FieldDescriptor field) {
  269. if (!field.IsRepeated) {
  270. throw new ArgumentException("GetRepeatedFieldCount() can only be called on repeated fields.");
  271. }
  272. return ((IList<object>) this[field]).Count;
  273. }
  274. /// <summary>
  275. /// Implementation of both <c>MergeFrom</c> methods.
  276. /// </summary>
  277. /// <param name="otherFields"></param>
  278. private void MergeFields(IEnumerable<KeyValuePair<FieldDescriptor, object>> otherFields) {
  279. // Note: We don't attempt to verify that other's fields have valid
  280. // types. Doing so would be a losing battle. We'd have to verify
  281. // all sub-messages as well, and we'd have to make copies of all of
  282. // them to insure that they don't change after verification (since
  283. // the IMessage interface itself cannot enforce immutability of
  284. // implementations).
  285. // TODO(jonskeet): Provide a function somewhere called MakeDeepCopy()
  286. // which allows people to make secure deep copies of messages.
  287. foreach (KeyValuePair<FieldDescriptor, object> entry in otherFields) {
  288. FieldDescriptor field = entry.Key;
  289. object existingValue;
  290. fields.TryGetValue(field, out existingValue);
  291. if (field.IsRepeated) {
  292. if (existingValue == null) {
  293. existingValue = new List<object>();
  294. fields[field] = existingValue;
  295. }
  296. IList<object> list = (IList<object>) existingValue;
  297. foreach (object otherValue in (IEnumerable) entry.Value) {
  298. list.Add(otherValue);
  299. }
  300. } else if (field.MappedType == MappedType.Message && existingValue != null) {
  301. IMessage existingMessage = (IMessage)existingValue;
  302. IMessage merged = existingMessage.WeakCreateBuilderForType()
  303. .WeakMergeFrom(existingMessage)
  304. .WeakMergeFrom((IMessage) entry.Value)
  305. .WeakBuild();
  306. this[field] = merged;
  307. } else {
  308. this[field] = entry.Value;
  309. }
  310. }
  311. }
  312. /// <summary>
  313. /// See <see cref="IBuilder{TMessage, TBuilder}.MergeFrom(IMessage)" />
  314. /// </summary>
  315. public void MergeFrom(IMessage other) {
  316. MergeFields(other.AllFields);
  317. }
  318. /// <summary>
  319. /// Like <see cref="MergeFrom(IMessage)"/>, but merges from another <c>FieldSet</c>.
  320. /// </summary>
  321. public void MergeFrom(FieldSet other) {
  322. MergeFields(other.fields);
  323. }
  324. /// <summary>
  325. /// See <see cref="IMessage.WriteTo(CodedOutputStream)" />.
  326. /// </summary>
  327. public void WriteTo(CodedOutputStream output) {
  328. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  329. WriteField(entry.Key, entry.Value, output);
  330. }
  331. }
  332. /// <summary>
  333. /// Writes a single field to a CodedOutputStream.
  334. /// </summary>
  335. public void WriteField(FieldDescriptor field, Object value, CodedOutputStream output) {
  336. if (field.IsExtension && field.ContainingType.Options.MessageSetWireFormat) {
  337. output.WriteMessageSetExtension(field.FieldNumber, (IMessage) value);
  338. } else {
  339. if (field.IsRepeated) {
  340. foreach (object element in (IEnumerable) value) {
  341. output.WriteField(field.FieldType, field.FieldNumber, element);
  342. }
  343. } else {
  344. output.WriteField(field.FieldType, field.FieldNumber, value);
  345. }
  346. }
  347. }
  348. /// <summary>
  349. /// See <see cref="IMessage.SerializedSize" />. It's up to the caller to
  350. /// cache the resulting size if desired.
  351. /// </summary>
  352. public int SerializedSize {
  353. get {
  354. int size = 0;
  355. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  356. FieldDescriptor field = entry.Key;
  357. object value = entry.Value;
  358. if (field.IsExtension && field.ContainingType.Options.MessageSetWireFormat) {
  359. size += CodedOutputStream.ComputeMessageSetExtensionSize(field.FieldNumber, (IMessage) value);
  360. } else {
  361. if (field.IsRepeated) {
  362. foreach (object element in (IEnumerable) value) {
  363. size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element);
  364. }
  365. } else {
  366. size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, value);
  367. }
  368. }
  369. }
  370. return size;
  371. }
  372. }
  373. /// <summary>
  374. /// Verifies that the given object is of the correct type to be a valid
  375. /// value for the given field.
  376. /// </summary>
  377. /// <remarks>
  378. /// For repeated fields, this checks if the object is of the right
  379. /// element type, not whether it's a list.
  380. /// </remarks>
  381. /// <exception cref="ArgumentException">The value is not of the right type.</exception>
  382. private static void VerifyType(FieldDescriptor field, object value) {
  383. bool isValid = false;
  384. switch (field.MappedType) {
  385. case MappedType.Int32: isValid = value is int; break;
  386. case MappedType.Int64: isValid = value is long; break;
  387. case MappedType.UInt32: isValid = value is uint; break;
  388. case MappedType.UInt64: isValid = value is ulong; break;
  389. case MappedType.Single: isValid = value is float; break;
  390. case MappedType.Double: isValid = value is double; break;
  391. case MappedType.Boolean: isValid = value is bool; break;
  392. case MappedType.String: isValid = value is string; break;
  393. case MappedType.ByteString: isValid = value is ByteString; break;
  394. case MappedType.Enum:
  395. EnumValueDescriptor enumValue = value as EnumValueDescriptor;
  396. isValid = enumValue != null && enumValue.EnumDescriptor == field.EnumType;
  397. break;
  398. case MappedType.Message:
  399. IMessage messageValue = value as IMessage;
  400. isValid = messageValue != null && messageValue.DescriptorForType == field.MessageType;
  401. break;
  402. }
  403. if (!isValid) {
  404. // When chaining calls to SetField(), it can be hard to tell from
  405. // the stack trace which exact call failed, since the whole chain is
  406. // considered one line of code. So, let's make sure to include the
  407. // field name and other useful info in the exception.
  408. throw new ArgumentException("Wrong object type used with protocol message reflection. "
  409. + "Message type \"" + field.ContainingType.FullName
  410. + "\", field \"" + (field.IsExtension ? field.FullName : field.Name)
  411. + "\", value was type \"" + value.GetType().Name + "\".");
  412. }
  413. }
  414. }
  415. }