ModernUO/Projects/Server/Serialization/GenericPersistence.cs
Kamron Batman 432f8d2b70
fix(core): Fixes generic persistence (#544)
- [X] Fixes generic persistence, making the API for writing from a static class much easier.

Example:
```cs
namespace Server
{
    public static class ExampleSystem
    {
        public static void Configure()
        {
            GenericPersistence.Register("ExampleSystem", Serialize, Deserialize);
        }
        
        public static void Serialize(IGenericWriter writer)
        {
            // Do serialization here
            writer.WriteEncodedInt(0); // version
        }

        public static void Deserialize(IGenericReader reader)
        {
            // Do deserialization here
            var version = reader.ReadEncodedInt();
        }
    }
}
```
2021-03-09 23:41:54 -08:00

83 lines
3 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GenericPersistence.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.IO;
namespace Server
{
public static class GenericPersistence
{
public static void Register(
string name,
Action<IGenericWriter> serializer,
Action<IGenericReader> deserializer
)
{
BufferWriter saveBuffer = null;
void Serialize()
{
saveBuffer ??= new BufferWriter(true);
saveBuffer.Seek(0, SeekOrigin.Begin);
serializer(saveBuffer);
}
void WriterSnapshot(string savePath)
{
var path = Path.Combine(savePath, name);
AssemblyHandler.EnsureDirectory(path);
string binPath = Path.Combine(path, $"{name}.bin");
using var bin = new BinaryFileWriter(binPath, true);
saveBuffer!.Resize((int)saveBuffer.Position);
bin.Write(saveBuffer.Buffer);
}
void Deserialize(string savePath)
{
var path = Path.Combine(savePath, name);
AssemblyHandler.EnsureDirectory(path);
string binPath = Path.Combine(path, $"{name}.bin");
if (!File.Exists(binPath))
{
return;
}
try
{
using FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read);
var br = new BufferReader(GC.AllocateUninitializedArray<byte>((int)bin.Length));
deserializer(br);
}
catch (Exception e)
{
Utility.PushColor(ConsoleColor.Red);
Persistence.WriteConsoleLine($"***** Bad deserialize of {name} *****");
Persistence.WriteConsoleLine(e.ToString());
Utility.PopColor();
}
}
Persistence.Register(Serialize, WriterSnapshot, Deserialize);
}
}
}