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