示例#1
0
 public static void OnSave(WorldSaveEventArgs e)
 {
     Persistence.Serialize(FilePath, OnSerialize);
 }
示例#2
0
 public static void OnLoad()
 {
     Persistence.Deserialize(FilePath, OnDeserialize);
 }
示例#3
0
        public static void LoadData <I, T>(
            string path,
            IIndexInfo <I> indexInfo,
            List <EntityIndex <T> > entities
            ) where T : class, ISerializable
        {
            var indexType = indexInfo.TypeName;

            string dataPath = Path.Combine(path, indexType, $"{indexType}.bin");

            if (!File.Exists(dataPath))
            {
                return;
            }

            using FileStream bin = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read);

            BufferReader br = null;

            foreach (var entry in entities)
            {
                T t = entry.Entity;

                var position = bin.Position;

                // Skip this entry
                if (t == null)
                {
                    bin.Seek(entry.Length, SeekOrigin.Current);
                    continue;
                }

                var buffer = GC.AllocateUninitializedArray <byte>(entry.Length);
                if (br == null)
                {
                    br = new BufferReader(buffer);
                }
                else
                {
                    br.SwapBuffers(buffer, out _);
                }

                bin.Read(buffer.AsSpan());
                string error;

                try
                {
                    t.Deserialize(br);

                    error = br.Position != entry.Length
                        ? $"Serialized object was {entry.Length} bytes, but {br.Position} bytes deserialized"
                        : null;
                }
                catch (Exception e)
                {
                    error = e.ToString();
                }

                if (error == null)
                {
                    t.InitializeSaveBuffer(buffer);
                }
                else
                {
                    Utility.PushColor(ConsoleColor.Red);
                    Persistence.WriteConsoleLine($"***** Bad deserialize of {t.GetType()} *****");
                    Persistence.WriteConsoleLine(error);
                    Utility.PopColor();

                    Persistence.WriteConsoleLine("Delete the object and continue? (y/n)");

                    if (Console.ReadKey(true).Key != ConsoleKey.Y)
                    {
                        throw new Exception("Deserialization failed.");
                    }

                    t.Delete();
                    // Skip this entry
                    bin.Seek(position + entry.Length, SeekOrigin.Begin);
                }
            }
        }