| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- namespace DevilLink2.Persistence
- {
- public interface ISaveStorage
- {
- object SyncRoot { get; }
- bool Exists(string name);
- string Read(string name);
- void WriteDurable(string name, string text);
- void Move(string source, string destination);
- void Delete(string name);
- bool TryAtomicReplace(string source, string destination);
- }
- public sealed class FileSaveStorage : ISaveStorage
- {
- private static readonly Dictionary<string, object> gates = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
- private readonly string directory;
- private readonly bool preferAtomicReplace;
- private static readonly Encoding utf8 = new UTF8Encoding(false, true);
- public object SyncRoot { get; }
- public string DirectoryPath => directory;
- public FileSaveStorage(string directory, bool preferAtomicReplace = true)
- {
- if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentException("Save directory is required.", nameof(directory));
- string fullPath = Path.GetFullPath(directory);
- this.directory = fullPath == Path.GetPathRoot(fullPath) ? fullPath : fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- this.preferAtomicReplace = preferAtomicReplace;
- lock (gates)
- {
- if (!gates.TryGetValue(this.directory, out var gate)) gates.Add(this.directory, gate = new object());
- SyncRoot = gate;
- }
- }
- private string Resolve(string name)
- {
- if (string.IsNullOrEmpty(name) || Path.GetFileName(name) != name || name == "." || name == "..")
- throw new ArgumentException("Expected a file name within the save directory.", nameof(name));
- return Path.Combine(directory, name);
- }
- public bool Exists(string name) => File.Exists(Resolve(name));
- public string Read(string name) => File.ReadAllText(Resolve(name), utf8);
- public void WriteDurable(string name, string text)
- {
- Directory.CreateDirectory(directory);
- byte[] bytes = utf8.GetBytes(text);
- using (var stream = new FileStream(Resolve(name), FileMode.Create, FileAccess.Write, FileShare.None))
- { stream.Write(bytes, 0, bytes.Length); stream.Flush(true); }
- }
- public void Move(string source, string destination) => File.Move(Resolve(source), Resolve(destination));
- public void Delete(string name) => File.Delete(Resolve(name));
- public bool TryAtomicReplace(string source, string destination)
- {
- if (!preferAtomicReplace) return false;
- try { File.Replace(Resolve(source), Resolve(destination), null); return true; }
- catch (NotSupportedException) { return false; }
- // Permission/sharing/disk errors propagate; do not turn them into destructive retries.
- }
- }
- }
|