ValueMember.cs 37 KB

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