ValueMember.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. #if !NO_RUNTIME
  2. using System;
  3. using ProtoBuf.Serializers;
  4. using System.Globalization;
  5. using System.Collections.Generic;
  6. #if FEAT_IKVM
  7. using Type = IKVM.Reflection.Type;
  8. using IKVM.Reflection;
  9. #else
  10. using System.Reflection;
  11. #endif
  12. namespace ProtoBuf.Meta
  13. {
  14. /// <summary>
  15. /// Represents a member (property/field) that is mapped to a protobuf field
  16. /// </summary>
  17. public class ValueMember
  18. {
  19. private readonly int fieldNumber;
  20. /// <summary>
  21. /// The number that identifies this member in a protobuf stream
  22. /// </summary>
  23. public int FieldNumber { get { return fieldNumber; } }
  24. private readonly MemberInfo originalMember;
  25. private MemberInfo backingMember;
  26. /// <summary>
  27. /// Gets the member (field/property) which this member relates to.
  28. /// </summary>
  29. public MemberInfo Member { get { return originalMember; } }
  30. /// <summary>
  31. /// Gets the backing member (field/property) which this member relates to
  32. /// </summary>
  33. public MemberInfo BackingMember
  34. {
  35. get { return backingMember; }
  36. set
  37. {
  38. if(backingMember != value)
  39. {
  40. ThrowIfFrozen();
  41. backingMember = value;
  42. }
  43. }
  44. }
  45. private readonly Type parentType, itemType, defaultType, memberType;
  46. private object defaultValue;
  47. /// <summary>
  48. /// Within a list / array / etc, the type of object for each item in the list (especially useful with ArrayList)
  49. /// </summary>
  50. public Type ItemType { get { return itemType; } }
  51. /// <summary>
  52. /// The underlying type of the member
  53. /// </summary>
  54. public Type MemberType { get { return memberType; } }
  55. /// <summary>
  56. /// For abstract types (IList etc), the type of concrete object to create (if required)
  57. /// </summary>
  58. public Type DefaultType { get { return defaultType; } }
  59. /// <summary>
  60. /// The type the defines the member
  61. /// </summary>
  62. public Type ParentType { get { return parentType; } }
  63. /// <summary>
  64. /// The default value of the item (members with this value will not be serialized)
  65. /// </summary>
  66. public object DefaultValue
  67. {
  68. get { return defaultValue; }
  69. set {
  70. if (defaultValue != value)
  71. {
  72. ThrowIfFrozen();
  73. defaultValue = value;
  74. }
  75. }
  76. }
  77. private readonly RuntimeTypeModel model;
  78. /// <summary>
  79. /// Creates a new ValueMember instance
  80. /// </summary>
  81. public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue)
  82. : this(model, fieldNumber,memberType, itemType, defaultType, dataFormat)
  83. {
  84. if (member == null) throw new ArgumentNullException("member");
  85. if (parentType == null) throw new ArgumentNullException("parentType");
  86. if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
  87. this.originalMember = member;
  88. this.parentType = parentType;
  89. if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber");
  90. //#if WINRT
  91. if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType)
  92. //#else
  93. // if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue))
  94. //#endif
  95. {
  96. defaultValue = ParseDefaultValue(memberType, defaultValue);
  97. }
  98. this.defaultValue = defaultValue;
  99. MetaType type = model.FindWithoutAdd(memberType);
  100. if (type != null)
  101. {
  102. AsReference = type.AsReferenceDefault;
  103. }
  104. else
  105. { // we need to scan the hard way; can't risk recursion by fully walking it
  106. AsReference = MetaType.GetAsReferenceDefault(model, memberType);
  107. }
  108. }
  109. /// <summary>
  110. /// Creates a new ValueMember instance
  111. /// </summary>
  112. internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat)
  113. {
  114. if (memberType == null) throw new ArgumentNullException("memberType");
  115. if (model == null) throw new ArgumentNullException("model");
  116. this.fieldNumber = fieldNumber;
  117. this.memberType = memberType;
  118. this.itemType = itemType;
  119. this.defaultType = defaultType;
  120. this.model = model;
  121. this.dataFormat = dataFormat;
  122. }
  123. internal object GetRawEnumValue()
  124. {
  125. #if WINRT || PORTABLE || CF || FX11 || COREFX
  126. object value = ((FieldInfo)originalMember).GetValue(null);
  127. switch(Helpers.GetTypeCode(Enum.GetUnderlyingType(((FieldInfo)originalMember).FieldType)))
  128. {
  129. case ProtoTypeCode.SByte: return (sbyte)value;
  130. case ProtoTypeCode.Byte: return (byte)value;
  131. case ProtoTypeCode.Int16: return (short)value;
  132. case ProtoTypeCode.UInt16: return (ushort)value;
  133. case ProtoTypeCode.Int32: return (int)value;
  134. case ProtoTypeCode.UInt32: return (uint)value;
  135. case ProtoTypeCode.Int64: return (long)value;
  136. case ProtoTypeCode.UInt64: return (ulong)value;
  137. default:
  138. throw new InvalidOperationException();
  139. }
  140. #else
  141. return ((FieldInfo)originalMember).GetRawConstantValue();
  142. #endif
  143. }
  144. private static object ParseDefaultValue(Type type, object value)
  145. {
  146. if(true)
  147. {
  148. Type tmp = Helpers.GetUnderlyingType(type);
  149. if (tmp != null) type = tmp;
  150. }
  151. switch (Helpers.GetTypeCode(type))
  152. {
  153. case ProtoTypeCode.Boolean:
  154. case ProtoTypeCode.Byte:
  155. case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
  156. case ProtoTypeCode.DateTime:
  157. case ProtoTypeCode.Decimal:
  158. case ProtoTypeCode.Double:
  159. case ProtoTypeCode.Int16:
  160. case ProtoTypeCode.Int32:
  161. case ProtoTypeCode.Int64:
  162. case ProtoTypeCode.SByte:
  163. case ProtoTypeCode.Single:
  164. case ProtoTypeCode.String:
  165. case ProtoTypeCode.UInt16:
  166. case ProtoTypeCode.UInt32:
  167. case ProtoTypeCode.UInt64:
  168. case ProtoTypeCode.TimeSpan:
  169. case ProtoTypeCode.Uri:
  170. case ProtoTypeCode.Guid:
  171. {
  172. value = value + "";
  173. }
  174. break;
  175. }
  176. if (value is string)
  177. {
  178. string s = (string)value;
  179. if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
  180. switch (Helpers.GetTypeCode(type))
  181. {
  182. case ProtoTypeCode.Boolean: return bool.Parse(s);
  183. case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
  184. case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
  185. if (s.Length == 1) return s[0];
  186. throw new FormatException("Single character expected: \"" + s + "\"");
  187. case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
  188. case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  189. case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  190. case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  191. case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  192. case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  193. case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
  194. case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  195. case ProtoTypeCode.String: return s;
  196. case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  197. case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  198. case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
  199. case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
  200. case ProtoTypeCode.Uri: return s; // Uri is decorated as string
  201. case ProtoTypeCode.Guid: return new Guid(s);
  202. }
  203. }
  204. #if FEAT_IKVM
  205. if (Helpers.IsEnum(type)) return value; // return the underlying type instead
  206. System.Type convertType = null;
  207. switch(Helpers.GetTypeCode(type))
  208. {
  209. case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
  210. case ProtoTypeCode.Int16: convertType = typeof(short); break;
  211. case ProtoTypeCode.Int32: convertType = typeof(int); break;
  212. case ProtoTypeCode.Int64: convertType = typeof(long); break;
  213. case ProtoTypeCode.Byte: convertType = typeof(byte); break;
  214. case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
  215. case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
  216. case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
  217. case ProtoTypeCode.Single: convertType = typeof(float); break;
  218. case ProtoTypeCode.Double: convertType = typeof(double); break;
  219. case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
  220. }
  221. if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
  222. throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
  223. #else
  224. if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
  225. return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
  226. #endif
  227. }
  228. private IProtoSerializer serializer;
  229. internal IProtoSerializer Serializer
  230. {
  231. get
  232. {
  233. if (serializer == null) serializer = BuildSerializer();
  234. return serializer;
  235. }
  236. }
  237. private DataFormat dataFormat;
  238. /// <summary>
  239. /// Specifies the rules used to process the field; this is used to determine the most appropriate
  240. /// wite-type, but also to describe subtypes <i>within</i> that wire-type (such as SignedVariant)
  241. /// </summary>
  242. public DataFormat DataFormat {
  243. get { return dataFormat; }
  244. set
  245. {
  246. if (value != dataFormat)
  247. {
  248. ThrowIfFrozen();
  249. this.dataFormat = value;
  250. }
  251. }
  252. }
  253. /// <summary>
  254. /// Indicates whether this field should follow strict encoding rules; this means (for example) that if a "fixed32"
  255. /// is encountered when "variant" is defined, then it will fail (throw an exception) when parsing. Note that
  256. /// when serializing the defined type is always used.
  257. /// </summary>
  258. public bool IsStrict
  259. {
  260. get { return HasFlag(OPTIONS_IsStrict); }
  261. set { SetFlag(OPTIONS_IsStrict, value, true); }
  262. }
  263. /// <summary>
  264. /// Indicates whether this field should use packed encoding (which can save lots of space for repeated primitive values).
  265. /// This option only applies to list/array data of primitive types (int, double, etc).
  266. /// </summary>
  267. public bool IsPacked
  268. {
  269. get { return HasFlag(OPTIONS_IsPacked); }
  270. set { SetFlag(OPTIONS_IsPacked, value, true); }
  271. }
  272. /// <summary>
  273. /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*).
  274. /// This option only applies to list/array data.
  275. /// </summary>
  276. public bool OverwriteList
  277. {
  278. get { return HasFlag(OPTIONS_OverwriteList); }
  279. set { SetFlag(OPTIONS_OverwriteList, value, true); }
  280. }
  281. /// <summary>
  282. /// Indicates whether this field is mandatory.
  283. /// </summary>
  284. public bool IsRequired
  285. {
  286. get { return HasFlag(OPTIONS_IsRequired); }
  287. set { SetFlag(OPTIONS_IsRequired, value, true); }
  288. }
  289. /// <summary>
  290. /// Enables full object-tracking/full-graph support.
  291. /// </summary>
  292. public bool AsReference
  293. {
  294. get { return HasFlag(OPTIONS_AsReference); }
  295. set { SetFlag(OPTIONS_AsReference, value, true); }
  296. }
  297. /// <summary>
  298. /// Embeds the type information into the stream, allowing usage with types not known in advance.
  299. /// </summary>
  300. public bool DynamicType
  301. {
  302. get { return HasFlag(OPTIONS_DynamicType); }
  303. set { SetFlag(OPTIONS_DynamicType, value, true); }
  304. }
  305. /// <summary>
  306. /// Indicates that the member should be treated as a protobuf Map
  307. /// </summary>
  308. public bool IsMap
  309. {
  310. get { return HasFlag(OPTIONS_IsMap); }
  311. set { SetFlag(OPTIONS_IsMap, value, true); }
  312. }
  313. private DataFormat mapKeyFormat, mapValueFormat;
  314. /// <summary>
  315. /// Specifies the data-format that should be used for the key, when IsMap is enabled
  316. /// </summary>
  317. public DataFormat MapKeyFormat
  318. {
  319. get { return mapKeyFormat; }
  320. set
  321. {
  322. if(mapKeyFormat != value)
  323. {
  324. ThrowIfFrozen();
  325. mapKeyFormat = value;
  326. }
  327. }
  328. }
  329. /// <summary>
  330. /// Specifies the data-format that should be used for the value, when IsMap is enabled
  331. /// </summary>
  332. public DataFormat MapValueFormat
  333. {
  334. get { return mapValueFormat; }
  335. set
  336. {
  337. if (mapValueFormat != value)
  338. {
  339. ThrowIfFrozen();
  340. mapValueFormat = value;
  341. }
  342. }
  343. }
  344. private MethodInfo getSpecified, setSpecified;
  345. /// <summary>
  346. /// Specifies methods for working with optional data members.
  347. /// </summary>
  348. /// <param name="getSpecified">Provides a method (null for none) to query whether this member should
  349. /// be serialized; it must be of the form "bool {Method}()". The member is only serialized if the
  350. /// method returns true.</param>
  351. /// <param name="setSpecified">Provides a method (null for none) to indicate that a member was
  352. /// deserialized; it must be of the form "void {Method}(bool)", and will be called with "true"
  353. /// when data is found.</param>
  354. public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified)
  355. {
  356. if (this.getSpecified != getSpecified || this.setSpecified != setSpecified)
  357. {
  358. if (getSpecified != null)
  359. {
  360. if (getSpecified.ReturnType != model.MapType(typeof(bool))
  361. || getSpecified.IsStatic
  362. || getSpecified.GetParameters().Length != 0)
  363. {
  364. throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified");
  365. }
  366. }
  367. if (setSpecified != null)
  368. {
  369. ParameterInfo[] args;
  370. if (setSpecified.ReturnType != model.MapType(typeof(void))
  371. || setSpecified.IsStatic
  372. || (args = setSpecified.GetParameters()).Length != 1
  373. || args[0].ParameterType != model.MapType(typeof(bool)))
  374. {
  375. throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified");
  376. }
  377. }
  378. ThrowIfFrozen();
  379. this.getSpecified = getSpecified;
  380. this.setSpecified = setSpecified;
  381. }
  382. }
  383. private void ThrowIfFrozen()
  384. {
  385. if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated");
  386. }
  387. internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
  388. {
  389. dictionaryType = keyType = valueType = null;
  390. #if WINRT || COREFX
  391. var info = memberType.GetTypeInfo();
  392. #else
  393. var info = memberType;
  394. #endif
  395. MethodInfo b, a, ar, f;
  396. if(ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out b, out a, out ar, out f))
  397. {
  398. return false;
  399. }
  400. if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
  401. {
  402. var typeArgs = memberType.GetGenericArguments();
  403. if (IsValidMapKeyType(typeArgs[0]))
  404. {
  405. keyType = typeArgs[0];
  406. valueType = typeArgs[1];
  407. dictionaryType = memberType;
  408. }
  409. return false;
  410. }
  411. foreach (var iType in memberType.GetInterfaces())
  412. {
  413. #if WINRT || COREFX
  414. info = iType.GetTypeInfo();
  415. #else
  416. info = iType;
  417. #endif
  418. if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
  419. {
  420. if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
  421. var typeArgs = iType.GetGenericArguments();
  422. if (IsValidMapKeyType(typeArgs[0]))
  423. {
  424. keyType = typeArgs[0];
  425. valueType = typeArgs[1];
  426. dictionaryType = memberType;
  427. }
  428. }
  429. }
  430. if (dictionaryType == null) return false;
  431. // (note we checked the key type already)
  432. // not a map if value is repeated
  433. Type itemType = null, defaultType = null;
  434. model.ResolveListTypes(valueType, ref itemType, ref defaultType);
  435. if (itemType != null) return false;
  436. return dictionaryType != null;
  437. }
  438. static bool IsValidMapKeyType(Type type)
  439. {
  440. if (type == null) return false;
  441. switch(Helpers.GetTypeCode(type))
  442. {
  443. case ProtoTypeCode.Boolean:
  444. case ProtoTypeCode.Byte:
  445. case ProtoTypeCode.Char:
  446. case ProtoTypeCode.Int16:
  447. case ProtoTypeCode.Int32:
  448. case ProtoTypeCode.Int64:
  449. case ProtoTypeCode.String:
  450. case ProtoTypeCode.SByte:
  451. case ProtoTypeCode.UInt16:
  452. case ProtoTypeCode.UInt32:
  453. case ProtoTypeCode.UInt64:
  454. return true;
  455. }
  456. return false;
  457. }
  458. private IProtoSerializer BuildSerializer()
  459. {
  460. int opaqueToken = 0;
  461. try
  462. {
  463. model.TakeLock(ref opaqueToken);// check nobody is still adding this type
  464. var member = backingMember ?? originalMember;
  465. IProtoSerializer ser;
  466. if (IsMap)
  467. {
  468. Type dictionaryType,keyType,valueType;
  469. ResolveMapTypes(out dictionaryType, out keyType, out valueType);
  470. if (dictionaryType == null)
  471. {
  472. throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName);
  473. }
  474. var concreteType = defaultType;
  475. if(concreteType == null && Helpers.IsClass(memberType))
  476. {
  477. concreteType = memberType;
  478. }
  479. WireType keyWireType;
  480. var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType, out keyWireType, false, false, false, false);
  481. if(!AsReference)
  482. {
  483. AsReference = MetaType.GetAsReferenceDefault(model, valueType);
  484. }
  485. WireType valueWireType;
  486. var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType, out valueWireType, AsReference, DynamicType, false, true);
  487. var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors(
  488. BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
  489. if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
  490. ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, fieldNumber,
  491. DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
  492. }
  493. else
  494. {
  495. WireType wireType;
  496. Type finalType = itemType == null ? memberType : itemType;
  497. ser = TryGetCoreSerializer(model, dataFormat, finalType, out wireType, AsReference, DynamicType, OverwriteList, true);
  498. if (ser == null)
  499. {
  500. throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName);
  501. }
  502. // apply tags
  503. if (itemType != null && SupportNull)
  504. {
  505. if (IsPacked)
  506. {
  507. throw new NotSupportedException("Packed encodings cannot support null values");
  508. }
  509. ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser);
  510. ser = new NullDecorator(model, ser);
  511. ser = new TagDecorator(fieldNumber, WireType.StartGroup, false, ser);
  512. }
  513. else
  514. {
  515. ser = new TagDecorator(fieldNumber, wireType, IsStrict, ser);
  516. }
  517. // apply lists if appropriate
  518. if (itemType != null)
  519. {
  520. #if NO_GENERICS
  521. Type underlyingItemType = itemType;
  522. #else
  523. Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType;
  524. #endif
  525. Helpers.DebugAssert(underlyingItemType == ser.ExpectedType
  526. || (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType))
  527. , "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType);
  528. if (memberType.IsArray)
  529. {
  530. ser = new ArrayDecorator(model, ser, fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull);
  531. }
  532. else
  533. {
  534. ser = ListDecorator.Create(model, memberType, defaultType, ser, fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull);
  535. }
  536. }
  537. else if (defaultValue != null && !IsRequired && getSpecified == null)
  538. { // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue,
  539. // as does "IsRequired"
  540. ser = new DefaultValueDecorator(model, defaultValue, ser);
  541. }
  542. if (memberType == model.MapType(typeof(Uri)))
  543. {
  544. ser = new UriDecorator(model, ser);
  545. }
  546. #if PORTABLE
  547. else if(memberType.FullName == typeof(Uri).FullName)
  548. {
  549. // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri)
  550. ser = new ReflectedUriDecorator(memberType, model, ser);
  551. }
  552. #endif
  553. }
  554. if (member != null)
  555. {
  556. PropertyInfo prop = member as PropertyInfo;
  557. if (prop != null)
  558. {
  559. ser = new PropertyDecorator(model, parentType, (PropertyInfo)member, ser);
  560. }
  561. else
  562. {
  563. FieldInfo fld = member as FieldInfo;
  564. if (fld != null)
  565. {
  566. ser = new FieldDecorator(parentType, (FieldInfo)member, ser);
  567. }
  568. else
  569. {
  570. throw new InvalidOperationException();
  571. }
  572. }
  573. if (getSpecified != null || setSpecified != null)
  574. {
  575. ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser);
  576. }
  577. }
  578. return ser;
  579. }
  580. finally
  581. {
  582. model.ReleaseLock(opaqueToken);
  583. }
  584. }
  585. private static WireType GetIntWireType(DataFormat format, int width) {
  586. switch(format) {
  587. case DataFormat.ZigZag: return WireType.SignedVariant;
  588. case DataFormat.FixedSize: return width == 32 ? WireType.Fixed32 : WireType.Fixed64;
  589. case DataFormat.TwosComplement:
  590. case DataFormat.Default: return WireType.Variant;
  591. default: throw new InvalidOperationException();
  592. }
  593. }
  594. private static WireType GetDateTimeWireType(DataFormat format)
  595. {
  596. switch (format)
  597. {
  598. case DataFormat.Group: return WireType.StartGroup;
  599. case DataFormat.FixedSize: return WireType.Fixed64;
  600. case DataFormat.WellKnown:
  601. case DataFormat.Default:
  602. return WireType.String;
  603. default: throw new InvalidOperationException();
  604. }
  605. }
  606. internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType,
  607. bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes)
  608. {
  609. #if !NO_GENERICS
  610. {
  611. Type tmp = Helpers.GetUnderlyingType(type);
  612. if (tmp != null) type = tmp;
  613. }
  614. #endif
  615. if (Helpers.IsEnum(type))
  616. {
  617. if (allowComplexTypes && model != null)
  618. {
  619. // need to do this before checking the typecode; an int enum will report Int32 etc
  620. defaultWireType = WireType.Variant;
  621. return new EnumSerializer(type, model.GetEnumMap(type));
  622. }
  623. else
  624. { // enum is fine for adding as a meta-type
  625. defaultWireType = WireType.None;
  626. return null;
  627. }
  628. }
  629. ProtoTypeCode code = Helpers.GetTypeCode(type);
  630. switch (code)
  631. {
  632. case ProtoTypeCode.Int32:
  633. defaultWireType = GetIntWireType(dataFormat, 32);
  634. return new Int32Serializer(model);
  635. case ProtoTypeCode.UInt32:
  636. defaultWireType = GetIntWireType(dataFormat, 32);
  637. return new UInt32Serializer(model);
  638. case ProtoTypeCode.Int64:
  639. defaultWireType = GetIntWireType(dataFormat, 64);
  640. return new Int64Serializer(model);
  641. case ProtoTypeCode.UInt64:
  642. defaultWireType = GetIntWireType(dataFormat, 64);
  643. return new UInt64Serializer(model);
  644. case ProtoTypeCode.String:
  645. defaultWireType = WireType.String;
  646. if (asReference)
  647. {
  648. return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference);
  649. }
  650. return new StringSerializer(model);
  651. case ProtoTypeCode.Single:
  652. defaultWireType = WireType.Fixed32;
  653. return new SingleSerializer(model);
  654. case ProtoTypeCode.Double:
  655. defaultWireType = WireType.Fixed64;
  656. return new DoubleSerializer(model);
  657. case ProtoTypeCode.Boolean:
  658. defaultWireType = WireType.Variant;
  659. return new BooleanSerializer(model);
  660. case ProtoTypeCode.DateTime:
  661. defaultWireType = GetDateTimeWireType(dataFormat);
  662. return new DateTimeSerializer(dataFormat, model);
  663. case ProtoTypeCode.Decimal:
  664. defaultWireType = WireType.String;
  665. return new DecimalSerializer(model);
  666. case ProtoTypeCode.Byte:
  667. defaultWireType = GetIntWireType(dataFormat, 32);
  668. return new ByteSerializer(model);
  669. case ProtoTypeCode.SByte:
  670. defaultWireType = GetIntWireType(dataFormat, 32);
  671. return new SByteSerializer(model);
  672. case ProtoTypeCode.Char:
  673. defaultWireType = WireType.Variant;
  674. return new CharSerializer(model);
  675. case ProtoTypeCode.Int16:
  676. defaultWireType = GetIntWireType(dataFormat, 32);
  677. return new Int16Serializer(model);
  678. case ProtoTypeCode.UInt16:
  679. defaultWireType = GetIntWireType(dataFormat, 32);
  680. return new UInt16Serializer(model);
  681. case ProtoTypeCode.TimeSpan:
  682. defaultWireType = GetDateTimeWireType(dataFormat);
  683. return new TimeSpanSerializer(dataFormat, model);
  684. case ProtoTypeCode.Guid:
  685. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  686. return new GuidSerializer(model);
  687. case ProtoTypeCode.Uri:
  688. defaultWireType = WireType.String;
  689. return new StringSerializer(model);
  690. case ProtoTypeCode.ByteArray:
  691. defaultWireType = WireType.String;
  692. return new BlobSerializer(model, overwriteList);
  693. case ProtoTypeCode.Type:
  694. defaultWireType = WireType.String;
  695. return new SystemTypeSerializer(model);
  696. }
  697. IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null;
  698. if (parseable != null)
  699. {
  700. defaultWireType = WireType.String;
  701. return parseable;
  702. }
  703. if (allowComplexTypes && model != null)
  704. {
  705. int key = model.GetKey(type, false, true);
  706. MetaType meta = null;
  707. if (key >= 0)
  708. {
  709. meta = model[type];
  710. if(dataFormat == DataFormat.Default && meta.IsGroup)
  711. {
  712. dataFormat = DataFormat.Group;
  713. }
  714. }
  715. if (asReference || dynamicType)
  716. {
  717. BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
  718. if (asReference) options |= BclHelpers.NetObjectOptions.AsReference;
  719. if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType;
  720. if (meta != null)
  721. { // exists
  722. if (asReference && Helpers.IsValueType(type))
  723. {
  724. string message = "AsReference cannot be used with value-types";
  725. if (type.Name == "KeyValuePair`2")
  726. {
  727. message += "; please see http://stackoverflow.com/q/14436606/";
  728. }
  729. else
  730. {
  731. message += ": " + type.FullName;
  732. }
  733. throw new InvalidOperationException(message);
  734. }
  735. if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet;
  736. if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor;
  737. }
  738. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  739. return new NetObjectSerializer(model, type, key, options);
  740. }
  741. if (key >= 0)
  742. {
  743. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  744. return new SubItemSerializer(type, key, meta, true);
  745. }
  746. }
  747. defaultWireType = WireType.None;
  748. return null;
  749. }
  750. private string name;
  751. internal void SetName(string name)
  752. {
  753. if (name != this.name)
  754. {
  755. ThrowIfFrozen();
  756. this.name = name;
  757. }
  758. }
  759. /// <summary>
  760. /// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used
  761. /// when inferring a schema).
  762. /// </summary>
  763. public string Name
  764. {
  765. get { return Helpers.IsNullOrEmpty(name) ? originalMember.Name : name; }
  766. set { SetName(value); }
  767. }
  768. private const byte
  769. OPTIONS_IsStrict = 1,
  770. OPTIONS_IsPacked = 2,
  771. OPTIONS_IsRequired = 4,
  772. OPTIONS_OverwriteList = 8,
  773. OPTIONS_SupportNull = 16,
  774. OPTIONS_AsReference = 32,
  775. OPTIONS_IsMap = 64,
  776. OPTIONS_DynamicType = 128;
  777. private byte flags;
  778. private bool HasFlag(byte flag) { return (flags & flag) == flag; }
  779. private void SetFlag(byte flag, bool value, bool throwIfFrozen)
  780. {
  781. if (throwIfFrozen && HasFlag(flag) != value)
  782. {
  783. ThrowIfFrozen();
  784. }
  785. if (value)
  786. flags |= flag;
  787. else
  788. flags = (byte)(flags & ~flag);
  789. }
  790. /// <summary>
  791. /// Should lists have extended support for null values? Note this makes the serialization less efficient.
  792. /// </summary>
  793. public bool SupportNull
  794. {
  795. get { return HasFlag(OPTIONS_SupportNull); }
  796. set { SetFlag(OPTIONS_SupportNull, value, true);}
  797. }
  798. internal string GetSchemaTypeName(bool applyNetObjectProxy, ref RuntimeTypeModel.CommonImports imports)
  799. {
  800. Type effectiveType = ItemType;
  801. if (effectiveType == null) effectiveType = MemberType;
  802. return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports);
  803. }
  804. internal sealed class Comparer : System.Collections.IComparer
  805. #if !NO_GENERICS
  806. , System.Collections.Generic.IComparer<ValueMember>
  807. #endif
  808. {
  809. public static readonly Comparer Default = new Comparer();
  810. public int Compare(object x, object y)
  811. {
  812. return Compare(x as ValueMember, y as ValueMember);
  813. }
  814. public int Compare(ValueMember x, ValueMember y)
  815. {
  816. if (ReferenceEquals(x, y)) return 0;
  817. if (x == null) return -1;
  818. if (y == null) return 1;
  819. return x.FieldNumber.CompareTo(y.FieldNumber);
  820. }
  821. }
  822. }
  823. }
  824. #endif