Serializer.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. 
  2. using ProtoBuf.Meta;
  3. using System;
  4. using System.IO;
  5. #if !NO_GENERICS
  6. using System.Collections.Generic;
  7. #endif
  8. #if FEAT_IKVM
  9. using Type = IKVM.Reflection.Type;
  10. using IKVM.Reflection;
  11. #else
  12. #endif
  13. namespace ProtoBuf
  14. {
  15. /// <summary>
  16. /// Provides protocol-buffer serialization capability for concrete, attributed types. This
  17. /// is a *default* model, but custom serializer models are also supported.
  18. /// </summary>
  19. /// <remarks>
  20. /// Protocol-buffer serialization is a compact binary format, designed to take
  21. /// advantage of sparse data and knowledge of specific data types; it is also
  22. /// extensible, allowing a type to be deserialized / merged even if some data is
  23. /// not recognised.
  24. /// </remarks>
  25. public
  26. #if FX11
  27. sealed
  28. #else
  29. static
  30. #endif
  31. class Serializer
  32. {
  33. #if FX11
  34. private Serializer() { } // not a static class for C# 1.2 reasons
  35. #endif
  36. #if !NO_RUNTIME && !NO_GENERICS
  37. /// <summary>
  38. /// Suggest a .proto definition for the given type
  39. /// </summary>
  40. /// <typeparam name="T">The type to generate a .proto definition for</typeparam>
  41. /// <returns>The .proto definition as a string</returns>
  42. public static string GetProto<T>() => GetProto<T>(ProtoSyntax.Proto2);
  43. /// <summary>
  44. /// Suggest a .proto definition for the given type
  45. /// </summary>
  46. /// <typeparam name="T">The type to generate a .proto definition for</typeparam>
  47. /// <returns>The .proto definition as a string</returns>
  48. public static string GetProto<T>(ProtoSyntax syntax)
  49. {
  50. return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof(T)), syntax);
  51. }
  52. /// <summary>
  53. /// Create a deep clone of the supplied instance; any sub-items are also cloned.
  54. /// </summary>
  55. public static T DeepClone<T>(T instance)
  56. {
  57. return instance == null ? instance : (T)RuntimeTypeModel.Default.DeepClone(instance);
  58. }
  59. /// <summary>
  60. /// Applies a protocol-buffer stream to an existing instance.
  61. /// </summary>
  62. /// <typeparam name="T">The type being merged.</typeparam>
  63. /// <param name="instance">The existing instance to be modified (can be null).</param>
  64. /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
  65. /// <returns>The updated instance; this may be different to the instance argument if
  66. /// either the original instance was null, or the stream defines a known sub-type of the
  67. /// original instance.</returns>
  68. public static T Merge<T>(Stream source, T instance)
  69. {
  70. return (T)RuntimeTypeModel.Default.Deserialize(source, instance, typeof(T));
  71. }
  72. /// <summary>
  73. /// Creates a new instance from a protocol-buffer stream
  74. /// </summary>
  75. /// <typeparam name="T">The type to be created.</typeparam>
  76. /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
  77. /// <returns>A new, initialized instance.</returns>
  78. public static T Deserialize<T>(Stream source)
  79. {
  80. return (T) RuntimeTypeModel.Default.Deserialize(source, null, typeof(T));
  81. }
  82. /// <summary>
  83. /// Creates a new instance from a protocol-buffer stream
  84. /// </summary>
  85. /// <param name="type">The type to be created.</param>
  86. /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
  87. /// <returns>A new, initialized instance.</returns>
  88. public static object Deserialize(System.Type type, Stream source)
  89. {
  90. return RuntimeTypeModel.Default.Deserialize(source, null, type);
  91. }
  92. /// <summary>
  93. /// Writes a protocol-buffer representation of the given instance to the supplied stream.
  94. /// </summary>
  95. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  96. /// <param name="destination">The destination stream to write to.</param>
  97. public static void Serialize<T>(Stream destination, T instance)
  98. {
  99. if(instance != null) {
  100. RuntimeTypeModel.Default.Serialize(destination, instance);
  101. }
  102. }
  103. /// <summary>
  104. /// Serializes a given instance and deserializes it as a different type;
  105. /// this can be used to translate between wire-compatible objects (where
  106. /// two .NET types represent the same data), or to promote/demote a type
  107. /// through an inheritance hierarchy.
  108. /// </summary>
  109. /// <remarks>No assumption of compatibility is made between the types.</remarks>
  110. /// <typeparam name="TFrom">The type of the object being copied.</typeparam>
  111. /// <typeparam name="TTo">The type of the new object to be created.</typeparam>
  112. /// <param name="instance">The existing instance to use as a template.</param>
  113. /// <returns>A new instane of type TNewType, with the data from TOldType.</returns>
  114. public static TTo ChangeType<TFrom,TTo>(TFrom instance)
  115. {
  116. using (MemoryStream ms = new MemoryStream())
  117. {
  118. Serialize<TFrom>(ms, instance);
  119. ms.Position = 0;
  120. return Deserialize<TTo>(ms);
  121. }
  122. }
  123. #if PLAT_BINARYFORMATTER && !(WINRT || PHONE8 || COREFX)
  124. /// <summary>
  125. /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
  126. /// </summary>
  127. /// <typeparam name="T">The type being serialized.</typeparam>
  128. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  129. /// <param name="info">The destination SerializationInfo to write to.</param>
  130. public static void Serialize<T>(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable
  131. {
  132. Serialize<T>(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance);
  133. }
  134. /// <summary>
  135. /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo.
  136. /// </summary>
  137. /// <typeparam name="T">The type being serialized.</typeparam>
  138. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  139. /// <param name="info">The destination SerializationInfo to write to.</param>
  140. /// <param name="context">Additional information about this serialization operation.</param>
  141. public static void Serialize<T>(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable
  142. {
  143. // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
  144. if (info == null) throw new ArgumentNullException("info");
  145. if (instance == null) throw new ArgumentNullException("instance");
  146. if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
  147. using (MemoryStream ms = new MemoryStream())
  148. {
  149. RuntimeTypeModel.Default.Serialize(ms, instance, context);
  150. info.AddValue(ProtoBinaryField, ms.ToArray());
  151. }
  152. }
  153. #endif
  154. #if PLAT_XMLSERIALIZER
  155. /// <summary>
  156. /// Writes a protocol-buffer representation of the given instance to the supplied XmlWriter.
  157. /// </summary>
  158. /// <typeparam name="T">The type being serialized.</typeparam>
  159. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  160. /// <param name="writer">The destination XmlWriter to write to.</param>
  161. public static void Serialize<T>(System.Xml.XmlWriter writer, T instance) where T : System.Xml.Serialization.IXmlSerializable
  162. {
  163. if (writer == null) throw new ArgumentNullException("writer");
  164. if (instance == null) throw new ArgumentNullException("instance");
  165. using (MemoryStream ms = new MemoryStream())
  166. {
  167. Serializer.Serialize(ms, instance);
  168. writer.WriteBase64(Helpers.GetBuffer(ms), 0, (int)ms.Length);
  169. }
  170. }
  171. /// <summary>
  172. /// Applies a protocol-buffer from an XmlReader to an existing instance.
  173. /// </summary>
  174. /// <typeparam name="T">The type being merged.</typeparam>
  175. /// <param name="instance">The existing instance to be modified (cannot be null).</param>
  176. /// <param name="reader">The XmlReader containing the data to apply to the instance (cannot be null).</param>
  177. public static void Merge<T>(System.Xml.XmlReader reader, T instance) where T : System.Xml.Serialization.IXmlSerializable
  178. {
  179. if (reader == null) throw new ArgumentNullException("reader");
  180. if (instance == null) throw new ArgumentNullException("instance");
  181. const int LEN = 4096;
  182. byte[] buffer = new byte[LEN];
  183. int read;
  184. using (MemoryStream ms = new MemoryStream())
  185. {
  186. int depth = reader.Depth;
  187. while(reader.Read() && reader.Depth > depth)
  188. {
  189. if (reader.NodeType == System.Xml.XmlNodeType.Text)
  190. {
  191. while ((read = reader.ReadContentAsBase64(buffer, 0, LEN)) > 0)
  192. {
  193. ms.Write(buffer, 0, read);
  194. }
  195. if (reader.Depth <= depth) break;
  196. }
  197. }
  198. ms.Position = 0;
  199. Serializer.Merge(ms, instance);
  200. }
  201. }
  202. #endif
  203. private const string ProtoBinaryField = "proto";
  204. #if PLAT_BINARYFORMATTER && !NO_GENERICS && !(WINRT || PHONE8 || COREFX)
  205. /// <summary>
  206. /// Applies a protocol-buffer from a SerializationInfo to an existing instance.
  207. /// </summary>
  208. /// <typeparam name="T">The type being merged.</typeparam>
  209. /// <param name="instance">The existing instance to be modified (cannot be null).</param>
  210. /// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
  211. public static void Merge<T>(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable
  212. {
  213. Merge<T>(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance);
  214. }
  215. /// <summary>
  216. /// Applies a protocol-buffer from a SerializationInfo to an existing instance.
  217. /// </summary>
  218. /// <typeparam name="T">The type being merged.</typeparam>
  219. /// <param name="instance">The existing instance to be modified (cannot be null).</param>
  220. /// <param name="info">The SerializationInfo containing the data to apply to the instance (cannot be null).</param>
  221. /// <param name="context">Additional information about this serialization operation.</param>
  222. public static void Merge<T>(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable
  223. {
  224. // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization)
  225. if (info == null) throw new ArgumentNullException("info");
  226. if (instance == null) throw new ArgumentNullException("instance");
  227. if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance");
  228. byte[] buffer = (byte[])info.GetValue(ProtoBinaryField, typeof(byte[]));
  229. using (MemoryStream ms = new MemoryStream(buffer))
  230. {
  231. T result = (T)RuntimeTypeModel.Default.Deserialize(ms, instance, typeof(T), context);
  232. if (!ReferenceEquals(result, instance))
  233. {
  234. throw new ProtoException("Deserialization changed the instance; cannot succeed.");
  235. }
  236. }
  237. }
  238. #endif
  239. #if !NO_GENERICS
  240. /// <summary>
  241. /// Precompiles the serializer for a given type.
  242. /// </summary>
  243. public static void PrepareSerializer<T>()
  244. {
  245. #if FEAT_COMPILER
  246. RuntimeTypeModel model = RuntimeTypeModel.Default;
  247. model[model.MapType(typeof(T))].CompileInPlace();
  248. #endif
  249. }
  250. #if PLAT_BINARYFORMATTER && !(WINRT || PHONE8 || COREFX)
  251. /// <summary>
  252. /// Creates a new IFormatter that uses protocol-buffer [de]serialization.
  253. /// </summary>
  254. /// <typeparam name="T">The type of object to be [de]deserialized by the formatter.</typeparam>
  255. /// <returns>A new IFormatter to be used during [de]serialization.</returns>
  256. public static System.Runtime.Serialization.IFormatter CreateFormatter<T>()
  257. {
  258. #if FEAT_IKVM
  259. throw new NotSupportedException();
  260. #else
  261. return RuntimeTypeModel.Default.CreateFormatter(typeof(T));
  262. #endif
  263. }
  264. #endif
  265. /// <summary>
  266. /// Reads a sequence of consecutive length-prefixed items from a stream, using
  267. /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag
  268. /// are directly comparable to serializing multiple items in succession
  269. /// (use the <see cref="ListItemTag"/> tag to emulate the implicit behavior
  270. /// when serializing a list/array). When a tag is
  271. /// specified, any records with different tags are silently omitted. The
  272. /// tag is ignored. The tag is ignored for fixed-length prefixes.
  273. /// </summary>
  274. /// <typeparam name="T">The type of object to deserialize.</typeparam>
  275. /// <param name="source">The binary stream containing the serialized records.</param>
  276. /// <param name="style">The prefix style used in the data.</param>
  277. /// <param name="fieldNumber">The tag of records to return (if non-positive, then no tag is
  278. /// expected and all records are returned).</param>
  279. /// <returns>The sequence of deserialized objects.</returns>
  280. public static IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int fieldNumber)
  281. {
  282. return RuntimeTypeModel.Default.DeserializeItems<T>(source, style, fieldNumber);
  283. }
  284. /// <summary>
  285. /// Creates a new instance from a protocol-buffer stream that has a length-prefix
  286. /// on data (to assist with network IO).
  287. /// </summary>
  288. /// <typeparam name="T">The type to be created.</typeparam>
  289. /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
  290. /// <param name="style">How to encode the length prefix.</param>
  291. /// <returns>A new, initialized instance.</returns>
  292. public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style)
  293. {
  294. return DeserializeWithLengthPrefix<T>(source, style, 0);
  295. }
  296. /// <summary>
  297. /// Creates a new instance from a protocol-buffer stream that has a length-prefix
  298. /// on data (to assist with network IO).
  299. /// </summary>
  300. /// <typeparam name="T">The type to be created.</typeparam>
  301. /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
  302. /// <param name="style">How to encode the length prefix.</param>
  303. /// <param name="fieldNumber">The expected tag of the item (only used with base-128 prefix style).</param>
  304. /// <returns>A new, initialized instance.</returns>
  305. public static T DeserializeWithLengthPrefix<T>(Stream source, PrefixStyle style, int fieldNumber)
  306. {
  307. RuntimeTypeModel model = RuntimeTypeModel.Default;
  308. return (T)model.DeserializeWithLengthPrefix(source, null, model.MapType(typeof(T)), style, fieldNumber);
  309. }
  310. /// <summary>
  311. /// Applies a protocol-buffer stream to an existing instance, using length-prefixed
  312. /// data - useful with network IO.
  313. /// </summary>
  314. /// <typeparam name="T">The type being merged.</typeparam>
  315. /// <param name="instance">The existing instance to be modified (can be null).</param>
  316. /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
  317. /// <param name="style">How to encode the length prefix.</param>
  318. /// <returns>The updated instance; this may be different to the instance argument if
  319. /// either the original instance was null, or the stream defines a known sub-type of the
  320. /// original instance.</returns>
  321. public static T MergeWithLengthPrefix<T>(Stream source, T instance, PrefixStyle style)
  322. {
  323. RuntimeTypeModel model = RuntimeTypeModel.Default;
  324. return (T)model.DeserializeWithLengthPrefix(source, instance, model.MapType(typeof(T)), style, 0);
  325. }
  326. /// <summary>
  327. /// Writes a protocol-buffer representation of the given instance to the supplied stream,
  328. /// with a length-prefix. This is useful for socket programming,
  329. /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
  330. /// from an ongoing stream.
  331. /// </summary>
  332. /// <typeparam name="T">The type being serialized.</typeparam>
  333. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  334. /// <param name="style">How to encode the length prefix.</param>
  335. /// <param name="destination">The destination stream to write to.</param>
  336. public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style)
  337. {
  338. SerializeWithLengthPrefix<T>(destination, instance, style, 0);
  339. }
  340. /// <summary>
  341. /// Writes a protocol-buffer representation of the given instance to the supplied stream,
  342. /// with a length-prefix. This is useful for socket programming,
  343. /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
  344. /// from an ongoing stream.
  345. /// </summary>
  346. /// <typeparam name="T">The type being serialized.</typeparam>
  347. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  348. /// <param name="style">How to encode the length prefix.</param>
  349. /// <param name="destination">The destination stream to write to.</param>
  350. /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
  351. public static void SerializeWithLengthPrefix<T>(Stream destination, T instance, PrefixStyle style, int fieldNumber)
  352. {
  353. RuntimeTypeModel model = RuntimeTypeModel.Default;
  354. model.SerializeWithLengthPrefix(destination, instance, model.MapType(typeof(T)), style, fieldNumber);
  355. }
  356. #endif
  357. /// <summary>Indicates the number of bytes expected for the next message.</summary>
  358. /// <param name="source">The stream containing the data to investigate for a length.</param>
  359. /// <param name="style">The algorithm used to encode the length.</param>
  360. /// <param name="length">The length of the message, if it could be identified.</param>
  361. /// <returns>True if a length could be obtained, false otherwise.</returns>
  362. public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length)
  363. {
  364. int fieldNumber, bytesRead;
  365. length = ProtoReader.ReadLengthPrefix(source, false, style, out fieldNumber, out bytesRead);
  366. return bytesRead > 0;
  367. }
  368. /// <summary>Indicates the number of bytes expected for the next message.</summary>
  369. /// <param name="buffer">The buffer containing the data to investigate for a length.</param>
  370. /// <param name="index">The offset of the first byte to read from the buffer.</param>
  371. /// <param name="count">The number of bytes to read from the buffer.</param>
  372. /// <param name="style">The algorithm used to encode the length.</param>
  373. /// <param name="length">The length of the message, if it could be identified.</param>
  374. /// <returns>True if a length could be obtained, false otherwise.</returns>
  375. public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length)
  376. {
  377. using (Stream source = new MemoryStream(buffer, index, count))
  378. {
  379. return TryReadLengthPrefix(source, style, out length);
  380. }
  381. }
  382. #endif
  383. /// <summary>
  384. /// The field number that is used as a default when serializing/deserializing a list of objects.
  385. /// The data is treated as repeated message with field number 1.
  386. /// </summary>
  387. public const int ListItemTag = 1;
  388. #if !NO_RUNTIME
  389. /// <summary>
  390. /// Provides non-generic access to the default serializer.
  391. /// </summary>
  392. public
  393. #if FX11
  394. sealed
  395. #else
  396. static
  397. #endif
  398. class NonGeneric
  399. {
  400. #if FX11
  401. private NonGeneric() { } // not a static class for C# 1.2 reasons
  402. #endif
  403. /// <summary>
  404. /// Create a deep clone of the supplied instance; any sub-items are also cloned.
  405. /// </summary>
  406. public static object DeepClone(object instance)
  407. {
  408. return instance == null ? null : RuntimeTypeModel.Default.DeepClone(instance);
  409. }
  410. /// <summary>
  411. /// Writes a protocol-buffer representation of the given instance to the supplied stream.
  412. /// </summary>
  413. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  414. /// <param name="dest">The destination stream to write to.</param>
  415. public static void Serialize(Stream dest, object instance)
  416. {
  417. if (instance != null)
  418. {
  419. RuntimeTypeModel.Default.Serialize(dest, instance);
  420. }
  421. }
  422. /// <summary>
  423. /// Creates a new instance from a protocol-buffer stream
  424. /// </summary>
  425. /// <param name="type">The type to be created.</param>
  426. /// <param name="source">The binary stream to apply to the new instance (cannot be null).</param>
  427. /// <returns>A new, initialized instance.</returns>
  428. public static object Deserialize(System.Type type, Stream source)
  429. {
  430. return RuntimeTypeModel.Default.Deserialize(source, null, type);
  431. }
  432. /// <summary>Applies a protocol-buffer stream to an existing instance.</summary>
  433. /// <param name="instance">The existing instance to be modified (cannot be null).</param>
  434. /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
  435. /// <returns>The updated instance</returns>
  436. public static object Merge(Stream source, object instance)
  437. {
  438. if (instance == null) throw new ArgumentNullException("instance");
  439. return RuntimeTypeModel.Default.Deserialize(source, instance, instance.GetType(), null);
  440. }
  441. /// <summary>
  442. /// Writes a protocol-buffer representation of the given instance to the supplied stream,
  443. /// with a length-prefix. This is useful for socket programming,
  444. /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back
  445. /// from an ongoing stream.
  446. /// </summary>
  447. /// <param name="instance">The existing instance to be serialized (cannot be null).</param>
  448. /// <param name="style">How to encode the length prefix.</param>
  449. /// <param name="destination">The destination stream to write to.</param>
  450. /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param>
  451. public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber)
  452. {
  453. if (instance == null) throw new ArgumentNullException("instance");
  454. RuntimeTypeModel model = RuntimeTypeModel.Default;
  455. model.SerializeWithLengthPrefix(destination, instance, model.MapType(instance.GetType()), style, fieldNumber);
  456. }
  457. /// <summary>
  458. /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
  459. /// data - useful with network IO.
  460. /// </summary>
  461. /// <param name="value">The existing instance to be modified (can be null).</param>
  462. /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
  463. /// <param name="style">How to encode the length prefix.</param>
  464. /// <param name="resolver">Used to resolve types on a per-field basis.</param>
  465. /// <returns>The updated instance; this may be different to the instance argument if
  466. /// either the original instance was null, or the stream defines a known sub-type of the
  467. /// original instance.</returns>
  468. public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value)
  469. {
  470. value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver);
  471. return value != null;
  472. }
  473. /// <summary>
  474. /// Indicates whether the supplied type is explicitly modelled by the model
  475. /// </summary>
  476. public static bool CanSerialize(Type type)
  477. {
  478. return RuntimeTypeModel.Default.IsDefined(type);
  479. }
  480. }
  481. /// <summary>
  482. /// Global switches that change the behavior of protobuf-net
  483. /// </summary>
  484. public
  485. #if FX11
  486. sealed
  487. #else
  488. static
  489. #endif
  490. class GlobalOptions
  491. {
  492. #if FX11
  493. private GlobalOptions() { } // not a static class for C# 1.2 reasons
  494. #endif
  495. /// <summary>
  496. /// <see cref="RuntimeTypeModel.InferTagFromNameDefault"/>
  497. /// </summary>
  498. [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)]
  499. public static bool InferTagFromName
  500. {
  501. get { return RuntimeTypeModel.Default.InferTagFromNameDefault; }
  502. set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; }
  503. }
  504. }
  505. #endif
  506. /// <summary>
  507. /// Maps a field-number to a type
  508. /// </summary>
  509. public delegate Type TypeResolver(int fieldNumber);
  510. /// <summary>
  511. /// Releases any internal buffers that have been reserved for efficiency; this does not affect any serialization
  512. /// operations; simply: it can be used (optionally) to release the buffers for garbage collection (at the expense
  513. /// of having to re-allocate a new buffer for the next operation, rather than re-use prior buffers).
  514. /// </summary>
  515. public static void FlushPool()
  516. {
  517. BufferPool.Flush();
  518. }
  519. }
  520. }