using System.Collections.Concurrent; namespace Titano.Data.Processing; /// /// The output paths the renders of this process are writing. Encoders write to a hidden temporary file and rename it over /// the output when they finish, so two renders that picked the same free name (the same preset queued twice) would /// overwrite each other: a render reserves each name it picks until it ends. /// internal sealed class OutputNames : IDisposable { private static readonly ConcurrentDictionary Writing = new(StringComparer.OrdinalIgnoreCase); private readonly List _mine = []; /// A path from , given the test for paths other renders are writing, reserved for this render. public string Reserve(Func, string> pick) { while (true) { var path = pick(p => Writing.ContainsKey(Key(p))); // Another render may have taken the same name since: pick again. if (TryReserve(path)) return path; } } /// Reserves for this render; false when another render is writing it. public bool TryReserve(string path) { var key = Key(path); if (!Writing.TryAdd(key, 0)) return false; lock (_mine) _mine.Add(key); return true; } /// Gives back a path this render reserved, so it can be picked again. public void Release(string path) { var key = Key(path); lock (_mine) { if (_mine.Remove(key)) Writing.TryRemove(key, out _); } } public void Dispose() { lock (_mine) { foreach (var key in _mine) Writing.TryRemove(key, out _); _mine.Clear(); } } private static string Key(string path) => Path.GetFullPath(path); }