ValueMember.cs 37 KB

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