0.2.0-dev Download ZIP
61 lines ·2.3 KB Raw
| 1 | using System.Collections.Concurrent; |
| 2 | using EvilEngine.Mounts; |
| 3 | |
| 4 | namespace EvilEngine.Conversion; |
| 5 | |
| 6 | internal sealed class FileHashes(CaseRule caseRule) |
| 7 | { |
| 8 | private readonly ConcurrentDictionary<string, FileStamp> _entries = new(VirtualPath.Comparer(caseRule)); |
| 9 | |
| 10 | private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _layered = |
| 11 | new(VirtualPath.Comparer(caseRule)); |
| 12 | |
| 13 | private readonly ConcurrentDictionary<(VirtualPath, bool), Lazy<FolderListing>> _listings = new(); |
| 14 | |
| 15 | public FileStamp Of(IFileSource files, VirtualPath path, long length, string? layer = null) |
| 16 | { |
| 17 | var key = layer is null ? path.Value : $"{path.Value}\0{layer}"; |
| 18 | if (layer is not null) |
| 19 | _layered.GetOrAdd(path.Value, _ => new ConcurrentDictionary<string, byte>()).TryAdd(key, 0); |
| 20 | while (true) |
| 21 | { |
| 22 | var stamp = _entries.GetOrAdd(key, _ => new FileStamp(files, path, length)); |
| 23 | if (stamp.Length == length) |
| 24 | return stamp; |
| 25 | if (_entries.TryUpdate(key, new FileStamp(files, path, length), stamp)) |
| 26 | stamp.Forget(); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | public FolderListing Listing(IFileSource files, VirtualPath directory, bool recursive) |
| 31 | { |
| 32 | var key = (directory, recursive); |
| 33 | var listing = _listings.GetOrAdd(key, _ => new Lazy<FolderListing>(() => |
| 34 | { |
| 35 | var entries = ConversionContext.Listing(files, directory, recursive); |
| 36 | return new FolderListing(entries, ConversionContext.Hash(entries, files)); |
| 37 | })); |
| 38 | try |
| 39 | { |
| 40 | return listing.Value; |
| 41 | } |
| 42 | catch |
| 43 | { |
| 44 | _listings.TryRemove(new KeyValuePair<(VirtualPath, bool), Lazy<FolderListing>>(key, listing)); |
| 45 | throw; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | public void Forget(IReadOnlyCollection<VirtualPath> paths) |
| 50 | { |
| 51 | foreach (var path in paths) |
| 52 | foreach (var key in _layered.TryRemove(path.Value, out var keys) ? keys.Keys.Append(path.Value) : [path.Value]) |
| 53 | if (_entries.TryRemove(key, out var stamp)) |
| 54 | stamp.Forget(); |
| 55 | foreach (var ((directory, recursive), _) in _listings) |
| 56 | if (paths.Any(path => path.IsUnder(directory, caseRule, recursive))) |
| 57 | _listings.TryRemove((directory, recursive), out _); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | internal sealed record FolderListing(FileEntry[] Entries, string Hash); |