FieldSet.cs 23 KB

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