BclHelpers.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. using System;
  2. namespace ProtoBuf
  3. {
  4. internal enum TimeSpanScale
  5. {
  6. Days = 0,
  7. Hours = 1,
  8. Minutes = 2,
  9. Seconds = 3,
  10. Milliseconds = 4,
  11. Ticks = 5,
  12. MinMax = 15
  13. }
  14. /// <summary>
  15. /// Provides support for common .NET types that do not have a direct representation
  16. /// in protobuf, using the definitions from bcl.proto
  17. /// </summary>
  18. public
  19. #if FX11
  20. sealed
  21. #else
  22. static
  23. #endif
  24. class BclHelpers
  25. {
  26. /// <summary>
  27. /// Creates a new instance of the specified type, bypassing the constructor.
  28. /// </summary>
  29. /// <param name="type">The type to create</param>
  30. /// <returns>The new instance</returns>
  31. /// <exception cref="NotSupportedException">If the platform does not support constructor-skipping</exception>
  32. public static object GetUninitializedObject(Type type)
  33. {
  34. #if COREFX
  35. object obj = TryGetUninitializedObjectWithFormatterServices(type);
  36. if (obj != null) return obj;
  37. #endif
  38. #if PLAT_BINARYFORMATTER && !(WINRT || PHONE8 || COREFX)
  39. return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
  40. #else
  41. throw new NotSupportedException("Constructor-skipping is not supported on this platform");
  42. #endif
  43. }
  44. #if COREFX // this is inspired by DCS: https://github.com/dotnet/corefx/blob/c02d33b18398199f6acc17d375dab154e9a1df66/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs#L854-L894
  45. static Func<Type, object> getUninitializedObject;
  46. static internal object TryGetUninitializedObjectWithFormatterServices(Type type)
  47. {
  48. if (getUninitializedObject == null)
  49. {
  50. try {
  51. var formatterServiceType = typeof(string).GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.FormatterServices");
  52. MethodInfo method = formatterServiceType?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  53. if (method != null)
  54. {
  55. getUninitializedObject = (Func<Type, object>)method.CreateDelegate(typeof(Func<Type, object>));
  56. }
  57. }
  58. catch { /* best efforts only */ }
  59. if(getUninitializedObject == null) getUninitializedObject = x => null;
  60. }
  61. return getUninitializedObject(type);
  62. }
  63. #endif
  64. #if FX11
  65. private BclHelpers() { } // not a static class for C# 1.2 reasons
  66. #endif
  67. const int FieldTimeSpanValue = 0x01, FieldTimeSpanScale = 0x02, FieldTimeSpanKind = 0x03;
  68. internal static readonly DateTime[] EpochOrigin = {
  69. new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
  70. new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc),
  71. new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local)
  72. };
  73. /// <summary>
  74. /// The default value for dates that are following google.protobuf.Timestamp semantics
  75. /// </summary>
  76. private static readonly DateTime TimestampEpoch = EpochOrigin[(int)DateTimeKind.Utc];
  77. /// <summary>
  78. /// Writes a TimeSpan to a protobuf stream using protobuf-net's own representation, bcl.TimeSpan
  79. /// </summary>
  80. public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest)
  81. {
  82. WriteTimeSpanImpl(timeSpan, dest, DateTimeKind.Unspecified);
  83. }
  84. private static void WriteTimeSpanImpl(TimeSpan timeSpan, ProtoWriter dest, DateTimeKind kind)
  85. {
  86. if (dest == null) throw new ArgumentNullException("dest");
  87. long value;
  88. switch(dest.WireType)
  89. {
  90. case WireType.String:
  91. case WireType.StartGroup:
  92. TimeSpanScale scale;
  93. value = timeSpan.Ticks;
  94. if (timeSpan == TimeSpan.MaxValue)
  95. {
  96. value = 1;
  97. scale = TimeSpanScale.MinMax;
  98. }
  99. else if (timeSpan == TimeSpan.MinValue)
  100. {
  101. value = -1;
  102. scale = TimeSpanScale.MinMax;
  103. }
  104. else if (value % TimeSpan.TicksPerDay == 0)
  105. {
  106. scale = TimeSpanScale.Days;
  107. value /= TimeSpan.TicksPerDay;
  108. }
  109. else if (value % TimeSpan.TicksPerHour == 0)
  110. {
  111. scale = TimeSpanScale.Hours;
  112. value /= TimeSpan.TicksPerHour;
  113. }
  114. else if (value % TimeSpan.TicksPerMinute == 0)
  115. {
  116. scale = TimeSpanScale.Minutes;
  117. value /= TimeSpan.TicksPerMinute;
  118. }
  119. else if (value % TimeSpan.TicksPerSecond == 0)
  120. {
  121. scale = TimeSpanScale.Seconds;
  122. value /= TimeSpan.TicksPerSecond;
  123. }
  124. else if (value % TimeSpan.TicksPerMillisecond == 0)
  125. {
  126. scale = TimeSpanScale.Milliseconds;
  127. value /= TimeSpan.TicksPerMillisecond;
  128. }
  129. else
  130. {
  131. scale = TimeSpanScale.Ticks;
  132. }
  133. SubItemToken token = ProtoWriter.StartSubItem(null, dest);
  134. if(value != 0) {
  135. ProtoWriter.WriteFieldHeader(FieldTimeSpanValue, WireType.SignedVariant, dest);
  136. ProtoWriter.WriteInt64(value, dest);
  137. }
  138. if(scale != TimeSpanScale.Days) {
  139. ProtoWriter.WriteFieldHeader(FieldTimeSpanScale, WireType.Variant, dest);
  140. ProtoWriter.WriteInt32((int)scale, dest);
  141. }
  142. if(kind != DateTimeKind.Unspecified)
  143. {
  144. ProtoWriter.WriteFieldHeader(FieldTimeSpanKind, WireType.Variant, dest);
  145. ProtoWriter.WriteInt32((int)kind, dest);
  146. }
  147. ProtoWriter.EndSubItem(token, dest);
  148. break;
  149. case WireType.Fixed64:
  150. ProtoWriter.WriteInt64(timeSpan.Ticks, dest);
  151. break;
  152. default:
  153. throw new ProtoException("Unexpected wire-type: " + dest.WireType.ToString());
  154. }
  155. }
  156. /// <summary>
  157. /// Parses a TimeSpan from a protobuf stream using protobuf-net's own representation, bcl.TimeSpan
  158. /// </summary>
  159. public static TimeSpan ReadTimeSpan(ProtoReader source)
  160. {
  161. DateTimeKind kind;
  162. long ticks = ReadTimeSpanTicks(source, out kind);
  163. if (ticks == long.MinValue) return TimeSpan.MinValue;
  164. if (ticks == long.MaxValue) return TimeSpan.MaxValue;
  165. return TimeSpan.FromTicks(ticks);
  166. }
  167. /// <summary>
  168. /// Parses a TimeSpan from a protobuf stream using the standardized format, google.protobuf.Duration
  169. /// </summary>
  170. public static TimeSpan ReadDuration(ProtoReader source)
  171. {
  172. long seconds = 0;
  173. int nanos = 0;
  174. SubItemToken token = ProtoReader.StartSubItem(source);
  175. int fieldNumber;
  176. while ((fieldNumber = source.ReadFieldHeader()) > 0)
  177. {
  178. switch (fieldNumber)
  179. {
  180. case 1:
  181. seconds = source.ReadInt64();
  182. break;
  183. case 2:
  184. nanos = source.ReadInt32();
  185. break;
  186. default:
  187. source.SkipField();
  188. break;
  189. }
  190. }
  191. ProtoReader.EndSubItem(token, source);
  192. return FromDurationSeconds(seconds, nanos);
  193. }
  194. /// <summary>
  195. /// Writes a TimeSpan to a protobuf stream using the standardized format, google.protobuf.Duration
  196. /// </summary>
  197. public static void WriteDuration(TimeSpan value, ProtoWriter dest)
  198. {
  199. int nanos;
  200. var seconds = ToDurationSeconds(value, out nanos);
  201. WriteSecondsNanos(seconds, nanos, dest);
  202. }
  203. private static void WriteSecondsNanos(long seconds, int nanos, ProtoWriter dest)
  204. {
  205. SubItemToken token = ProtoWriter.StartSubItem(null, dest);
  206. if (seconds != 0)
  207. {
  208. ProtoWriter.WriteFieldHeader(1, WireType.Variant, dest);
  209. ProtoWriter.WriteInt64(seconds, dest);
  210. }
  211. if (nanos != 0)
  212. {
  213. ProtoWriter.WriteFieldHeader(2, WireType.Variant, dest);
  214. ProtoWriter.WriteInt32(nanos, dest);
  215. }
  216. ProtoWriter.EndSubItem(token, dest);
  217. }
  218. /// <summary>
  219. /// Parses a DateTime from a protobuf stream using the standardized format, google.protobuf.Timestamp
  220. /// </summary>
  221. public static DateTime ReadTimestamp(ProtoReader source)
  222. {
  223. // note: DateTime is only defined for just over 0000 to just below 10000;
  224. // TimeSpan has a range of +/- 10,675,199 days === 29k years;
  225. // so we can just use epoch time delta
  226. return TimestampEpoch + ReadDuration(source);
  227. }
  228. /// <summary>
  229. /// Writes a DateTime to a protobuf stream using the standardized format, google.protobuf.Timestamp
  230. /// </summary>
  231. public static void WriteTimestamp(DateTime value, ProtoWriter dest)
  232. {
  233. int nanos;
  234. var seconds = ToDurationSeconds(value - TimestampEpoch, out nanos);
  235. if (nanos < 0)
  236. { // from Timestamp.proto:
  237. // "Negative second values with fractions must still have
  238. // non -negative nanos values that count forward in time."
  239. seconds--;
  240. nanos += 1000000000;
  241. }
  242. WriteSecondsNanos(seconds, nanos, dest);
  243. }
  244. static TimeSpan FromDurationSeconds(long seconds, int nanos)
  245. {
  246. long ticks = checked((seconds * TimeSpan.TicksPerSecond)
  247. + (nanos * TimeSpan.TicksPerMillisecond) / 1000000);
  248. return TimeSpan.FromTicks(ticks);
  249. }
  250. static long ToDurationSeconds(TimeSpan value, out int nanos)
  251. {
  252. nanos = (int)(((value.Ticks % TimeSpan.TicksPerSecond) * 1000000)
  253. / TimeSpan.TicksPerMillisecond);
  254. return value.Ticks / TimeSpan.TicksPerSecond;
  255. }
  256. /// <summary>
  257. /// Parses a DateTime from a protobuf stream
  258. /// </summary>
  259. public static DateTime ReadDateTime(ProtoReader source)
  260. {
  261. DateTimeKind kind;
  262. long ticks = ReadTimeSpanTicks(source, out kind);
  263. if (ticks == long.MinValue) return DateTime.MinValue;
  264. if (ticks == long.MaxValue) return DateTime.MaxValue;
  265. return EpochOrigin[(int)kind].AddTicks(ticks);
  266. }
  267. /// <summary>
  268. /// Writes a DateTime to a protobuf stream, excluding the <c>Kind</c>
  269. /// </summary>
  270. public static void WriteDateTime(DateTime value, ProtoWriter dest)
  271. {
  272. WriteDateTimeImpl(value, dest, false);
  273. }
  274. /// <summary>
  275. /// Writes a DateTime to a protobuf stream, including the <c>Kind</c>
  276. /// </summary>
  277. public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest)
  278. {
  279. WriteDateTimeImpl(value, dest, true);
  280. }
  281. private static void WriteDateTimeImpl(DateTime value, ProtoWriter dest, bool includeKind)
  282. {
  283. if (dest == null) throw new ArgumentNullException("dest");
  284. TimeSpan delta;
  285. switch (dest.WireType)
  286. {
  287. case WireType.StartGroup:
  288. case WireType.String:
  289. if (value == DateTime.MaxValue)
  290. {
  291. delta = TimeSpan.MaxValue;
  292. includeKind = false;
  293. }
  294. else if (value == DateTime.MinValue)
  295. {
  296. delta = TimeSpan.MinValue;
  297. includeKind = false;
  298. }
  299. else
  300. {
  301. delta = value - EpochOrigin[0];
  302. }
  303. break;
  304. default:
  305. delta = value - EpochOrigin[0];
  306. break;
  307. }
  308. WriteTimeSpanImpl(delta, dest, includeKind ? value.Kind : DateTimeKind.Unspecified);
  309. }
  310. private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind) {
  311. kind = DateTimeKind.Unspecified;
  312. switch (source.WireType)
  313. {
  314. case WireType.String:
  315. case WireType.StartGroup:
  316. SubItemToken token = ProtoReader.StartSubItem(source);
  317. int fieldNumber;
  318. TimeSpanScale scale = TimeSpanScale.Days;
  319. long value = 0;
  320. while ((fieldNumber = source.ReadFieldHeader()) > 0)
  321. {
  322. switch (fieldNumber)
  323. {
  324. case FieldTimeSpanScale:
  325. scale = (TimeSpanScale)source.ReadInt32();
  326. break;
  327. case FieldTimeSpanValue:
  328. source.Assert(WireType.SignedVariant);
  329. value = source.ReadInt64();
  330. break;
  331. case FieldTimeSpanKind:
  332. kind = (DateTimeKind)source.ReadInt32();
  333. switch(kind)
  334. {
  335. case DateTimeKind.Unspecified:
  336. case DateTimeKind.Utc:
  337. case DateTimeKind.Local:
  338. break; // fine
  339. default:
  340. throw new ProtoException("Invalid date/time kind: " + kind.ToString());
  341. }
  342. break;
  343. default:
  344. source.SkipField();
  345. break;
  346. }
  347. }
  348. ProtoReader.EndSubItem(token, source);
  349. switch (scale)
  350. {
  351. case TimeSpanScale.Days:
  352. return value * TimeSpan.TicksPerDay;
  353. case TimeSpanScale.Hours:
  354. return value * TimeSpan.TicksPerHour;
  355. case TimeSpanScale.Minutes:
  356. return value * TimeSpan.TicksPerMinute;
  357. case TimeSpanScale.Seconds:
  358. return value * TimeSpan.TicksPerSecond;
  359. case TimeSpanScale.Milliseconds:
  360. return value * TimeSpan.TicksPerMillisecond;
  361. case TimeSpanScale.Ticks:
  362. return value;
  363. case TimeSpanScale.MinMax:
  364. switch (value)
  365. {
  366. case 1: return long.MaxValue;
  367. case -1: return long.MinValue;
  368. default: throw new ProtoException("Unknown min/max value: " + value.ToString());
  369. }
  370. default:
  371. throw new ProtoException("Unknown timescale: " + scale.ToString());
  372. }
  373. case WireType.Fixed64:
  374. return source.ReadInt64();
  375. default:
  376. throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString());
  377. }
  378. }
  379. const int FieldDecimalLow = 0x01, FieldDecimalHigh = 0x02, FieldDecimalSignScale = 0x03;
  380. /// <summary>
  381. /// Parses a decimal from a protobuf stream
  382. /// </summary>
  383. public static decimal ReadDecimal(ProtoReader reader)
  384. {
  385. ulong low = 0;
  386. uint high = 0;
  387. uint signScale = 0;
  388. int fieldNumber;
  389. SubItemToken token = ProtoReader.StartSubItem(reader);
  390. while ((fieldNumber = reader.ReadFieldHeader()) > 0)
  391. {
  392. switch (fieldNumber)
  393. {
  394. case FieldDecimalLow: low = reader.ReadUInt64(); break;
  395. case FieldDecimalHigh: high = reader.ReadUInt32(); break;
  396. case FieldDecimalSignScale: signScale = reader.ReadUInt32(); break;
  397. default: reader.SkipField(); break;
  398. }
  399. }
  400. ProtoReader.EndSubItem(token, reader);
  401. if (low == 0 && high == 0) return decimal.Zero;
  402. int lo = (int)(low & 0xFFFFFFFFL),
  403. mid = (int)((low >> 32) & 0xFFFFFFFFL),
  404. hi = (int)high;
  405. bool isNeg = (signScale & 0x0001) == 0x0001;
  406. byte scale = (byte)((signScale & 0x01FE) >> 1);
  407. return new decimal(lo, mid, hi, isNeg, scale);
  408. }
  409. /// <summary>
  410. /// Writes a decimal to a protobuf stream
  411. /// </summary>
  412. public static void WriteDecimal(decimal value, ProtoWriter writer)
  413. {
  414. int[] bits = decimal.GetBits(value);
  415. ulong a = ((ulong)bits[1]) << 32, b = ((ulong)bits[0]) & 0xFFFFFFFFL;
  416. ulong low = a | b;
  417. uint high = (uint)bits[2];
  418. uint signScale = (uint)(((bits[3] >> 15) & 0x01FE) | ((bits[3] >> 31) & 0x0001));
  419. SubItemToken token = ProtoWriter.StartSubItem(null, writer);
  420. if (low != 0) {
  421. ProtoWriter.WriteFieldHeader(FieldDecimalLow, WireType.Variant, writer);
  422. ProtoWriter.WriteUInt64(low, writer);
  423. }
  424. if (high != 0)
  425. {
  426. ProtoWriter.WriteFieldHeader(FieldDecimalHigh, WireType.Variant, writer);
  427. ProtoWriter.WriteUInt32(high, writer);
  428. }
  429. if (signScale != 0)
  430. {
  431. ProtoWriter.WriteFieldHeader(FieldDecimalSignScale, WireType.Variant, writer);
  432. ProtoWriter.WriteUInt32(signScale, writer);
  433. }
  434. ProtoWriter.EndSubItem(token, writer);
  435. }
  436. const int FieldGuidLow = 1, FieldGuidHigh = 2;
  437. /// <summary>
  438. /// Writes a Guid to a protobuf stream
  439. /// </summary>
  440. public static void WriteGuid(Guid value, ProtoWriter dest)
  441. {
  442. byte[] blob = value.ToByteArray();
  443. SubItemToken token = ProtoWriter.StartSubItem(null, dest);
  444. if (value != Guid.Empty)
  445. {
  446. ProtoWriter.WriteFieldHeader(FieldGuidLow, WireType.Fixed64, dest);
  447. ProtoWriter.WriteBytes(blob, 0, 8, dest);
  448. ProtoWriter.WriteFieldHeader(FieldGuidHigh, WireType.Fixed64, dest);
  449. ProtoWriter.WriteBytes(blob, 8, 8, dest);
  450. }
  451. ProtoWriter.EndSubItem(token, dest);
  452. }
  453. /// <summary>
  454. /// Parses a Guid from a protobuf stream
  455. /// </summary>
  456. public static Guid ReadGuid(ProtoReader source)
  457. {
  458. ulong low = 0, high = 0;
  459. int fieldNumber;
  460. SubItemToken token = ProtoReader.StartSubItem(source);
  461. while ((fieldNumber = source.ReadFieldHeader()) > 0)
  462. {
  463. switch (fieldNumber)
  464. {
  465. case FieldGuidLow: low = source.ReadUInt64(); break;
  466. case FieldGuidHigh: high = source.ReadUInt64(); break;
  467. default: source.SkipField(); break;
  468. }
  469. }
  470. ProtoReader.EndSubItem(token, source);
  471. if(low == 0 && high == 0) return Guid.Empty;
  472. uint a = (uint)(low >> 32), b = (uint)low, c = (uint)(high >> 32), d= (uint)high;
  473. return new Guid((int)b, (short)a, (short)(a >> 16),
  474. (byte)d, (byte)(d >> 8), (byte)(d >> 16), (byte)(d >> 24),
  475. (byte)c, (byte)(c >> 8), (byte)(c >> 16), (byte)(c >> 24));
  476. }
  477. private const int
  478. FieldExistingObjectKey = 1,
  479. FieldNewObjectKey = 2,
  480. FieldExistingTypeKey = 3,
  481. FieldNewTypeKey = 4,
  482. FieldTypeName = 8,
  483. FieldObject = 10;
  484. /// <summary>
  485. /// Optional behaviours that introduce .NET-specific functionality
  486. /// </summary>
  487. [Flags]
  488. public enum NetObjectOptions : byte
  489. {
  490. /// <summary>
  491. /// No special behaviour
  492. /// </summary>
  493. None = 0,
  494. /// <summary>
  495. /// Enables full object-tracking/full-graph support.
  496. /// </summary>
  497. AsReference = 1,
  498. /// <summary>
  499. /// Embeds the type information into the stream, allowing usage with types not known in advance.
  500. /// </summary>
  501. DynamicType = 2,
  502. /// <summary>
  503. /// If false, the constructor for the type is bypassed during deserialization, meaning any field initializers
  504. /// or other initialization code is skipped.
  505. /// </summary>
  506. UseConstructor = 4,
  507. /// <summary>
  508. /// Should the object index be reserved, rather than creating an object promptly
  509. /// </summary>
  510. LateSet = 8
  511. }
  512. /// <summary>
  513. /// Reads an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc.
  514. /// </summary>
  515. public static object ReadNetObject(object value, ProtoReader source, int key, Type type, NetObjectOptions options)
  516. {
  517. #if FEAT_IKVM
  518. throw new NotSupportedException();
  519. #else
  520. SubItemToken token = ProtoReader.StartSubItem(source);
  521. int fieldNumber;
  522. int newObjectKey = -1, newTypeKey = -1, tmp;
  523. while ((fieldNumber = source.ReadFieldHeader()) > 0)
  524. {
  525. switch (fieldNumber)
  526. {
  527. case FieldExistingObjectKey:
  528. tmp = source.ReadInt32();
  529. value = source.NetCache.GetKeyedObject(tmp);
  530. break;
  531. case FieldNewObjectKey:
  532. newObjectKey = source.ReadInt32();
  533. break;
  534. case FieldExistingTypeKey:
  535. tmp = source.ReadInt32();
  536. type = (Type)source.NetCache.GetKeyedObject(tmp);
  537. key = source.GetTypeKey(ref type);
  538. break;
  539. case FieldNewTypeKey:
  540. newTypeKey = source.ReadInt32();
  541. break;
  542. case FieldTypeName:
  543. string typeName = source.ReadString();
  544. type = source.DeserializeType(typeName);
  545. if(type == null)
  546. {
  547. throw new ProtoException("Unable to resolve type: " + typeName + " (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)");
  548. }
  549. if (type == typeof(string))
  550. {
  551. key = -1;
  552. }
  553. else
  554. {
  555. key = source.GetTypeKey(ref type);
  556. if (key < 0)
  557. throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name);
  558. }
  559. break;
  560. case FieldObject:
  561. bool isString = type == typeof(string);
  562. bool wasNull = value == null;
  563. bool lateSet = wasNull && (isString || ((options & NetObjectOptions.LateSet) != 0));
  564. if (newObjectKey >= 0 && !lateSet)
  565. {
  566. if (value == null)
  567. {
  568. source.TrapNextObject(newObjectKey);
  569. }
  570. else
  571. {
  572. source.NetCache.SetKeyedObject(newObjectKey, value);
  573. }
  574. if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type);
  575. }
  576. object oldValue = value;
  577. if (isString)
  578. {
  579. value = source.ReadString();
  580. }
  581. else
  582. {
  583. value = ProtoReader.ReadTypedObject(oldValue, key, source, type);
  584. }
  585. if (newObjectKey >= 0)
  586. {
  587. if(wasNull && !lateSet)
  588. { // this both ensures (via exception) that it *was* set, and makes sure we don't shout
  589. // about changed references
  590. oldValue = source.NetCache.GetKeyedObject(newObjectKey);
  591. }
  592. if (lateSet)
  593. {
  594. source.NetCache.SetKeyedObject(newObjectKey, value);
  595. if (newTypeKey >= 0) source.NetCache.SetKeyedObject(newTypeKey, type);
  596. }
  597. }
  598. if (newObjectKey >= 0 && !lateSet && !ReferenceEquals(oldValue, value))
  599. {
  600. throw new ProtoException("A reference-tracked object changed reference during deserialization");
  601. }
  602. if (newObjectKey < 0 && newTypeKey >= 0)
  603. { // have a new type, but not a new object
  604. source.NetCache.SetKeyedObject(newTypeKey, type);
  605. }
  606. break;
  607. default:
  608. source.SkipField();
  609. break;
  610. }
  611. }
  612. if(newObjectKey >= 0 && (options & NetObjectOptions.AsReference) == 0)
  613. {
  614. throw new ProtoException("Object key in input stream, but reference-tracking was not expected");
  615. }
  616. ProtoReader.EndSubItem(token, source);
  617. return value;
  618. #endif
  619. }
  620. /// <summary>
  621. /// Writes an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc.
  622. /// </summary>
  623. public static void WriteNetObject(object value, ProtoWriter dest, int key, NetObjectOptions options)
  624. {
  625. #if FEAT_IKVM
  626. throw new NotSupportedException();
  627. #else
  628. if (dest == null) throw new ArgumentNullException("dest");
  629. bool dynamicType = (options & NetObjectOptions.DynamicType) != 0,
  630. asReference = (options & NetObjectOptions.AsReference) != 0;
  631. WireType wireType = dest.WireType;
  632. SubItemToken token = ProtoWriter.StartSubItem(null, dest);
  633. bool writeObject = true;
  634. if (asReference)
  635. {
  636. bool existing;
  637. int objectKey = dest.NetCache.AddObjectKey(value, out existing);
  638. ProtoWriter.WriteFieldHeader(existing ? FieldExistingObjectKey : FieldNewObjectKey, WireType.Variant, dest);
  639. ProtoWriter.WriteInt32(objectKey, dest);
  640. if (existing)
  641. {
  642. writeObject = false;
  643. }
  644. }
  645. if (writeObject)
  646. {
  647. if (dynamicType)
  648. {
  649. bool existing;
  650. Type type = value.GetType();
  651. if (!(value is string))
  652. {
  653. key = dest.GetTypeKey(ref type);
  654. if (key < 0) throw new InvalidOperationException("Dynamic type is not a contract-type: " + type.Name);
  655. }
  656. int typeKey = dest.NetCache.AddObjectKey(type, out existing);
  657. ProtoWriter.WriteFieldHeader(existing ? FieldExistingTypeKey : FieldNewTypeKey, WireType.Variant, dest);
  658. ProtoWriter.WriteInt32(typeKey, dest);
  659. if (!existing)
  660. {
  661. ProtoWriter.WriteFieldHeader(FieldTypeName, WireType.String, dest);
  662. ProtoWriter.WriteString(dest.SerializeType(type), dest);
  663. }
  664. }
  665. ProtoWriter.WriteFieldHeader(FieldObject, wireType, dest);
  666. if (value is string)
  667. {
  668. ProtoWriter.WriteString((string)value, dest);
  669. }
  670. else {
  671. ProtoWriter.WriteObject(value, key, dest);
  672. }
  673. }
  674. ProtoWriter.EndSubItem(token, dest);
  675. #endif
  676. }
  677. }
  678. }