FieldSet.cs 16 KB

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