ValueMember.cs 28 KB

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