FieldSet.cs 23 KB

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