예제 #1
0
        public static void Register(
            string name,
            Action <IGenericWriter> serializer,
            Action <IGenericReader> deserializer,
            int priority = Persistence.DefaultPriority
            )
        {
            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);

                PathUtility.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);

                PathUtility.EnsureDirectory(path);

                string binPath = Path.Combine(path, $"{name}.bin");

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

                try
                {
                    using FileStream fs = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    using var br        = new BinaryFileReader(fs);
                    deserializer(br);
                }
                catch (Exception e)
                {
                    Utility.PushColor(ConsoleColor.Red);
                    Console.WriteLine($"***** Bad deserialize of {name} *****");
                    Console.WriteLine(e.ToString());
                    Utility.PopColor();
                }
            }

            Persistence.Register(name, Serialize, WriterSnapshot, Deserialize, priority);
        }