|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using CommunityToolkit.Mvvm.ComponentModel; |
| 5 | + |
| 6 | +namespace SourceGit.ViewModels |
| 7 | +{ |
| 8 | + public class BinaryFile : ObservableObject, IDisposable |
| 9 | + { |
| 10 | + public long FileSize |
| 11 | + { |
| 12 | + get => _fileSize; |
| 13 | + private set => SetProperty(ref _fileSize, value); |
| 14 | + } |
| 15 | + |
| 16 | + public static async Task<BinaryFile> LoadAsync(string repo, string path, string revision = "HEAD") |
| 17 | + { |
| 18 | + string saveTo = Path.GetTempFileName(); |
| 19 | + await Commands.SaveRevisionFile.RunAsync(repo, revision, path, saveTo).ConfigureAwait(false); |
| 20 | + return new BinaryFile(saveTo); |
| 21 | + } |
| 22 | + |
| 23 | + public BinaryFile(string file) |
| 24 | + { |
| 25 | + _filePath = file; |
| 26 | + |
| 27 | + if (File.Exists(_filePath)) |
| 28 | + { |
| 29 | + _fileSize = new FileInfo(_filePath).Length; |
| 30 | + _reader = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read, BUFFER_SIZE, FileOptions.RandomAccess); |
| 31 | + _readedStart = 0; |
| 32 | + _readedEnd = Math.Min(_fileSize, BUFFER_SIZE); |
| 33 | + |
| 34 | + if (_fileSize > 0) |
| 35 | + { |
| 36 | + _reader.Seek(_readedStart, SeekOrigin.Begin); |
| 37 | + _reader.ReadExactly(_buffer, 0, (int)_readedEnd); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public void Dispose() |
| 43 | + { |
| 44 | + _reader?.Dispose(); |
| 45 | + _reader = null; |
| 46 | + |
| 47 | + if (File.Exists(_filePath)) |
| 48 | + File.Delete(_filePath); |
| 49 | + } |
| 50 | + |
| 51 | + public ArraySegment<byte> Read(long offset, long length) |
| 52 | + { |
| 53 | + if (_reader == null || _fileSize == 0 || offset >= _fileSize) |
| 54 | + return Array.Empty<byte>(); |
| 55 | + |
| 56 | + if (length > 8192) |
| 57 | + length = 8192; |
| 58 | + |
| 59 | + if (offset + length > _fileSize) |
| 60 | + length = _fileSize - offset; |
| 61 | + |
| 62 | + if (_readedStart <= offset && _readedEnd >= offset + length) |
| 63 | + return new ArraySegment<byte>(_buffer, (int)(offset - _readedStart), (int)length); |
| 64 | + |
| 65 | + _readedStart = (Math.Max(0, offset - 2048) / 1024) * 1024; |
| 66 | + _readedEnd = Math.Min(_readedStart + BUFFER_SIZE, _fileSize); |
| 67 | + |
| 68 | + _reader.Seek(_readedStart, SeekOrigin.Begin); |
| 69 | + _reader.ReadExactly(_buffer, 0, (int)(_readedEnd - _readedStart)); |
| 70 | + |
| 71 | + return new ArraySegment<byte>(_buffer, (int)(offset - _readedStart), (int)length); |
| 72 | + } |
| 73 | + |
| 74 | + private const int BUFFER_SIZE = 16384; |
| 75 | + |
| 76 | + private string _filePath = string.Empty; |
| 77 | + private FileStream _reader = null; |
| 78 | + private long _fileSize = 0; |
| 79 | + private long _readedStart = 0; |
| 80 | + private long _readedEnd = 0; |
| 81 | + private byte[] _buffer = new byte[BUFFER_SIZE]; |
| 82 | + } |
| 83 | +} |
0 commit comments