ValueMember.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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
  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, "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType);
  331. if (memberType.IsArray)
  332. {
  333. ser = new ArrayDecorator(model, ser, fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull);
  334. }
  335. else
  336. {
  337. ser = ListDecorator.Create(model, memberType, defaultType, ser, fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull);
  338. }
  339. }
  340. else if (defaultValue != null && !IsRequired && getSpecified == null)
  341. { // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue,
  342. // as does "IsRequired"
  343. ser = new DefaultValueDecorator(model, defaultValue, ser);
  344. }
  345. if (memberType == model.MapType(typeof(Uri)))
  346. {
  347. ser = new UriDecorator(model, ser);
  348. }
  349. if (member != null)
  350. {
  351. PropertyInfo prop = member as PropertyInfo;
  352. if (prop != null)
  353. {
  354. ser = new PropertyDecorator(model, parentType, (PropertyInfo)member, ser);
  355. }
  356. else
  357. {
  358. FieldInfo fld = member as FieldInfo;
  359. if (fld != null)
  360. {
  361. ser = new FieldDecorator(parentType, (FieldInfo)member, ser);
  362. }
  363. else
  364. {
  365. throw new InvalidOperationException();
  366. }
  367. }
  368. if (getSpecified != null || setSpecified != null)
  369. {
  370. ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser);
  371. }
  372. }
  373. return ser;
  374. }
  375. finally
  376. {
  377. model.ReleaseLock(opaqueToken);
  378. }
  379. }
  380. private static WireType GetIntWireType(DataFormat format, int width) {
  381. switch(format) {
  382. case DataFormat.ZigZag: return WireType.SignedVariant;
  383. case DataFormat.FixedSize: return width == 32 ? WireType.Fixed32 : WireType.Fixed64;
  384. case DataFormat.TwosComplement:
  385. case DataFormat.Default: return WireType.Variant;
  386. default: throw new InvalidOperationException();
  387. }
  388. }
  389. private static WireType GetDateTimeWireType(DataFormat format)
  390. {
  391. switch (format)
  392. {
  393. case DataFormat.Group: return WireType.StartGroup;
  394. case DataFormat.FixedSize: return WireType.Fixed64;
  395. case DataFormat.Default: return WireType.String;
  396. default: throw new InvalidOperationException();
  397. }
  398. }
  399. internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType,
  400. bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes)
  401. {
  402. #if !NO_GENERICS
  403. {
  404. Type tmp = Helpers.GetUnderlyingType(type);
  405. if (tmp != null) type = tmp;
  406. }
  407. #endif
  408. if (Helpers.IsEnum(type))
  409. {
  410. if (allowComplexTypes && model != null)
  411. {
  412. // need to do this before checking the typecode; an int enum will report Int32 etc
  413. defaultWireType = WireType.Variant;
  414. return new EnumSerializer(type, model.GetEnumMap(type));
  415. }
  416. else
  417. { // enum is fine for adding as a meta-type
  418. defaultWireType = WireType.None;
  419. return null;
  420. }
  421. }
  422. ProtoTypeCode code = Helpers.GetTypeCode(type);
  423. switch (code)
  424. {
  425. case ProtoTypeCode.Int32:
  426. defaultWireType = GetIntWireType(dataFormat, 32);
  427. return new Int32Serializer(model);
  428. case ProtoTypeCode.UInt32:
  429. defaultWireType = GetIntWireType(dataFormat, 32);
  430. return new UInt32Serializer(model);
  431. case ProtoTypeCode.Int64:
  432. defaultWireType = GetIntWireType(dataFormat, 64);
  433. return new Int64Serializer(model);
  434. case ProtoTypeCode.UInt64:
  435. defaultWireType = GetIntWireType(dataFormat, 64);
  436. return new UInt64Serializer(model);
  437. case ProtoTypeCode.String:
  438. defaultWireType = WireType.String;
  439. if (asReference)
  440. {
  441. return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference);
  442. }
  443. return new StringSerializer(model);
  444. case ProtoTypeCode.Single:
  445. defaultWireType = WireType.Fixed32;
  446. return new SingleSerializer(model);
  447. case ProtoTypeCode.Double:
  448. defaultWireType = WireType.Fixed64;
  449. return new DoubleSerializer(model);
  450. case ProtoTypeCode.Boolean:
  451. defaultWireType = WireType.Variant;
  452. return new BooleanSerializer(model);
  453. case ProtoTypeCode.DateTime:
  454. defaultWireType = GetDateTimeWireType(dataFormat);
  455. return new DateTimeSerializer(model);
  456. case ProtoTypeCode.Decimal:
  457. defaultWireType = WireType.String;
  458. return new DecimalSerializer(model);
  459. case ProtoTypeCode.Byte:
  460. defaultWireType = GetIntWireType(dataFormat, 32);
  461. return new ByteSerializer(model);
  462. case ProtoTypeCode.SByte:
  463. defaultWireType = GetIntWireType(dataFormat, 32);
  464. return new SByteSerializer(model);
  465. case ProtoTypeCode.Char:
  466. defaultWireType = WireType.Variant;
  467. return new CharSerializer(model);
  468. case ProtoTypeCode.Int16:
  469. defaultWireType = GetIntWireType(dataFormat, 32);
  470. return new Int16Serializer(model);
  471. case ProtoTypeCode.UInt16:
  472. defaultWireType = GetIntWireType(dataFormat, 32);
  473. return new UInt16Serializer(model);
  474. case ProtoTypeCode.TimeSpan:
  475. defaultWireType = GetDateTimeWireType(dataFormat);
  476. return new TimeSpanSerializer(model);
  477. case ProtoTypeCode.Guid:
  478. defaultWireType = WireType.String;
  479. return new GuidSerializer(model);
  480. case ProtoTypeCode.Uri:
  481. defaultWireType = WireType.String;
  482. return new StringSerializer(model); // treat as string; wrapped in decorator later
  483. case ProtoTypeCode.ByteArray:
  484. defaultWireType = WireType.String;
  485. return new BlobSerializer(model, overwriteList);
  486. case ProtoTypeCode.Type:
  487. defaultWireType = WireType.String;
  488. return new SystemTypeSerializer(model);
  489. }
  490. IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null;
  491. if (parseable != null)
  492. {
  493. defaultWireType = WireType.String;
  494. return parseable;
  495. }
  496. if (allowComplexTypes && model != null)
  497. {
  498. int key = model.GetKey(type, false, true);
  499. if (asReference || dynamicType)
  500. {
  501. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  502. BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
  503. if (asReference) options |= BclHelpers.NetObjectOptions.AsReference;
  504. if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType;
  505. if (key >= 0)
  506. { // exists
  507. if (asReference && Helpers.IsValueType(type))
  508. {
  509. string message = "AsReference cannot be used with value-types";
  510. if (type.Name == "KeyValuePair`2")
  511. {
  512. message += "; please see http://stackoverflow.com/q/14436606/";
  513. }
  514. else
  515. {
  516. message += ": " + type.FullName;
  517. }
  518. throw new InvalidOperationException(message);
  519. }
  520. MetaType meta = model[type];
  521. if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet;
  522. if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor;
  523. }
  524. return new NetObjectSerializer(model, type, key, options);
  525. }
  526. if (key >= 0)
  527. {
  528. defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
  529. return new SubItemSerializer(type, key, model[type], true);
  530. }
  531. }
  532. defaultWireType = WireType.None;
  533. return null;
  534. }
  535. private string name;
  536. internal void SetName(string name)
  537. {
  538. ThrowIfFrozen();
  539. this.name = name;
  540. }
  541. /// <summary>
  542. /// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used
  543. /// when inferring a schema).
  544. /// </summary>
  545. public string Name
  546. {
  547. get { return Helpers.IsNullOrEmpty(name) ? member.Name : name; }
  548. }
  549. private const byte
  550. OPTIONS_IsStrict = 1,
  551. OPTIONS_IsPacked = 2,
  552. OPTIONS_IsRequired = 4,
  553. OPTIONS_OverwriteList = 8,
  554. OPTIONS_SupportNull = 16;
  555. private byte flags;
  556. private bool HasFlag(byte flag) { return (flags & flag) == flag; }
  557. private void SetFlag(byte flag, bool value, bool throwIfFrozen)
  558. {
  559. if (throwIfFrozen && HasFlag(flag) != value)
  560. {
  561. ThrowIfFrozen();
  562. }
  563. if (value)
  564. flags |= flag;
  565. else
  566. flags = (byte)(flags & ~flag);
  567. }
  568. /// <summary>
  569. /// Should lists have extended support for null values? Note this makes the serialization less efficient.
  570. /// </summary>
  571. public bool SupportNull
  572. {
  573. get { return HasFlag(OPTIONS_SupportNull); }
  574. set { SetFlag(OPTIONS_SupportNull, value, true);}
  575. }
  576. internal string GetSchemaTypeName(bool applyNetObjectProxy, ref bool requiresBclImport)
  577. {
  578. Type effectiveType = ItemType;
  579. if (effectiveType == null) effectiveType = MemberType;
  580. return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && asReference, applyNetObjectProxy && dynamicType, ref requiresBclImport);
  581. }
  582. internal sealed class Comparer : System.Collections.IComparer
  583. #if !NO_GENERICS
  584. , System.Collections.Generic.IComparer<ValueMember>
  585. #endif
  586. {
  587. public static readonly Comparer Default = new Comparer();
  588. public int Compare(object x, object y)
  589. {
  590. return Compare(x as ValueMember, y as ValueMember);
  591. }
  592. public int Compare(ValueMember x, ValueMember y)
  593. {
  594. if (ReferenceEquals(x, y)) return 0;
  595. if (x == null) return -1;
  596. if (y == null) return 1;
  597. return x.FieldNumber.CompareTo(y.FieldNumber);
  598. }
  599. }
  600. }
  601. }
  602. #endif