FieldSet.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. ///
  20. /// All repeated fields are stored as IList[object] even
  21. /// </summary>
  22. internal class FieldSet {
  23. private static readonly FieldSet defaultInstance = new FieldSet(new Dictionary<FieldDescriptor, object>()).MakeImmutable();
  24. private IDictionary<FieldDescriptor, object> fields;
  25. private FieldSet(IDictionary<FieldDescriptor, object> fields) {
  26. this.fields = fields;
  27. }
  28. public static FieldSet CreateFieldSet() {
  29. return new FieldSet(new Dictionary<FieldDescriptor, object>());
  30. }
  31. /// <summary>
  32. /// Makes this FieldSet immutable, and returns it for convenience. Any
  33. /// mutable repeated fields are made immutable, as well as the map itself.
  34. /// </summary>
  35. internal FieldSet MakeImmutable() {
  36. // First check if we have any repeated values
  37. bool hasRepeats = false;
  38. foreach (object value in fields.Values) {
  39. IList<object> list = value as IList<object>;
  40. if (list != null && !list.IsReadOnly) {
  41. hasRepeats = true;
  42. break;
  43. }
  44. }
  45. if (hasRepeats) {
  46. var tmp = new SortedList<FieldDescriptor, object>();
  47. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  48. IList<object> list = entry.Value as IList<object>;
  49. tmp[entry.Key] = list == null ? entry.Value : Lists.AsReadOnly(list);
  50. }
  51. fields = tmp;
  52. }
  53. fields = Dictionaries.AsReadOnly(fields);
  54. return this;
  55. }
  56. /// <summary>
  57. /// Returns the default, immutable instance with no fields defined.
  58. /// </summary>
  59. internal static FieldSet DefaultInstance {
  60. get { return defaultInstance; }
  61. }
  62. /// <summary>
  63. /// Returns an immutable mapping of fields. Note that although the mapping itself
  64. /// is immutable, the entries may not be (i.e. any repeated values are represented by
  65. /// mutable lists). The behaviour is not specified if the contents are mutated.
  66. /// </summary>
  67. internal IDictionary<FieldDescriptor, object> AllFields {
  68. get { return Dictionaries.AsReadOnly(fields); }
  69. }
  70. /// <summary>
  71. /// See <see cref="IMessage.HasField"/>.
  72. /// </summary>
  73. public bool HasField(FieldDescriptor field) {
  74. if (field.IsRepeated) {
  75. throw new ArgumentException("HasField() can only be called on non-repeated fields.");
  76. }
  77. return fields.ContainsKey(field);
  78. }
  79. // TODO(jonskeet): Should this be in UnknownFieldSet.Builder really? Or CodedInputStream?
  80. internal static void MergeFrom(CodedInputStream input, UnknownFieldSet.Builder unknownFields,
  81. ExtensionRegistry extensionRegistry, IBuilder builder) {
  82. while (true) {
  83. uint tag = input.ReadTag();
  84. if (tag == 0) {
  85. break;
  86. }
  87. if (!MergeFieldFrom(input, unknownFields, extensionRegistry,
  88. builder, tag)) {
  89. // end group tag
  90. break;
  91. }
  92. }
  93. }
  94. // TODO(jonskeet): Should this be in UnknownFieldSet.Builder really? Or CodedInputStream?
  95. /// <summary>
  96. /// Like <see cref="MergeFrom(CodedInputStream, UnknownFieldSet.Builder, ExtensionRegistry, IBuilder)" />
  97. /// but parses a single field.
  98. /// </summary>
  99. /// <param name="input">The input to read the field from</param>
  100. /// <param name="unknownFields">The set of unknown fields to add the newly-read field to, if it's not a known field</param>
  101. /// <param name="extensionRegistry">Registry to use when an extension field is encountered</param>
  102. /// <param name="builder">Builder to merge field into, if it's a known field</param>
  103. /// <param name="tag">The tag, which should already have been read from the input</param>
  104. /// <returns>true unless the tag is an end-group tag</returns>
  105. internal static bool MergeFieldFrom(CodedInputStream input, UnknownFieldSet.Builder unknownFields,
  106. ExtensionRegistry extensionRegistry, IBuilder builder, uint tag) {
  107. MessageDescriptor type = builder.DescriptorForType;
  108. if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart) {
  109. MergeMessageSetExtensionFromCodedStream(input, unknownFields, extensionRegistry, builder);
  110. return true;
  111. }
  112. WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
  113. int fieldNumber = WireFormat.GetTagFieldNumber(tag);
  114. FieldDescriptor field;
  115. IMessage defaultFieldInstance = null;
  116. if (type.IsExtensionNumber(fieldNumber)) {
  117. ExtensionInfo extension = extensionRegistry[type, fieldNumber];
  118. if (extension == null) {
  119. field = null;
  120. } else {
  121. field = extension.Descriptor;
  122. defaultFieldInstance = extension.DefaultInstance;
  123. }
  124. } else {
  125. field = type.FindFieldByNumber(fieldNumber);
  126. }
  127. // Unknown field or wrong wire type. Skip.
  128. if (field == null || wireType != WireFormat.FieldTypeToWireFormatMap[field.FieldType]) {
  129. return unknownFields.MergeFieldFrom(tag, input);
  130. }
  131. object value;
  132. switch (field.FieldType) {
  133. case FieldType.Group:
  134. case FieldType.Message: {
  135. IBuilder subBuilder;
  136. if (defaultFieldInstance != null) {
  137. subBuilder = defaultFieldInstance.CreateBuilderForType();
  138. } else {
  139. subBuilder = builder.CreateBuilderForField(field);
  140. }
  141. if (!field.IsRepeated) {
  142. subBuilder.MergeFrom((IMessage) builder[field]);
  143. }
  144. if (field.FieldType == FieldType.Group) {
  145. input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
  146. } else {
  147. input.ReadMessage(subBuilder, extensionRegistry);
  148. }
  149. value = subBuilder.Build();
  150. break;
  151. }
  152. case FieldType.Enum: {
  153. int rawValue = input.ReadEnum();
  154. value = field.EnumType.FindValueByNumber(rawValue);
  155. // If the number isn't recognized as a valid value for this enum,
  156. // drop it.
  157. if (value == null) {
  158. unknownFields.MergeVarintField(fieldNumber, (ulong) rawValue);
  159. return true;
  160. }
  161. break;
  162. }
  163. default:
  164. value = input.ReadPrimitiveField(field.FieldType);
  165. break;
  166. }
  167. if (field.IsRepeated) {
  168. builder.AddRepeatedField(field, value);
  169. } else {
  170. builder[field] = value;
  171. }
  172. return true;
  173. }
  174. // TODO(jonskeet): Should this be in UnknownFieldSet.Builder really? Or CodedInputStream?
  175. /// <summary>
  176. /// Called by MergeFieldFrom to parse a MessageSet extension.
  177. /// </summary>
  178. private static void MergeMessageSetExtensionFromCodedStream(CodedInputStream input,
  179. UnknownFieldSet.Builder unknownFields,
  180. ExtensionRegistry extensionRegistry,
  181. IBuilder builder) {
  182. MessageDescriptor type = builder.DescriptorForType;
  183. // The wire format for MessageSet is:
  184. // message MessageSet {
  185. // repeated group Item = 1 {
  186. // required int32 typeId = 2;
  187. // required bytes message = 3;
  188. // }
  189. // }
  190. // "typeId" is the extension's field number. The extension can only be
  191. // a message type, where "message" contains the encoded bytes of that
  192. // message.
  193. //
  194. // In practice, we will probably never see a MessageSet item in which
  195. // the message appears before the type ID, or where either field does not
  196. // appear exactly once. However, in theory such cases are valid, so we
  197. // should be prepared to accept them.
  198. int typeId = 0;
  199. ByteString rawBytes = null; // If we encounter "message" before "typeId"
  200. IBuilder subBuilder = null;
  201. FieldDescriptor field = null;
  202. while (true) {
  203. uint tag = input.ReadTag();
  204. if (tag == 0) {
  205. break;
  206. }
  207. if (tag == WireFormat.MessageSetTag.TypeID) {
  208. typeId = input.ReadInt32();
  209. // Zero is not a valid type ID.
  210. if (typeId != 0) {
  211. ExtensionInfo extension = extensionRegistry[type, typeId];
  212. if (extension != null) {
  213. field = extension.Descriptor;
  214. subBuilder = extension.DefaultInstance.CreateBuilderForType();
  215. IMessage originalMessage = (IMessage) builder[field];
  216. if (originalMessage != null) {
  217. subBuilder.MergeFrom(originalMessage);
  218. }
  219. if (rawBytes != null) {
  220. // We already encountered the message. Parse it now.
  221. // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes.
  222. // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry?
  223. subBuilder.MergeFrom(rawBytes.CreateCodedInput());
  224. rawBytes = null;
  225. }
  226. } else {
  227. // Unknown extension number. If we already saw data, put it
  228. // in rawBytes.
  229. if (rawBytes != null) {
  230. unknownFields.MergeField(typeId,
  231. UnknownField.CreateBuilder()
  232. .AddLengthDelimited(rawBytes)
  233. .Build());
  234. rawBytes = null;
  235. }
  236. }
  237. }
  238. } else if (tag == WireFormat.MessageSetTag.Message) {
  239. if (typeId == 0) {
  240. // We haven't seen a type ID yet, so we have to store the raw bytes for now.
  241. rawBytes = input.ReadBytes();
  242. } else if (subBuilder == null) {
  243. // We don't know how to parse this. Ignore it.
  244. unknownFields.MergeField(typeId,
  245. UnknownField.CreateBuilder()
  246. .AddLengthDelimited(input.ReadBytes())
  247. .Build());
  248. } else {
  249. // We already know the type, so we can parse directly from the input
  250. // with no copying. Hooray!
  251. input.ReadMessage(subBuilder, extensionRegistry);
  252. }
  253. } else {
  254. // Unknown tag. Skip it.
  255. if (!input.SkipField(tag)) {
  256. break; // end of group
  257. }
  258. }
  259. }
  260. input.CheckLastTagWas(WireFormat.MessageSetTag.ItemEnd);
  261. if (subBuilder != null) {
  262. builder[field] = subBuilder.Build();
  263. }
  264. }
  265. /// <summary>
  266. /// Clears all fields.
  267. /// </summary>
  268. internal void Clear() {
  269. fields.Clear();
  270. }
  271. /// <summary>
  272. /// See <see cref="IMessage.Item(FieldDescriptor)"/>
  273. /// </summary>
  274. /// <remarks>
  275. /// If the field is not set, the behaviour when fetching this property varies by field type:
  276. /// <list>
  277. /// <item>For singular message values, null is returned.</item>
  278. /// <item>For singular non-message values, the default value of the field is returned.</item>
  279. /// <item>For repeated values, an empty immutable list is returned. This will be compatible
  280. /// with IList[object], regardless of the type of the repeated item.</item>
  281. /// </list>
  282. /// This method returns null if the field is a singular message type
  283. /// and is not set; in this case it is up to the caller to fetch the
  284. /// message's default instance. For repeated fields of message types,
  285. /// an empty collection is returned. For repeated fields of non-message
  286. /// types, null is returned.
  287. /// <para />
  288. /// When setting this property, any list values are copied, and each element is checked
  289. /// to ensure it is of an appropriate type.
  290. /// </remarks>
  291. ///
  292. internal object this[FieldDescriptor field] {
  293. get {
  294. object result;
  295. if (fields.TryGetValue(field, out result)) {
  296. return result;
  297. }
  298. // This will just do the right thing
  299. return field.DefaultValue;
  300. }
  301. set {
  302. if (field.IsRepeated) {
  303. List<object> list = value as List<object>;
  304. if (list == null) {
  305. throw new ArgumentException("Wrong object type used with protocol message reflection.");
  306. }
  307. // Wrap the contents in a new list so that the caller cannot change
  308. // the list's contents after setting it.
  309. List<object> newList = new List<object>(list);
  310. foreach (object element in newList) {
  311. VerifyType(field, element);
  312. }
  313. value = newList;
  314. }
  315. else {
  316. VerifyType(field, value);
  317. }
  318. fields[field] = value;
  319. }
  320. }
  321. /// <summary>
  322. /// See <see cref="IMessage.Item(FieldDescriptor,int)" />
  323. /// </summary>
  324. internal object this[FieldDescriptor field, int index] {
  325. get {
  326. if (!field.IsRepeated) {
  327. throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
  328. }
  329. return ((IList<object>) this[field])[index];
  330. }
  331. set {
  332. if (!field.IsRepeated) {
  333. throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
  334. }
  335. VerifyType(field, value);
  336. object list;
  337. if (!fields.TryGetValue(field, out list)) {
  338. throw new ArgumentOutOfRangeException();
  339. }
  340. ((IList<object>) list)[index] = value;
  341. }
  342. }
  343. /// <summary>
  344. /// See <see cref="IBuilder.AddRepeatedField" />
  345. /// </summary>
  346. internal void AddRepeatedField(FieldDescriptor field, object value) {
  347. if (!field.IsRepeated) {
  348. throw new ArgumentException("AddRepeatedField can only be called on repeated fields.");
  349. }
  350. VerifyType(field, value);
  351. object list;
  352. if (!fields.TryGetValue(field, out list)) {
  353. list = new List<object>();
  354. fields[field] = list;
  355. }
  356. ((IList<object>) list).Add(value);
  357. }
  358. /// <summary>
  359. /// Returns an enumerator for the field map. Used to write the fields out.
  360. /// </summary>
  361. internal IEnumerator<KeyValuePair<FieldDescriptor, object>> GetEnumerator() {
  362. return fields.GetEnumerator();
  363. }
  364. /// <summary>
  365. /// See <see cref="IMessage.IsInitialized" />
  366. /// </summary>
  367. /// <remarks>
  368. /// Since FieldSet itself does not have any way of knowing about
  369. /// required fields that aren't actually present in the set, it is up
  370. /// to the caller to check for genuinely required fields. This property
  371. /// merely checks that any messages present are themselves initialized.
  372. /// </remarks>
  373. internal bool IsInitialized {
  374. get {
  375. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  376. FieldDescriptor field = entry.Key;
  377. if (field.MappedType == MappedType.Message) {
  378. if (field.IsRepeated) {
  379. foreach(IMessage message in (IEnumerable) entry.Value) {
  380. if (!message.IsInitialized) {
  381. return false;
  382. }
  383. }
  384. } else {
  385. if (!((IMessage) entry.Value).IsInitialized) {
  386. return false;
  387. }
  388. }
  389. }
  390. }
  391. return true;
  392. }
  393. }
  394. /// <summary>
  395. /// Verifies whether all the required fields in the specified message
  396. /// descriptor are present in this field set, as well as whether
  397. /// all the embedded messages are themselves initialized.
  398. /// </summary>
  399. internal bool IsInitializedWithRespectTo(MessageDescriptor type) {
  400. foreach (FieldDescriptor field in type.Fields) {
  401. if (field.IsRequired && !HasField(field)) {
  402. return false;
  403. }
  404. }
  405. return IsInitialized;
  406. }
  407. /// <summary>
  408. /// See <see cref="IBuilder.ClearField" />
  409. /// </summary>
  410. public void ClearField(FieldDescriptor field) {
  411. fields.Remove(field);
  412. }
  413. /// <summary>
  414. /// See <see cref="IMessage.GetRepeatedFieldCount" />
  415. /// </summary>
  416. public int GetRepeatedFieldCount(FieldDescriptor field) {
  417. if (!field.IsRepeated) {
  418. throw new ArgumentException("GetRepeatedFieldCount() can only be called on repeated fields.");
  419. }
  420. return ((IList<object>) this[field]).Count;
  421. }
  422. /// <summary>
  423. /// Implementation of both <c>MergeFrom</c> methods.
  424. /// </summary>
  425. /// <param name="otherFields"></param>
  426. private void MergeFields(IEnumerable<KeyValuePair<FieldDescriptor, object>> otherFields) {
  427. // Note: We don't attempt to verify that other's fields have valid
  428. // types. Doing so would be a losing battle. We'd have to verify
  429. // all sub-messages as well, and we'd have to make copies of all of
  430. // them to insure that they don't change after verification (since
  431. // the IMessage interface itself cannot enforce immutability of
  432. // implementations).
  433. // TODO(jonskeet): Provide a function somewhere called MakeDeepCopy()
  434. // which allows people to make secure deep copies of messages.
  435. foreach (KeyValuePair<FieldDescriptor, object> entry in otherFields) {
  436. FieldDescriptor field = entry.Key;
  437. object existingValue;
  438. fields.TryGetValue(field, out existingValue);
  439. if (field.IsRepeated) {
  440. if (existingValue == null) {
  441. existingValue = new List<object>();
  442. fields[field] = existingValue;
  443. }
  444. IList<object> list = (IList<object>) existingValue;
  445. foreach (object otherValue in (IEnumerable) entry.Value) {
  446. list.Add(otherValue);
  447. }
  448. } else if (field.MappedType == MappedType.Message && existingValue != null) {
  449. IMessage existingMessage = (IMessage)existingValue;
  450. IMessage merged = existingMessage.CreateBuilderForType()
  451. .MergeFrom(existingMessage)
  452. .MergeFrom((IMessage)entry.Value)
  453. .Build();
  454. this[field] = merged;
  455. } else {
  456. this[field] = entry.Value;
  457. }
  458. }
  459. }
  460. /// <summary>
  461. /// See <see cref="IBuilder.MergeFrom(IMessage)" />
  462. /// </summary>
  463. public void MergeFrom(IMessage other) {
  464. MergeFields(other.AllFields);
  465. }
  466. /// <summary>
  467. /// Like <see cref="MergeFrom(IMessage)"/>, but merges from another <c>FieldSet</c>.
  468. /// </summary>
  469. public void MergeFrom(FieldSet other) {
  470. MergeFields(other.fields);
  471. }
  472. /// <summary>
  473. /// See <see cref="IMessage.WriteTo(CodedOutputStream)" />.
  474. /// </summary>
  475. public void WriteTo(CodedOutputStream output) {
  476. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  477. WriteField(entry.Key, entry.Value, output);
  478. }
  479. }
  480. /// <summary>
  481. /// Writes a single field to a CodedOutputStream.
  482. /// </summary>
  483. public void WriteField(FieldDescriptor field, Object value, CodedOutputStream output) {
  484. if (field.IsExtension && field.ContainingType.Options.MessageSetWireFormat) {
  485. output.WriteMessageSetExtension(field.FieldNumber, (IMessage) value);
  486. } else {
  487. if (field.IsRepeated) {
  488. foreach (object element in (IEnumerable) value) {
  489. output.WriteField(field.FieldType, field.FieldNumber, element);
  490. }
  491. } else {
  492. output.WriteField(field.FieldType, field.FieldNumber, value);
  493. }
  494. }
  495. }
  496. /// <summary>
  497. /// See <see cref="IMessage.SerializedSize" />. It's up to the caller to
  498. /// cache the resulting size if desired.
  499. /// </summary>
  500. public int SerializedSize {
  501. get {
  502. int size = 0;
  503. foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
  504. FieldDescriptor field = entry.Key;
  505. object value = entry.Value;
  506. if (field.IsExtension && field.ContainingType.Options.MessageSetWireFormat) {
  507. size += CodedOutputStream.ComputeMessageSetExtensionSize(field.FieldNumber, (IMessage) value);
  508. } else {
  509. if (field.IsRepeated) {
  510. foreach (object element in (IEnumerable) value) {
  511. size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element);
  512. }
  513. } else {
  514. size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, value);
  515. }
  516. }
  517. }
  518. return size;
  519. }
  520. }
  521. /// <summary>
  522. /// Verifies that the given object is of the correct type to be a valid
  523. /// value for the given field.
  524. /// </summary>
  525. /// <remarks>
  526. /// For repeated fields, this checks if the object is of the right
  527. /// element type, not whether it's a list.
  528. /// </remarks>
  529. /// <exception cref="ArgumentException">The value is not of the right type.</exception>
  530. private static void VerifyType(FieldDescriptor field, object value) {
  531. bool isValid = false;
  532. switch (field.MappedType) {
  533. case MappedType.Int32: isValid = value is int; break;
  534. case MappedType.Int64: isValid = value is long; break;
  535. case MappedType.UInt32: isValid = value is uint; break;
  536. case MappedType.UInt64: isValid = value is ulong; break;
  537. case MappedType.Single: isValid = value is float; break;
  538. case MappedType.Double: isValid = value is double; break;
  539. case MappedType.Boolean: isValid = value is bool; break;
  540. case MappedType.String: isValid = value is string; break;
  541. case MappedType.ByteString: isValid = value is ByteString; break;
  542. case MappedType.Enum:
  543. EnumValueDescriptor enumValue = value as EnumValueDescriptor;
  544. isValid = enumValue != null && enumValue.EnumDescriptor == field.EnumType;
  545. break;
  546. case MappedType.Message:
  547. IMessage messageValue = value as IMessage;
  548. isValid = messageValue != null && messageValue.DescriptorForType == field.MessageType;
  549. break;
  550. }
  551. if (!isValid) {
  552. // When chaining calls to SetField(), it can be hard to tell from
  553. // the stack trace which exact call failed, since the whole chain is
  554. // considered one line of code. So, let's make sure to include the
  555. // field name and other useful info in the exception.
  556. throw new ArgumentException("Wrong object type used with protocol message reflection. "
  557. + "Message type \"" + field.ContainingType.FullName
  558. + "\", field \"" + (field.IsExtension ? field.FullName : field.Name)
  559. + "\", value was type \"" + value.GetType().Name + "\".");
  560. }
  561. }
  562. }
  563. }