2
0

ProtobufSerializer.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.IO;
  3. namespace MediaBrowser.Common.Serialization
  4. {
  5. /// <summary>
  6. /// Protocol buffers is google's binary serialization format. This is a .NET implementation of it.
  7. /// You have to tag your classes with some annoying attributes, but in return you get the fastest serialization around with the smallest possible output.
  8. /// </summary>
  9. public static class ProtobufSerializer
  10. {
  11. /// <summary>
  12. /// This is an auto-generated Protobuf Serialization assembly for best performance.
  13. /// It is created during the Model project's post-build event.
  14. /// This means that this class can currently only handle types within the Model project.
  15. /// If we need to, we can always add a param indicating whether or not the model serializer should be used.
  16. /// </summary>
  17. private static ProtobufModelSerializer ProtobufModelSerializer = new ProtobufModelSerializer();
  18. public static void SerializeToStream<T>(T obj, Stream stream)
  19. {
  20. ProtobufModelSerializer.Serialize(stream, obj);
  21. }
  22. public static T DeserializeFromStream<T>(Stream stream)
  23. where T : class
  24. {
  25. return ProtobufModelSerializer.Deserialize(stream, null, typeof(T)) as T;
  26. }
  27. public static object DeserializeFromStream(Stream stream, Type type)
  28. {
  29. return ProtobufModelSerializer.Deserialize(stream, null, type);
  30. }
  31. public static void SerializeToFile<T>(T obj, string file)
  32. {
  33. using (Stream stream = File.Open(file, FileMode.Create))
  34. {
  35. SerializeToStream<T>(obj, stream);
  36. }
  37. }
  38. public static T DeserializeFromFile<T>(string file)
  39. where T : class
  40. {
  41. using (Stream stream = File.OpenRead(file))
  42. {
  43. return DeserializeFromStream<T>(stream);
  44. }
  45. }
  46. }
  47. }