From cf222263825b797cc0a50908854f9d3d00397991 Mon Sep 17 00:00:00 2001
From: Kamron Batman <3953314+kamronbatman@users.noreply.github.com>
Date: Mon, 18 Jan 2021 13:16:18 -0800
Subject: [PATCH] fix(core): Adds back persistence. (#419)
- [X] Adds persistence back
Notes:
- Optimizations and parallel writing will not be supported in this PR.
---
Projects/Server/Serialization/Persistence.cs | 70 ++++++++++++++++++++
1 file changed, 70 insertions(+)
create mode 100644 Projects/Server/Serialization/Persistence.cs
diff --git a/Projects/Server/Serialization/Persistence.cs b/Projects/Server/Serialization/Persistence.cs
new file mode 100644
index 000000000..426c7b734
--- /dev/null
+++ b/Projects/Server/Serialization/Persistence.cs
@@ -0,0 +1,70 @@
+/*************************************************************************
+ * ModernUO *
+ * Copyright (C) 2019-2021 - ModernUO Development Team *
+ * Email: hi@modernuo.com *
+ * File: Persistence.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 . *
+ *************************************************************************/
+
+using System;
+using System.IO;
+
+namespace Server
+{
+ public static class Persistence
+ {
+ public static void Serialize(string path, Action serializer)
+ {
+ AssemblyHandler.EnsureDirectory(Path.GetDirectoryName(path));
+
+ using var fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None);
+ var writer = new BinaryFileWriter(fs, true);
+
+ try
+ {
+ serializer(writer);
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[Persistence]: Failed to serialize");
+ Console.WriteLine(e);
+ }
+ }
+
+ public static void Deserialize(string path, Action deserializer, bool ensure = true)
+ {
+ AssemblyHandler.EnsureDirectory(Path.GetDirectoryName(path));
+
+ if (!File.Exists(path))
+ {
+ if (ensure)
+ {
+ new FileInfo(path).Create().Close();
+ }
+
+ return;
+ }
+
+ using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ // TODO: Support files larger than 2GB
+ var buffer = GC.AllocateUninitializedArray((int)fs.Length);
+
+ try
+ {
+ deserializer(new BufferReader(buffer));
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("[Persistence]: Failed to deserialize");
+ Console.WriteLine(e);
+ }
+ }
+ }
+}