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>
|
2025-09-26 15:10:59 -04:00
|
|
|
/// 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>
|
2025-09-26 15:10:59 -04:00
|
|
|
public abstract class BaseBinaryWriter<TModel> :
|
|
|
|
|
IByteWriter<TModel>,
|
|
|
|
|
IFileWriter<TModel>,
|
|
|
|
|
IStreamWriter<TModel>
|
2024-04-04 02:42:25 -04:00
|
|
|
{
|
2026-01-25 20:07:59 -05:00
|
|
|
/// <inheritdoc/>
|
|
|
|
|
public bool Debug { get; set; } = false;
|
|
|
|
|
|
2025-09-26 15:10:59 -04:00
|
|
|
#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
|
|
|
|
|
|
2025-09-26 15:10:59 -04:00
|
|
|
#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;
|
|
|
|
|
|
2025-09-21 21:03:38 -04:00
|
|
|
using var fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None);
|
2026-03-24 19:17:25 -04:00
|
|
|
stream.BlockCopy(fs);
|
2025-09-21 21:03:38 -04:00
|
|
|
fs.Flush();
|
|
|
|
|
|
2024-04-04 02:42:25 -04:00
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
2025-09-26 15:10:59 -04:00
|
|
|
#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
|
|
|
|
|
}
|
2025-07-24 09:31:28 -04:00
|
|
|
}
|