using System.IO;
namespace SabreTools.Serialization.Readers
{
///
/// Base class for all binary deserializers
///
/// Type of the model to deserialize
///
/// This class allows all inheriting types to only implement
/// and still implicitly implement and
///
public abstract class BaseBinaryReader :
IByteReader,
IFileReader,
IStreamReader
{
///
public bool Debug { get; set; } = false;
#region IByteReader
///
public virtual TModel? Deserialize(byte[]? data, int offset)
{
// If the data is invalid
if (data is null || data.Length == 0)
return default;
// If the offset is out of bounds
if (offset < 0 || offset >= data.Length)
return default;
// Create a memory stream and parse that
var dataStream = new MemoryStream(data, offset, data.Length - offset);
return Deserialize(dataStream);
}
#endregion
#region IFileReader
///
public virtual TModel? Deserialize(string? path)
{
try
{
// If we don't have a file
if (string.IsNullOrEmpty(path) || !File.Exists(path))
return default;
// Open the file for deserialization
using var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return Deserialize(stream);
}
catch
{
// TODO: Handle logging the exception
return default;
}
}
#endregion
#region IStreamReader
///
public abstract TModel? Deserialize(Stream? data);
#endregion
}
}