using System.Collections.Concurrent; using EvilEngine.Mounts; namespace EvilEngine.Conversion; internal sealed class FileHashes(CaseRule caseRule) { private readonly ConcurrentDictionary _entries = new(VirtualPath.Comparer(caseRule)); private readonly ConcurrentDictionary> _layered = new(VirtualPath.Comparer(caseRule)); private readonly ConcurrentDictionary<(VirtualPath, bool), Lazy> _listings = new(); public FileStamp Of(IFileSource files, VirtualPath path, long length, string? layer = null) { var key = layer is null ? path.Value : $"{path.Value}\0{layer}"; if (layer is not null) _layered.GetOrAdd(path.Value, _ => new ConcurrentDictionary()).TryAdd(key, 0); while (true) { var stamp = _entries.GetOrAdd(key, _ => new FileStamp(files, path, length)); if (stamp.Length == length) return stamp; if (_entries.TryUpdate(key, new FileStamp(files, path, length), stamp)) stamp.Forget(); } } public FolderListing Listing(IFileSource files, VirtualPath directory, bool recursive) { var key = (directory, recursive); var listing = _listings.GetOrAdd(key, _ => new Lazy(() => { var entries = ConversionContext.Listing(files, directory, recursive); return new FolderListing(entries, ConversionContext.Hash(entries, files)); })); try { return listing.Value; } catch { _listings.TryRemove(new KeyValuePair<(VirtualPath, bool), Lazy>(key, listing)); throw; } } public void Forget(IReadOnlyCollection paths) { foreach (var path in paths) foreach (var key in _layered.TryRemove(path.Value, out var keys) ? keys.Keys.Append(path.Value) : [path.Value]) if (_entries.TryRemove(key, out var stamp)) stamp.Forget(); foreach (var ((directory, recursive), _) in _listings) if (paths.Any(path => path.IsUnder(directory, caseRule, recursive))) _listings.TryRemove((directory, recursive), out _); } } internal sealed record FolderListing(FileEntry[] Entries, string Hash);