2012-09-03 21:56:30 +00:00
using System ;
using System.IO ;
2012-08-23 05:45:26 +00:00
namespace MediaBrowser.Common.Serialization
{
2012-08-23 12:26:08 +00:00
/// <summary>
/// Protocol buffers is google's binary serialization format. This is a .NET implementation of it.
/// You have to tag your classes with some annoying attributes, but in return you get the fastest serialization around with the smallest possible output.
/// </summary>
2012-08-23 05:45:26 +00:00
public static class ProtobufSerializer
{
2012-09-09 05:30:07 +00:00
/// <summary>
/// This is an auto-generated Protobuf Serialization assembly for best performance.
/// It is created during the Model project's post-build event.
/// This means that this class can currently only handle types within the Model project.
/// If we need to, we can always add a param indicating whether or not the model serializer should be used.
/// </summary>
private static ProtobufModelSerializer ProtobufModelSerializer = new ProtobufModelSerializer ( ) ;
2012-08-23 05:45:26 +00:00
public static void SerializeToStream < T > ( T obj , Stream stream )
{
2012-09-09 12:53:04 +00:00
ProtobufModelSerializer . Serialize ( stream , obj ) ;
2012-08-23 05:45:26 +00:00
}
public static T DeserializeFromStream < T > ( Stream stream )
2012-09-09 05:30:07 +00:00
where T : class
2012-08-23 05:45:26 +00:00
{
2012-09-09 05:30:07 +00:00
return ProtobufModelSerializer . Deserialize ( stream , null , typeof ( T ) ) as T ;
2012-08-23 05:45:26 +00:00
}
2012-09-03 21:56:30 +00:00
public static object DeserializeFromStream ( Stream stream , Type type )
{
2012-09-09 05:30:07 +00:00
return ProtobufModelSerializer . Deserialize ( stream , null , type ) ;
2012-09-03 21:56:30 +00:00
}
2012-09-09 05:30:07 +00:00
2012-08-23 05:45:26 +00:00
public static void SerializeToFile < T > ( T obj , string file )
{
using ( Stream stream = File . Open ( file , FileMode . Create ) )
{
SerializeToStream < T > ( obj , stream ) ;
}
}
public static T DeserializeFromFile < T > ( string file )
2012-09-09 05:30:07 +00:00
where T : class
2012-08-23 05:45:26 +00:00
{
using ( Stream stream = File . OpenRead ( file ) )
{
return DeserializeFromStream < T > ( stream ) ;
}
}
}
}