FieldSet.cs 16 KB

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