ValueMember.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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 string mapKeyTypeName;
  345. public string MapKeyTypeName{
  346. get{
  347. return mapKeyTypeName;
  348. }
  349. set{
  350. mapKeyTypeName = value;
  351. }
  352. }
  353. private string mapValueTypeName;
  354. public string MapValueTypeName{
  355. get{
  356. return mapValueTypeName;
  357. }
  358. set{
  359. mapValueTypeName = value;
  360. }
  361. }
  362. private MethodInfo getSpecified, setSpecified;
  363. /// <summary>
  364. /// Specifies methods for working with optional data members.
  365. /// </summary>
  366. /// <param name="getSpecified">Provides a method (null for none) to query whether this member should
  367. /// be serialized; it must be of the form "bool {Method}()". The member is only serialized if the
  368. /// method returns true.</param>
  369. /// <param name="setSpecified">Provides a method (null for none) to indicate that a member was
  370. /// deserialized; it must be of the form "void {Method}(bool)", and will be called with "true"
  371. /// when data is found.</param>
  372. public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified)
  373. {
  374. if (this.getSpecified != getSpecified || this.setSpecified != setSpecified)
  375. {
  376. if (getSpecified != null)
  377. {
  378. if (getSpecified.ReturnType != model.MapType(typeof(bool))
  379. || getSpecified.IsStatic
  380. || getSpecified.GetParameters().Length != 0)
  381. {
  382. throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified");
  383. }
  384. }
  385. if (setSpecified != null)
  386. {
  387. ParameterInfo[] args;
  388. if (setSpecified.ReturnType != model.MapType(typeof(void))
  389. || setSpecified.IsStatic
  390. || (args = setSpecified.GetParameters()).Length != 1
  391. || args[0].ParameterType != model.MapType(typeof(bool)))
  392. {
  393. throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified");
  394. }
  395. }
  396. ThrowIfFrozen();
  397. this.getSpecified = getSpecified;
  398. this.setSpecified = setSpecified;
  399. }
  400. }
  401. private void ThrowIfFrozen()
  402. {
  403. if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated");
  404. }
  405. internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
  406. {
  407. dictionaryType = keyType = valueType = null;
  408. #if WINRT || COREFX
  409. var info = memberType.GetTypeInfo();
  410. #else
  411. var info = memberType;
  412. #endif
  413. MethodInfo b, a, ar, f;
  414. if(ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out b, out a, out ar, out f))
  415. {
  416. return false;
  417. }
  418. if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
  419. {
  420. var typeArgs = memberType.GetGenericArguments();
  421. if (IsValidMapKeyType(typeArgs[0]))
  422. {
  423. keyType = typeArgs[0];
  424. valueType = typeArgs[1];
  425. dictionaryType = memberType;
  426. }
  427. return false;
  428. }
  429. foreach (var iType in memberType.GetInterfaces())
  430. {
  431. #if WINRT || COREFX
  432. info = iType.GetTypeInfo();
  433. #else
  434. info = iType;
  435. #endif
  436. if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
  437. {
  438. if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
  439. var typeArgs = iType.GetGenericArguments();
  440. if (IsValidMapKeyType(typeArgs[0]))
  441. {
  442. keyType = typeArgs[0];
  443. valueType = typeArgs[1];
  444. dictionaryType = memberType;
  445. }
  446. }
  447. }
  448. if (dictionaryType == null) return false;
  449. // (note we checked the key type already)
  450. // not a map if value is repeated
  451. Type itemType = null, defaultType = null;
  452. model.ResolveListTypes(valueType, ref itemType, ref defaultType);
  453. if (itemType != null) return false;
  454. return dictionaryType != null;
  455. }
  456. static bool IsValidMapKeyType(Type type)
  457. {
  458. if (type == null) return false;
  459. switch(Helpers.GetTypeCode(type))
  460. {
  461. case ProtoTypeCode.Boolean:
  462. case ProtoTypeCode.Byte:
  463. case ProtoTypeCode.Char:
  464. case ProtoTypeCode.Int16:
  465. case ProtoTypeCode.Int32:
  466. case ProtoTypeCode.Int64:
  467. case ProtoTypeCode.String:
  468. case ProtoTypeCode.SByte:
  469. case ProtoTypeCode.UInt16:
  470. case ProtoTypeCode.UInt32:
  471. case ProtoTypeCode.UInt64:
  472. return true;
  473. }
  474. return false;
  475. }
  476. private IProtoSerializer BuildSerializer()
  477. {
  478. int opaqueToken = 0;
  479. try
  480. {
  481. model.TakeLock(ref opaqueToken);// check nobody is still adding this type
  482. var member = backingMember ?? originalMember;
  483. IProtoSerializer ser;
  484. if (IsMap)
  485. {
  486. Type dictionaryType,keyType,valueType;
  487. ResolveMapTypes(out dictionaryType, out keyType, out valueType);
  488. var keyType2 = keyType;
  489. var valueType2 = valueType;
  490. if (keyType2 != null && keyType2.FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance") {
  491. keyType2 = PType.FindType (mapKeyTypeName);
  492. }
  493. if (valueType2 != null && valueType2.FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance") {
  494. valueType2 = PType.FindType (mapValueTypeName);
  495. }
  496. if(dictionaryType != null){
  497. dictionaryType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(new Type[]{ keyType, valueType});
  498. }
  499. if (dictionaryType == null)
  500. {
  501. throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName);
  502. }
  503. var concreteType = defaultType;
  504. if(concreteType == null && Helpers.IsClass(memberType))
  505. {
  506. concreteType = memberType;
  507. }
  508. WireType keyWireType;
  509. var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType2, out keyWireType, false, false, false, false);
  510. if(!AsReference)
  511. {
  512. AsReference = MetaType.GetAsReferenceDefault(model, valueType);
  513. }
  514. WireType valueWireType;
  515. var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType2, out valueWireType, AsReference, DynamicType, false, true);
  516. var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors(
  517. BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
  518. if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor");
  519. ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, fieldNumber,
  520. DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList });
  521. }
  522. else
  523. {
  524. WireType wireType;
  525. Type finalType = itemType == null ? memberType : itemType;
  526. ser = TryGetCoreSerializer(model, dataFormat, finalType, out wireType, AsReference, DynamicType, OverwriteList, true);
  527. if (ser == null)
  528. {
  529. throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName);
  530. }
  531. // apply tags
  532. if (itemType != null && SupportNull)
  533. {
  534. if (IsPacked)
  535. {
  536. throw new NotSupportedException("Packed encodings cannot support null values");
  537. }
  538. ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser);
  539. ser = new NullDecorator(model, ser);
  540. ser = new TagDecorator(fieldNumber, WireType.StartGroup, false, ser);
  541. }
  542. else
  543. {
  544. ser = new TagDecorator(fieldNumber, wireType, IsStrict, ser);
  545. }
  546. // apply lists if appropriate
  547. if (itemType != null)
  548. {
  549. #if NO_GENERICS
  550. Type underlyingItemType = itemType;
  551. #else
  552. Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType;
  553. #endif
  554. Helpers.DebugAssert(underlyingItemType == ser.ExpectedType
  555. || (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType))
  556. , "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType);
  557. if (memberType.IsArray)
  558. {
  559. ser = new ArrayDecorator(model, ser, fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull);
  560. }
  561. else
  562. {
  563. ser = ListDecorator.Create(model, memberType, defaultType, ser, fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull);
  564. }
  565. }
  566. else if (defaultValue != null && !IsRequired && getSpecified == null)
  567. { // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue,
  568. // as does "IsRequired"
  569. ser = new DefaultValueDecorator(model, defaultValue, ser);
  570. }
  571. if (memberType == model.MapType(typeof(Uri)))
  572. {
  573. ser = new UriDecorator(model, ser);
  574. }
  575. #if PORTABLE
  576. else if(memberType.FullName == typeof(Uri).FullName)
  577. {
  578. // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri)
  579. ser = new ReflectedUriDecorator(memberType, model, ser);
  580. }
  581. #endif
  582. }
  583. if (member != null)
  584. {
  585. PropertyInfo prop = member as PropertyInfo;
  586. if (prop != null)
  587. {
  588. ser = new PropertyDecorator(model, parentType, (PropertyInfo)member, ser);
  589. }
  590. else
  591. {
  592. FieldInfo fld = member as FieldInfo;
  593. if (fld != null)
  594. {
  595. ser = new FieldDecorator(parentType, (FieldInfo)member, ser);
  596. }
  597. else
  598. {
  599. throw new InvalidOperationException();
  600. }
  601. }
  602. if (getSpecified != null || setSpecified != null)
  603. {
  604. ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser);
  605. }
  606. }
  607. return ser;
  608. }
  609. finally
  610. {
  611. model.ReleaseLock(opaqueToken);
  612. }
  613. }
  614. private static WireType GetIntWireType(DataFormat format, int width) {
  615. switch(format) {
  616. case DataFormat.ZigZag: return WireType.SignedVariant;
  617. case DataFormat.FixedSize: return width == 32 ? WireType.Fixed32 : WireType.Fixed64;
  618. case DataFormat.TwosComplement:
  619. case DataFormat.Default: return WireType.Variant;
  620. default: throw new InvalidOperationException();
  621. }
  622. }
  623. private static WireType GetDateTimeWireType(DataFormat format)
  624. {
  625. switch (format)
  626. {
  627. case DataFormat.Group: return WireType.StartGroup;
  628. case DataFormat.FixedSize: return WireType.Fixed64;
  629. case DataFormat.WellKnown:
  630. case DataFormat.Default:
  631. return WireType.String;
  632. default: throw new InvalidOperationException();
  633. }
  634. }
  635. internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType,
  636. bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes)
  637. {
  638. #if !NO_GENERICS
  639. {
  640. Type tmp = Helpers.GetUnderlyingType(type);
  641. if (tmp != null) type = tmp;
  642. }
  643. #endif
  644. if (Helpers.IsEnum(type))
  645. {
  646. if (allowComplexTypes && model != null)
  647. {
  648. // need to do this before checking the typecode; an int enum will report Int32 etc
  649. defaultWireType = WireType.Variant;
  650. return new EnumSerializer(type, model.GetEnumMap(type));
  651. }
  652. else
  653. { // enum is fine for adding as a meta-type
  654. defaultWireType = WireType.None;
  655. return null;
  656. }
  657. }
  658. ProtoTypeCode code = Helpers.GetTypeCode(type);
  659. switch (code)
  660. {
  661. case ProtoTypeCode.Int32:
  662. defaultWireType = GetIntWireType(dataFormat, 32);
  663. return new Int32Serializer(model);
  664. case ProtoTypeCode.UInt32:
  665. defaultWireType = GetIntWireType(dataFormat, 32);
  666. return new UInt32Serializer(model);
  667. case ProtoTypeCode.Int64:
  668. defaultWireType = GetIntWireType(dataFormat, 64);
  669. return new Int64Serializer(model);
  670. case ProtoTypeCode.UInt64:
  671. defaultWireType = GetIntWireType(dataFormat, 64);
  672. return new UInt64Serializer(model);
  673. case ProtoTypeCode.String:
  674. defaultWireType = WireType.String;
  675. if (asReference)
  676. {
  677. return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference);
  678. }
  679. return new StringSerializer(model);
  680. case ProtoTypeCode.Single:
  681. defaultWireType = WireType.Fixed32;
  682. return new SingleSerializer(model);
  683. case ProtoTypeCode.Double:
  684. defaultWireType = WireType.Fixed64;
  685. return new DoubleSerializer(model);
  686. case ProtoTypeCode.Boolean:
  687. defaultWireType = WireType.Variant;
  688. return new BooleanSerializer(model);
  689. case ProtoTypeCode.DateTime:
  690. defaultWireType = GetDateTimeWireType(dataFormat);
  691. return new DateTimeSerializer(dataFormat, model);
  692. case ProtoTypeCode.Decimal:
  693. defaultWireType = WireType.String;
  694. return new DecimalSerializer(model);
  695. case ProtoTypeCode.Byte:
  696. defaultWireType = GetIntWireType(dataFormat, 32);
  697. return new ByteSerializer(model);
  698. case ProtoTypeCode.SByte:
  699. defaultWireType = GetIntWireType(dataFormat, 32);
  700. return new SByteSerializer(model);
  701. case ProtoTypeCode.Char:
  702. defaultWireType = WireType.Variant;
  703. return new CharSerializer(model);
  704. case ProtoTypeCode.Int16:
  705. defaultWireType = GetIntWireType(dataFormat, 32);
  706. return new Int16Serializer(model);
  707. case ProtoTypeCode.UInt16:
  708. defaultWireType = GetIntWireType(dataFormat, 32);
  709. return new UInt16Serializer(model);
  710. case ProtoTypeCode.TimeSpan:
  711. defaultWireType = GetDateTimeWireType(dataFormat);
  712. return new TimeSpanSerializer(dataFormat, model);
  713. case ProtoTypeCode.Guid:
  714. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  715. return new GuidSerializer(model);
  716. case ProtoTypeCode.Uri:
  717. defaultWireType = WireType.String;
  718. return new StringSerializer(model);
  719. case ProtoTypeCode.ByteArray:
  720. defaultWireType = WireType.String;
  721. return new BlobSerializer(model, overwriteList);
  722. case ProtoTypeCode.Type:
  723. defaultWireType = WireType.String;
  724. return new SystemTypeSerializer(model);
  725. }
  726. IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null;
  727. if (parseable != null)
  728. {
  729. defaultWireType = WireType.String;
  730. return parseable;
  731. }
  732. if (allowComplexTypes && model != null)
  733. {
  734. int key = model.GetKey(type, false, true);
  735. MetaType meta = null;
  736. if (key >= 0)
  737. {
  738. meta = model[type];
  739. if(dataFormat == DataFormat.Default && meta.IsGroup)
  740. {
  741. dataFormat = DataFormat.Group;
  742. }
  743. }
  744. if (asReference || dynamicType)
  745. {
  746. BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
  747. if (asReference) options |= BclHelpers.NetObjectOptions.AsReference;
  748. if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType;
  749. if (meta != null)
  750. { // exists
  751. if (asReference && Helpers.IsValueType(type))
  752. {
  753. string message = "AsReference cannot be used with value-types";
  754. if (type.Name == "KeyValuePair`2")
  755. {
  756. message += "; please see http://stackoverflow.com/q/14436606/";
  757. }
  758. else
  759. {
  760. message += ": " + type.FullName;
  761. }
  762. throw new InvalidOperationException(message);
  763. }
  764. if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet;
  765. if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor;
  766. }
  767. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  768. return new NetObjectSerializer(model, type, key, options);
  769. }
  770. if (key >= 0)
  771. {
  772. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  773. return new SubItemSerializer(type, key, meta, true);
  774. }
  775. }
  776. defaultWireType = WireType.None;
  777. return null;
  778. }
  779. private string name;
  780. internal void SetName(string name)
  781. {
  782. if (name != this.name)
  783. {
  784. ThrowIfFrozen();
  785. this.name = name;
  786. }
  787. }
  788. /// <summary>
  789. /// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used
  790. /// when inferring a schema).
  791. /// </summary>
  792. public string Name
  793. {
  794. get { return Helpers.IsNullOrEmpty(name) ? originalMember.Name : name; }
  795. set { SetName(value); }
  796. }
  797. private const byte
  798. OPTIONS_IsStrict = 1,
  799. OPTIONS_IsPacked = 2,
  800. OPTIONS_IsRequired = 4,
  801. OPTIONS_OverwriteList = 8,
  802. OPTIONS_SupportNull = 16,
  803. OPTIONS_AsReference = 32,
  804. OPTIONS_IsMap = 64,
  805. OPTIONS_DynamicType = 128;
  806. private byte flags;
  807. private bool HasFlag(byte flag) { return (flags & flag) == flag; }
  808. private void SetFlag(byte flag, bool value, bool throwIfFrozen)
  809. {
  810. if (throwIfFrozen && HasFlag(flag) != value)
  811. {
  812. ThrowIfFrozen();
  813. }
  814. if (value)
  815. flags |= flag;
  816. else
  817. flags = (byte)(flags & ~flag);
  818. }
  819. /// <summary>
  820. /// Should lists have extended support for null values? Note this makes the serialization less efficient.
  821. /// </summary>
  822. public bool SupportNull
  823. {
  824. get { return HasFlag(OPTIONS_SupportNull); }
  825. set { SetFlag(OPTIONS_SupportNull, value, true);}
  826. }
  827. internal string GetSchemaTypeName(bool applyNetObjectProxy, ref RuntimeTypeModel.CommonImports imports)
  828. {
  829. Type effectiveType = ItemType;
  830. if (effectiveType == null) effectiveType = MemberType;
  831. return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports);
  832. }
  833. internal sealed class Comparer : System.Collections.IComparer
  834. #if !NO_GENERICS
  835. , System.Collections.Generic.IComparer<ValueMember>
  836. #endif
  837. {
  838. public static readonly Comparer Default = new Comparer();
  839. public int Compare(object x, object y)
  840. {
  841. return Compare(x as ValueMember, y as ValueMember);
  842. }
  843. public int Compare(ValueMember x, ValueMember y)
  844. {
  845. if (ReferenceEquals(x, y)) return 0;
  846. if (x == null) return -1;
  847. if (y == null) return 1;
  848. return x.FieldNumber.CompareTo(y.FieldNumber);
  849. }
  850. }
  851. }
  852. }
  853. #endif