using EvilEngine.Mounts; namespace EvilEngine.Adapters.Unreal; public sealed class IoStoreSource : IndexedSource { private readonly SharedAccess[] _partitions; public IoStoreSource(string location, IoStoreToc toc, Func openPartition) : base(location, CaseRule.Insensitive) { Toc = toc; _partitions = Enumerable.Range(0, toc.Partitions).Select(i => new SharedAccess(() => openPartition(i))) .ToArray(); } public IoStoreToc Toc { get; } public bool TryGetChunk(VirtualPath path, out int chunk) { return Index.TryGet(path, out chunk); } public IRandomAccess OpenChunk(int chunk) { if (Toc.Encrypted) throw new MountException($"'{Location}' encrypts its chunks, and no key is read."); var (_, offset, length, _, _) = Toc.Chunks[chunk]; if (length == 0) return new MemoryAccess(Array.Empty()); var first = offset / Toc.BlockSize; var last = (offset + length - 1) / Toc.BlockSize; if (last >= Toc.Blocks.Count) throw new MountException($"'{Location}' puts chunk {chunk} past its last block."); var blocks = new List((int)(last - first + 1)); for (var i = first; i <= last; i++) { var block = Toc.Blocks[(int)i]; var partition = Toc.PartitionSize is > 0 and < long.MaxValue ? (int)(block.Offset / Toc.PartitionSize) : 0; var at = Toc.PartitionSize is > 0 and < long.MaxValue ? block.Offset % Toc.PartitionSize : block.Offset; if (partition >= _partitions.Length) throw new MountException( $"'{Location}' puts block {i} in partition {partition} of {_partitions.Length}."); var method = block.Method == 0 ? "" : block.Method <= Toc.Methods.Count ? Toc.Methods[block.Method - 1] : $"method {block.Method}"; blocks.Add(new Block(_partitions[partition].Value, at, block.Stored, block.Size, method)); } return new BlockAccess(blocks, offset - first * Toc.BlockSize, length, $"{Location} chunk {chunk}"); } public byte[] ReadChunk(int chunk) { using var access = OpenChunk(chunk); var bytes = new byte[access.Length]; access.ReadExactly(0, bytes); return bytes; } public bool IsStored(int chunk) { var (_, offset, length, _, _) = Toc.Chunks[chunk]; if (length == 0) return true; for (var i = offset / Toc.BlockSize; i <= (offset + length - 1) / Toc.BlockSize; i++) if (Toc.Blocks[(int)i].Method != 0) return false; return true; } protected override void Fill(PathIndex index) { foreach (var (path, chunk) in Toc.Files) index.Add(path, Toc.Chunks[chunk].Length, chunk); } protected override Stream OpenEntry(int chunk) { return new AccessStream(OpenChunk(chunk)); } protected override IRandomAccess OpenEntryAccess(int chunk) { return OpenChunk(chunk); } protected override void Release() { foreach (var partition in _partitions) partition.Dispose(); } }