FieldSet.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using Google.ProtocolBuffers.Descriptors;
  6. using Google.ProtocolBuffers.Collections;
  7. namespace Google.ProtocolBuffers {
  8. /// <summary>
  9. /// A class which represents an arbitrary set of fields of some message type.
  10. /// This is used to implement DynamicMessage, and also to represent extensions
  11. /// in GeneratedMessage. This class is internal, since outside users should probably
  12. /// be using DynamicMessage.
  13. ///
  14. /// As in the Java implementation, this class goes against the rest of the framework
  15. /// in terms of mutability. Instead of having a mutable Builder class and an immutable
  16. /// FieldSet class, FieldSet just has a MakeImmutable() method. This is safe so long as
  17. /// all callers are careful not to let a mutable FieldSet escape into the open. This would
  18. /// be impossible to guarantee if this were a public class, of course.
  19. /// </summary>
  20. internal class FieldSet {
  21. private static readonly FieldSet defaultInstance = new FieldSet(new Dictionary<FieldDescriptor, object>()).MakeImmutable();
  22. private IDictionary<FieldDescriptor, object> fields;
  23. private FieldSet(IDictionary<FieldDescriptor, object> fields) {
  24. this.fields = fields;
  25. }
  26. /// <summary>
  27. /// Makes this FieldSet immutable, and returns it for convenience. Any
  28. /// mutable repeated fields are made immutable, as well as the map itself.
  29. /// </summary>
  30. internal FieldSet MakeImmutable() {
  31. // First check if we have any repeated values
  32. bool hasRepeats = false;
  33. foreach (object value in fields.Values) {
  34. IList<object> list = value as IList<object>;
  35. if (list != null && !list.IsReadOnly) {
  36. hasRepeats = true;
  37. break;
  38. }
  39. }
  40. if (hasRepeats) {
  41. var tmp = new SortedList<FieldDescriptor, object>();
  42. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  43. IList<object> list = entry.Value as IList<object>;
  44. tmp[entry.Key] = list == null ? entry.Value : Lists.AsReadOnly(list);
  45. }
  46. fields = tmp;
  47. }
  48. fields = Dictionaries.AsReadOnly(fields);
  49. return this;
  50. }
  51. /// <summary>
  52. /// Returns the default, immutable instance with no fields defined.
  53. /// </summary>
  54. internal static FieldSet DefaultInstance {
  55. get { return defaultInstance; }
  56. }
  57. /// <summary>
  58. /// Returns an immutable mapping of fields. Note that although the mapping itself
  59. /// is immutable, the entries may not be (i.e. any repeated values are represented by
  60. /// mutable lists). The behaviour is not specified if the contents are mutated.
  61. /// </summary>
  62. internal IDictionary<FieldDescriptor, object> AllFields {
  63. get { return Dictionaries.AsReadOnly(fields); }
  64. }
  65. /// <summary>
  66. /// See <see cref="IMessage.HasField"/>.
  67. /// </summary>
  68. public bool HasField(FieldDescriptor field) {
  69. if (field.IsRepeated) {
  70. throw new ArgumentException("HasField() can only be called on non-repeated fields.");
  71. }
  72. return fields.ContainsKey(field);
  73. }
  74. // TODO(jonskeet): Should this be in UnknownFieldSet.Builder really?
  75. internal static void MergeFrom(CodedInputStream input,
  76. UnknownFieldSet.Builder unknownFields,
  77. ExtensionRegistry extensionRegistry,
  78. IBuilder builder) {
  79. while (true) {
  80. uint tag = input.ReadTag();
  81. if (tag == 0) {
  82. break;
  83. }
  84. if (!MergeFieldFrom(input, unknownFields, extensionRegistry,
  85. builder, tag)) {
  86. // end group tag
  87. break;
  88. }
  89. }
  90. }
  91. // TODO(jonskeet): Should this be in UnknownFieldSet.Builder really?
  92. internal static bool MergeFieldFrom(CodedInputStream input,
  93. UnknownFieldSet.Builder unknownFields,
  94. ExtensionRegistry extensionRegistry,
  95. IBuilder builder,
  96. uint tag) {
  97. throw new NotImplementedException();
  98. }
  99. /// <summary>
  100. /// Clears all fields.
  101. /// </summary>
  102. internal void Clear() {
  103. fields.Clear();
  104. }
  105. /// <summary>
  106. /// <see cref="IMessage.Item(FieldDescriptor)"/>
  107. /// </summary>
  108. /// <remarks>
  109. /// If the field is not set, the behaviour when fetching this property varies by field type:
  110. /// <list>
  111. /// <item>For singular message values, null is returned.</item>
  112. /// <item>For singular non-message values, the default value of the field is returned.</item>
  113. /// <item>For repeated values, an empty immutable list is returned.</item>
  114. /// </list>
  115. /// This method returns null if the field is a singular message type
  116. /// and is not set; in this case it is up to the caller to fetch the
  117. /// message's default instance. For repeated fields of message types,
  118. /// an empty collection is returned. For repeated fields of non-message
  119. /// types, null is returned.
  120. /// <para />
  121. /// When setting this property, any list values are copied, and each element is checked
  122. /// to ensure it is of an appropriate type.
  123. /// </remarks>
  124. ///
  125. internal object this[FieldDescriptor field] {
  126. get {
  127. object result;
  128. if (fields.TryGetValue(field, out result)) {
  129. return result;
  130. }
  131. // This will just do the right thing
  132. return field.DefaultValue;
  133. }
  134. set {
  135. if (field.IsRepeated) {
  136. List<object> list = value as List<object>;
  137. if (list == null) {
  138. throw new ArgumentException("Wrong object type used with protocol message reflection.");
  139. }
  140. // Wrap the contents in a new list so that the caller cannot change
  141. // the list's contents after setting it.
  142. List<object> newList = new List<object>(list);
  143. foreach (object element in newList) {
  144. VerifyType(field, element);
  145. }
  146. value = newList;
  147. }
  148. else {
  149. VerifyType(field, value);
  150. }
  151. fields[field] = value;
  152. }
  153. }
  154. /// <summary>
  155. /// <see cref="IMessage.Item(FieldDescriptor,int)" />
  156. /// </summary>
  157. internal object this[FieldDescriptor field, int index] {
  158. get {
  159. if (!field.IsRepeated) {
  160. throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
  161. }
  162. return ((List<object>)this[field])[index];
  163. }
  164. set {
  165. if (!field.IsRepeated) {
  166. throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
  167. }
  168. VerifyType(field, value);
  169. object list;
  170. if (!fields.TryGetValue(field, out list)) {
  171. throw new ArgumentOutOfRangeException();
  172. }
  173. ((List<object>) list)[index] = value;
  174. }
  175. }
  176. /// <summary>
  177. /// <see cref="IBuilder.AddRepeatedField" />
  178. /// </summary>
  179. /// <param name="field"></param>
  180. /// <param name="value"></param>
  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. ((List<object>) list).Add(value);
  192. }
  193. /// <summary>
  194. /// <see cref="IMessage.IsInitialized" />
  195. /// </summary>
  196. /// <remarks>
  197. /// Since FieldSet itself does not have any way of knowing about
  198. /// required fields that aren't actually present in the set, it is up
  199. /// to the caller to check for genuinely required fields. This property
  200. /// merely checks that any messages present are themselves initialized.
  201. /// </remarks>
  202. internal bool IsInitialized {
  203. get {
  204. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  205. FieldDescriptor field = entry.Key;
  206. if (field.MappedType == MappedType.Message) {
  207. if (field.IsRepeated) {
  208. foreach(IMessage message in (IEnumerable) entry.Value) {
  209. if (!message.IsInitialized) {
  210. return false;
  211. }
  212. }
  213. } else {
  214. if (!((IMessage) entry.Value).IsInitialized) {
  215. return false;
  216. }
  217. }
  218. }
  219. }
  220. return true;
  221. }
  222. }
  223. /// <summary>
  224. /// Verifies whether all the required fields in the specified message
  225. /// descriptor are present in this field set, as well as whether
  226. /// all the embedded messages are themselves initialized.
  227. /// </summary>
  228. internal bool IsInitializedWithRespectTo(MessageDescriptor type) {
  229. foreach (FieldDescriptor field in type.Fields) {
  230. if (field.IsRequired && !HasField(field)) {
  231. return false;
  232. }
  233. }
  234. return IsInitialized;
  235. }
  236. /// <summary>
  237. /// <see cref="IBuilder.ClearField" />
  238. /// </summary>
  239. public void ClearField(FieldDescriptor field) {
  240. fields.Remove(field);
  241. }
  242. /// <summary>
  243. /// <see cref="IMessage.GetRepeatedFieldCount" />
  244. /// </summary>
  245. public int GetRepeatedFieldCount(FieldDescriptor field) {
  246. if (!field.IsRepeated) {
  247. throw new ArgumentException("GetRepeatedFieldCount() can only be called on repeated fields.");
  248. }
  249. return ((List<object>) this[field]).Count;
  250. }
  251. /// <summary>
  252. /// Verifies that the given object is of the correct type to be a valid
  253. /// value for the given field.
  254. /// </summary>
  255. /// <remarks>
  256. /// For repeated fields, this checks if the object is of the right
  257. /// element type, not whether it's a list.
  258. /// </remarks>
  259. /// <exception cref="ArgumentException">The value is not of the right type.</exception>
  260. private static void VerifyType(FieldDescriptor field, object value) {
  261. bool isValid = false;
  262. switch (field.MappedType) {
  263. case MappedType.Int32: isValid = value is int; break;
  264. case MappedType.Int64: isValid = value is long; break;
  265. case MappedType.UInt32: isValid = value is uint; break;
  266. case MappedType.UInt64: isValid = value is ulong; break;
  267. case MappedType.Single: isValid = value is float; break;
  268. case MappedType.Double: isValid = value is double; break;
  269. case MappedType.Boolean: isValid = value is bool; break;
  270. case MappedType.String: isValid = value is string; break;
  271. case MappedType.ByteString: isValid = value is ByteString; break;
  272. case MappedType.Enum:
  273. EnumValueDescriptor enumValue = value as EnumValueDescriptor;
  274. isValid = enumValue != null && enumValue.EnumDescriptor == field.EnumType;
  275. break;
  276. case MappedType.Message:
  277. IMessage messageValue = value as IMessage;
  278. isValid = messageValue != null && messageValue.DescriptorForType == field.MessageType;
  279. break;
  280. }
  281. if (!isValid) {
  282. // When chaining calls to SetField(), it can be hard to tell from
  283. // the stack trace which exact call failed, since the whole chain is
  284. // considered one line of code. So, let's make sure to include the
  285. // field name and other useful info in the exception.
  286. throw new ArgumentException("Wrong object type used with protocol message reflection. "
  287. + "Message type \"" + field.ContainingType.FullName
  288. + "\", field \"" + (field.IsExtension ? field.FullName : field.Name)
  289. + "\", value was type \"" + value.GetType().Name + "\".");
  290. }
  291. }
  292. }
  293. }