FieldSet.cs 24 KB

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