Files
SabreTools.Serialization/SabreTools.Serialization.Readers/BaseBinaryReader.cs
Matt Nadareski 7689c6dd07 Libraries
This change looks dramatic, but it's just separating out the already-split namespaces into separate top-level folders. In theory, every single one could be built into their own Nuget package. `SabreTools.Serialization` still builds the normal Nuget package that is used by all other projects and includes all namespaces.
2026-03-21 16:26:56 -04:00

73 lines
2.1 KiB
C#

using System.IO;
namespace SabreTools.Serialization.Readers
{
/// <summary>
/// Base class for all binary deserializers
/// </summary>
/// <typeparam name="TModel">Type of the model to deserialize</typeparam>
/// <remarks>
/// This class allows all inheriting types to only implement <see cref="IStreamReader<>"/>
/// and still implicitly implement <see cref="IByteReader<>"/> and <see cref="IFileReader<>"/>
/// </remarks>
public abstract class BaseBinaryReader<TModel> :
IByteReader<TModel>,
IFileReader<TModel>,
IStreamReader<TModel>
{
/// <inheritdoc/>
public bool Debug { get; set; } = false;
#region IByteReader
/// <inheritdoc/>
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
/// <inheritdoc/>
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
/// <inheritdoc/>
public abstract TModel? Deserialize(Stream? data);
#endregion
}
}