Files

67 lines
1.8 KiB
C#
Raw Permalink Normal View History

2024-04-04 02:42:25 -04:00
using System.IO;
2026-03-24 19:17:25 -04:00
using SabreTools.IO.Extensions;
2024-04-04 02:42:25 -04:00
2025-09-26 14:59:45 -04:00
namespace SabreTools.Serialization.Writers
2024-04-04 02:42:25 -04:00
{
/// <summary>
/// Base class for all binary serializers
/// </summary>
/// <typeparam name="TModel">Type of the model to serialize</typeparam>
2025-09-16 22:29:52 -04:00
/// <remarks>
/// This class allows all inheriting types to only implement <see cref="IStreamWriter<>"/>
2025-11-14 09:06:59 -05:00
/// and still implicitly implement <see cref="IByteWriter<>"/> and <see cref="IFileWriter<>"/>
2025-09-16 22:29:52 -04:00
/// </remarks>
public abstract class BaseBinaryWriter<TModel> :
IByteWriter<TModel>,
IFileWriter<TModel>,
IStreamWriter<TModel>
2024-04-04 02:42:25 -04:00
{
/// <inheritdoc/>
public bool Debug { get; set; } = false;
#region IByteWriter
2024-04-04 02:42:25 -04:00
/// <inheritdoc/>
public virtual byte[]? SerializeArray(TModel? obj)
{
2025-09-26 10:20:48 -04:00
using var stream = SerializeStream(obj);
2026-01-25 14:30:18 -05:00
if (stream is null)
2024-04-04 02:42:25 -04:00
return null;
byte[] bytes = new byte[stream.Length];
2024-11-13 02:42:14 -05:00
int read = stream.Read(bytes, 0, bytes.Length);
2024-04-04 02:42:25 -04:00
return bytes;
}
#endregion
#region IFileWriter
2024-04-04 02:42:25 -04:00
/// <inheritdoc/>
2025-09-26 10:20:48 -04:00
public virtual bool SerializeFile(TModel? obj, string? path)
2024-04-04 02:42:25 -04:00
{
if (string.IsNullOrEmpty(path))
return false;
2025-09-26 10:20:48 -04:00
using var stream = SerializeStream(obj);
2026-01-25 14:30:18 -05:00
if (stream is null)
2024-04-04 02:42:25 -04:00
return false;
using var fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None);
2026-03-24 19:17:25 -04:00
stream.BlockCopy(fs);
fs.Flush();
2024-04-04 02:42:25 -04:00
return true;
}
#endregion
#region IStreamWriter
2024-04-04 02:42:25 -04:00
/// <inheritdoc/>
2025-09-26 10:20:48 -04:00
public abstract Stream? SerializeStream(TModel? obj);
2024-04-04 02:42:25 -04:00
#endregion
}
}