ProtobufSerializer.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. //new ProtobufModelSerializer.Serialize(stream, typeof(T));
  21. ProtoBuf.Serializer.Serialize(stream, obj);
  22. }
  23. public static T DeserializeFromStream<T>(Stream stream)
  24. where T : class
  25. {
  26. //return ProtoBuf.Serializer.Deserialize<T>(stream);
  27. return ProtobufModelSerializer.Deserialize(stream, null, typeof(T)) as T;
  28. }
  29. public static object DeserializeFromStream(Stream stream, Type type)
  30. {
  31. //throw new NotImplementedException();
  32. return ProtobufModelSerializer.Deserialize(stream, null, type);
  33. }
  34. public static void SerializeToFile<T>(T obj, string file)
  35. {
  36. using (Stream stream = File.Open(file, FileMode.Create))
  37. {
  38. SerializeToStream<T>(obj, stream);
  39. }
  40. }
  41. public static T DeserializeFromFile<T>(string file)
  42. where T : class
  43. {
  44. using (Stream stream = File.OpenRead(file))
  45. {
  46. return DeserializeFromStream<T>(stream);
  47. }
  48. }
  49. }
  50. }