mirror of
https://github.com/adamhathcock/sharpcompress.git
synced 2026-02-04 13:34:59 +00:00
Compare commits
33 Commits
copilot/fi
...
async
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e08e4e5d9f | ||
|
|
dd710ec308 | ||
|
|
5cfc608010 | ||
|
|
997c11ef25 | ||
|
|
249f11f543 | ||
|
|
eeb6761a9f | ||
|
|
0c35abdebe | ||
|
|
30da0b91ed | ||
|
|
d9c53e1c82 | ||
|
|
14e6d95559 | ||
|
|
8cdc49cb85 | ||
|
|
5c11075d36 | ||
|
|
be34fe2056 | ||
|
|
7e9fb645cb | ||
|
|
15209178ce | ||
|
|
ea688e1f4c | ||
|
|
fe4cc8e6cb | ||
|
|
1f37ced35a | ||
|
|
949e90351f | ||
|
|
db02e8b634 | ||
|
|
d6fe729068 | ||
|
|
ef3d4da286 | ||
|
|
813bd5ae80 | ||
|
|
f40d3342c8 | ||
|
|
9738b812c4 | ||
|
|
c6a011df17 | ||
|
|
7d2dc58766 | ||
|
|
d234f2d509 | ||
|
|
cdba5ec419 | ||
|
|
9cf8a3dbbe | ||
|
|
2b4f02997e | ||
|
|
bcdfd992a3 | ||
|
|
3a820c52bd |
@@ -2,29 +2,25 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Readers;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
{
|
||||
public abstract class AbstractArchive<TEntry, TVolume> : IArchive, IArchiveExtractionListener
|
||||
public abstract class AbstractArchive<TEntry, TVolume> : IArchive
|
||||
where TEntry : IArchiveEntry
|
||||
where TVolume : IVolume
|
||||
{
|
||||
private readonly LazyReadOnlyCollection<TVolume> lazyVolumes;
|
||||
private readonly LazyReadOnlyCollection<TEntry> lazyEntries;
|
||||
|
||||
public event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>>? EntryExtractionBegin;
|
||||
public event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>>? EntryExtractionEnd;
|
||||
|
||||
public event EventHandler<CompressedBytesReadEventArgs>? CompressedBytesRead;
|
||||
public event EventHandler<FilePartExtractionBeginEventArgs>? FilePartExtractionBegin;
|
||||
|
||||
protected ReaderOptions ReaderOptions { get; }
|
||||
protected ReaderOptions ReaderOptions { get; } = new ();
|
||||
|
||||
private bool disposed;
|
||||
|
||||
internal AbstractArchive(ArchiveType type, FileInfo fileInfo, ReaderOptions readerOptions)
|
||||
internal AbstractArchive(ArchiveType type, FileInfo fileInfo, ReaderOptions readerOptions, CancellationToken cancellationToken)
|
||||
{
|
||||
Type = type;
|
||||
if (!fileInfo.Exists)
|
||||
@@ -33,42 +29,30 @@ namespace SharpCompress.Archives
|
||||
}
|
||||
ReaderOptions = readerOptions;
|
||||
readerOptions.LeaveStreamOpen = false;
|
||||
lazyVolumes = new LazyReadOnlyCollection<TVolume>(LoadVolumes(fileInfo));
|
||||
lazyEntries = new LazyReadOnlyCollection<TEntry>(LoadEntries(Volumes));
|
||||
lazyVolumes = new LazyReadOnlyCollection<TVolume>(LoadVolumes(fileInfo, cancellationToken));
|
||||
lazyEntries = new LazyReadOnlyCollection<TEntry>(LoadEntries(Volumes, cancellationToken));
|
||||
}
|
||||
|
||||
|
||||
protected abstract IEnumerable<TVolume> LoadVolumes(FileInfo file);
|
||||
protected abstract IAsyncEnumerable<TVolume> LoadVolumes(FileInfo file, CancellationToken cancellationToken);
|
||||
|
||||
internal AbstractArchive(ArchiveType type, IEnumerable<Stream> streams, ReaderOptions readerOptions)
|
||||
internal AbstractArchive(ArchiveType type, IAsyncEnumerable<Stream> streams, ReaderOptions readerOptions, CancellationToken cancellationToken)
|
||||
{
|
||||
Type = type;
|
||||
ReaderOptions = readerOptions;
|
||||
lazyVolumes = new LazyReadOnlyCollection<TVolume>(LoadVolumes(streams.Select(CheckStreams)));
|
||||
lazyEntries = new LazyReadOnlyCollection<TEntry>(LoadEntries(Volumes));
|
||||
lazyVolumes = new LazyReadOnlyCollection<TVolume>(LoadVolumes(streams.Select(CheckStreams), cancellationToken));
|
||||
lazyEntries = new LazyReadOnlyCollection<TEntry>(LoadEntries(Volumes, cancellationToken));
|
||||
}
|
||||
|
||||
#nullable disable
|
||||
internal AbstractArchive(ArchiveType type)
|
||||
{
|
||||
Type = type;
|
||||
lazyVolumes = new LazyReadOnlyCollection<TVolume>(Enumerable.Empty<TVolume>());
|
||||
lazyEntries = new LazyReadOnlyCollection<TEntry>(Enumerable.Empty<TEntry>());
|
||||
lazyVolumes = new LazyReadOnlyCollection<TVolume>( AsyncEnumerable.Empty<TVolume>());
|
||||
lazyEntries = new LazyReadOnlyCollection<TEntry>(AsyncEnumerable.Empty<TEntry>());
|
||||
}
|
||||
#nullable enable
|
||||
|
||||
public ArchiveType Type { get; }
|
||||
|
||||
void IArchiveExtractionListener.FireEntryExtractionBegin(IArchiveEntry entry)
|
||||
{
|
||||
EntryExtractionBegin?.Invoke(this, new ArchiveExtractionEventArgs<IArchiveEntry>(entry));
|
||||
}
|
||||
|
||||
void IArchiveExtractionListener.FireEntryExtractionEnd(IArchiveEntry entry)
|
||||
{
|
||||
EntryExtractionEnd?.Invoke(this, new ArchiveExtractionEventArgs<IArchiveEntry>(entry));
|
||||
}
|
||||
|
||||
private static Stream CheckStreams(Stream stream)
|
||||
{
|
||||
if (!stream.CanSeek || !stream.CanRead)
|
||||
@@ -81,63 +65,48 @@ namespace SharpCompress.Archives
|
||||
/// <summary>
|
||||
/// Returns an ReadOnlyCollection of all the RarArchiveEntries across the one or many parts of the RarArchive.
|
||||
/// </summary>
|
||||
public virtual ICollection<TEntry> Entries => lazyEntries;
|
||||
public virtual IAsyncEnumerable<TEntry> Entries => lazyEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Returns an ReadOnlyCollection of all the RarArchiveVolumes across the one or many parts of the RarArchive.
|
||||
/// </summary>
|
||||
public ICollection<TVolume> Volumes => lazyVolumes;
|
||||
public IAsyncEnumerable<TVolume> Volumes => lazyVolumes;
|
||||
|
||||
/// <summary>
|
||||
/// The total size of the files compressed in the archive.
|
||||
/// </summary>
|
||||
public virtual long TotalSize => Entries.Aggregate(0L, (total, cf) => total + cf.CompressedSize);
|
||||
public virtual async ValueTask<long> TotalSizeAsync()
|
||||
{
|
||||
await EnsureEntriesLoaded();
|
||||
return await Entries.AggregateAsync(0L, (total, cf) => total + cf.CompressedSize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The total size of the files as uncompressed in the archive.
|
||||
/// </summary>
|
||||
public virtual long TotalUncompressSize => Entries.Aggregate(0L, (total, cf) => total + cf.Size);
|
||||
public virtual async ValueTask<long> TotalUncompressedSizeAsync()
|
||||
{
|
||||
await EnsureEntriesLoaded();
|
||||
return await Entries.AggregateAsync(0L, (total, cf) => total + cf.Size);
|
||||
}
|
||||
|
||||
protected abstract IEnumerable<TVolume> LoadVolumes(IEnumerable<Stream> streams);
|
||||
protected abstract IEnumerable<TEntry> LoadEntries(IEnumerable<TVolume> volumes);
|
||||
protected abstract IAsyncEnumerable<TVolume> LoadVolumes(IAsyncEnumerable<Stream> streams, CancellationToken cancellationToken);
|
||||
protected abstract IAsyncEnumerable<TEntry> LoadEntries(IAsyncEnumerable<TVolume> volumes, CancellationToken cancellationToken);
|
||||
|
||||
IEnumerable<IArchiveEntry> IArchive.Entries => Entries.Cast<IArchiveEntry>();
|
||||
IAsyncEnumerable<IArchiveEntry> IArchive.Entries => Entries.Select(x => (IArchiveEntry)x);
|
||||
|
||||
IEnumerable<IVolume> IArchive.Volumes => lazyVolumes.Cast<IVolume>();
|
||||
IAsyncEnumerable<IVolume> IArchive.Volumes => lazyVolumes.Select(x => (IVolume)x);
|
||||
|
||||
public virtual void Dispose()
|
||||
public virtual async ValueTask DisposeAsync()
|
||||
{
|
||||
if (!disposed)
|
||||
{
|
||||
lazyVolumes.ForEach(v => v.Dispose());
|
||||
lazyEntries.GetLoaded().Cast<Entry>().ForEach(x => x.Close());
|
||||
await lazyVolumes.ForEachAsync(async v => await v.DisposeAsync());
|
||||
await lazyEntries.GetLoaded().Cast<Entry>().ForEachAsync(async x => await x.CloseAsync());
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
void IArchiveExtractionListener.EnsureEntriesLoaded()
|
||||
{
|
||||
lazyEntries.EnsureFullyLoaded();
|
||||
lazyVolumes.EnsureFullyLoaded();
|
||||
}
|
||||
|
||||
void IExtractionListener.FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes)
|
||||
{
|
||||
CompressedBytesRead?.Invoke(this, new CompressedBytesReadEventArgs(
|
||||
currentFilePartCompressedBytesRead: currentPartCompressedBytes,
|
||||
compressedBytesRead: compressedReadBytes
|
||||
));
|
||||
}
|
||||
|
||||
void IExtractionListener.FireFilePartExtractionBegin(string name, long size, long compressedSize)
|
||||
{
|
||||
FilePartExtractionBegin?.Invoke(this, new FilePartExtractionBeginEventArgs(
|
||||
compressedSize: compressedSize,
|
||||
size: size,
|
||||
name: name
|
||||
));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this method to extract all entries in an archive in order.
|
||||
/// This is primarily for SOLID Rar Archives or 7Zip Archives as they need to be
|
||||
@@ -149,29 +118,32 @@ namespace SharpCompress.Archives
|
||||
/// occur if this is used at the same time as other extraction methods on this instance.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public IReader ExtractAllEntries()
|
||||
public async ValueTask<IReader> ExtractAllEntries()
|
||||
{
|
||||
((IArchiveExtractionListener)this).EnsureEntriesLoaded();
|
||||
return CreateReaderForSolidExtraction();
|
||||
await EnsureEntriesLoaded();
|
||||
return await CreateReaderForSolidExtraction();
|
||||
}
|
||||
|
||||
public async ValueTask EnsureEntriesLoaded()
|
||||
{
|
||||
await lazyEntries.EnsureFullyLoaded();
|
||||
await lazyVolumes.EnsureFullyLoaded();
|
||||
}
|
||||
|
||||
protected abstract IReader CreateReaderForSolidExtraction();
|
||||
protected abstract ValueTask<IReader> CreateReaderForSolidExtraction();
|
||||
|
||||
/// <summary>
|
||||
/// Archive is SOLID (this means the Archive saved bytes by reusing information which helps for archives containing many small files).
|
||||
/// </summary>
|
||||
public virtual bool IsSolid => false;
|
||||
public virtual ValueTask<bool> IsSolidAsync() => new(false);
|
||||
|
||||
/// <summary>
|
||||
/// The archive can find all the parts of the archive needed to fully extract the archive. This forces the parsing of the entire archive.
|
||||
/// </summary>
|
||||
public bool IsComplete
|
||||
public async ValueTask<bool> IsCompleteAsync()
|
||||
{
|
||||
get
|
||||
{
|
||||
((IArchiveExtractionListener)this).EnsureEntriesLoaded();
|
||||
return Entries.All(x => x.IsComplete);
|
||||
}
|
||||
await EnsureEntriesLoaded();
|
||||
return await Entries.AllAsync(x => x.IsComplete);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Readers;
|
||||
using SharpCompress.Writers;
|
||||
@@ -12,7 +14,7 @@ namespace SharpCompress.Archives
|
||||
where TEntry : IArchiveEntry
|
||||
where TVolume : IVolume
|
||||
{
|
||||
private class RebuildPauseDisposable : IDisposable
|
||||
private class RebuildPauseDisposable : IAsyncDisposable
|
||||
{
|
||||
private readonly AbstractWritableArchive<TEntry, TVolume> archive;
|
||||
|
||||
@@ -22,16 +24,16 @@ namespace SharpCompress.Archives
|
||||
archive.pauseRebuilding = true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
archive.pauseRebuilding = false;
|
||||
archive.RebuildModifiedCollection();
|
||||
await archive.RebuildModifiedCollection();
|
||||
}
|
||||
}
|
||||
private readonly List<TEntry> newEntries = new List<TEntry>();
|
||||
private readonly List<TEntry> removedEntries = new List<TEntry>();
|
||||
private readonly List<TEntry> newEntries = new();
|
||||
private readonly List<TEntry> removedEntries = new();
|
||||
|
||||
private readonly List<TEntry> modifiedEntries = new List<TEntry>();
|
||||
private readonly List<TEntry> modifiedEntries = new();
|
||||
private bool hasModifications;
|
||||
private bool pauseRebuilding;
|
||||
|
||||
@@ -40,34 +42,36 @@ namespace SharpCompress.Archives
|
||||
{
|
||||
}
|
||||
|
||||
internal AbstractWritableArchive(ArchiveType type, Stream stream, ReaderOptions readerFactoryOptions)
|
||||
: base(type, stream.AsEnumerable(), readerFactoryOptions)
|
||||
internal AbstractWritableArchive(ArchiveType type, Stream stream, ReaderOptions readerFactoryOptions,
|
||||
CancellationToken cancellationToken)
|
||||
: base(type, stream.AsAsyncEnumerable(), readerFactoryOptions, cancellationToken)
|
||||
{
|
||||
}
|
||||
|
||||
internal AbstractWritableArchive(ArchiveType type, FileInfo fileInfo, ReaderOptions readerFactoryOptions)
|
||||
: base(type, fileInfo, readerFactoryOptions)
|
||||
internal AbstractWritableArchive(ArchiveType type, FileInfo fileInfo, ReaderOptions readerFactoryOptions,
|
||||
CancellationToken cancellationToken)
|
||||
: base(type, fileInfo, readerFactoryOptions, cancellationToken)
|
||||
{
|
||||
}
|
||||
|
||||
public override ICollection<TEntry> Entries
|
||||
public override IAsyncEnumerable<TEntry> Entries
|
||||
{
|
||||
get
|
||||
{
|
||||
if (hasModifications)
|
||||
{
|
||||
return modifiedEntries;
|
||||
return modifiedEntries.ToAsyncEnumerable();
|
||||
}
|
||||
return base.Entries;
|
||||
}
|
||||
}
|
||||
|
||||
public IDisposable PauseEntryRebuilding()
|
||||
public IAsyncDisposable PauseEntryRebuilding()
|
||||
{
|
||||
return new RebuildPauseDisposable(this);
|
||||
}
|
||||
|
||||
private void RebuildModifiedCollection()
|
||||
private async ValueTask RebuildModifiedCollection()
|
||||
{
|
||||
if (pauseRebuilding)
|
||||
{
|
||||
@@ -76,56 +80,57 @@ namespace SharpCompress.Archives
|
||||
hasModifications = true;
|
||||
newEntries.RemoveAll(v => removedEntries.Contains(v));
|
||||
modifiedEntries.Clear();
|
||||
modifiedEntries.AddRange(OldEntries.Concat(newEntries));
|
||||
modifiedEntries.AddRange(await OldEntries.Concat(newEntries.ToAsyncEnumerable()).ToListAsync());
|
||||
}
|
||||
|
||||
private IEnumerable<TEntry> OldEntries { get { return base.Entries.Where(x => !removedEntries.Contains(x)); } }
|
||||
private IAsyncEnumerable<TEntry> OldEntries { get { return base.Entries.Where(x => !removedEntries.Contains(x)); } }
|
||||
|
||||
public void RemoveEntry(TEntry entry)
|
||||
public async ValueTask RemoveEntryAsync(TEntry entry)
|
||||
{
|
||||
if (!removedEntries.Contains(entry))
|
||||
{
|
||||
removedEntries.Add(entry);
|
||||
RebuildModifiedCollection();
|
||||
await RebuildModifiedCollection();
|
||||
}
|
||||
}
|
||||
|
||||
void IWritableArchive.RemoveEntry(IArchiveEntry entry)
|
||||
ValueTask IWritableArchive.RemoveEntryAsync(IArchiveEntry entry, CancellationToken cancellationToken)
|
||||
{
|
||||
RemoveEntry((TEntry)entry);
|
||||
return RemoveEntryAsync((TEntry)entry);
|
||||
}
|
||||
|
||||
public TEntry AddEntry(string key, Stream source,
|
||||
long size = 0, DateTime? modified = null)
|
||||
public ValueTask<TEntry> AddEntryAsync(string key, Stream source,
|
||||
long size = 0, DateTime? modified = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return AddEntry(key, source, false, size, modified);
|
||||
return AddEntryAsync(key, source, false, size, modified, cancellationToken);
|
||||
}
|
||||
|
||||
IArchiveEntry IWritableArchive.AddEntry(string key, Stream source, bool closeStream, long size, DateTime? modified)
|
||||
async ValueTask<IArchiveEntry> IWritableArchive.AddEntryAsync(string key, Stream source, bool closeStream, long size, DateTime? modified, CancellationToken cancellationToken)
|
||||
{
|
||||
return AddEntry(key, source, closeStream, size, modified);
|
||||
return await AddEntryAsync(key, source, closeStream, size, modified, cancellationToken);
|
||||
}
|
||||
|
||||
public TEntry AddEntry(string key, Stream source, bool closeStream,
|
||||
long size = 0, DateTime? modified = null)
|
||||
public async ValueTask<TEntry> AddEntryAsync(string key, Stream source, bool closeStream,
|
||||
long size = 0, DateTime? modified = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (key.Length > 0 && key[0] is '/' or '\\')
|
||||
{
|
||||
key = key.Substring(1);
|
||||
}
|
||||
if (DoesKeyMatchExisting(key))
|
||||
if (await DoesKeyMatchExisting(key))
|
||||
{
|
||||
throw new ArchiveException("Cannot add entry with duplicate key: " + key);
|
||||
}
|
||||
var entry = CreateEntry(key, source, size, modified, closeStream);
|
||||
var entry = await CreateEntry(key, source, size, modified, closeStream, cancellationToken);
|
||||
newEntries.Add(entry);
|
||||
RebuildModifiedCollection();
|
||||
await RebuildModifiedCollection();
|
||||
return entry;
|
||||
}
|
||||
|
||||
private bool DoesKeyMatchExisting(string key)
|
||||
private async ValueTask<bool> DoesKeyMatchExisting(string key)
|
||||
{
|
||||
foreach (var path in Entries.Select(x => x.Key))
|
||||
await foreach (var path in Entries.Select(x => x.Key))
|
||||
{
|
||||
var p = path.Replace('/', '\\');
|
||||
if (p.Length > 0 && p[0] == '\\')
|
||||
@@ -137,34 +142,35 @@ namespace SharpCompress.Archives
|
||||
return false;
|
||||
}
|
||||
|
||||
public void SaveTo(Stream stream, WriterOptions options)
|
||||
public async ValueTask SaveToAsync(Stream stream, WriterOptions options, CancellationToken cancellationToken = default)
|
||||
{
|
||||
//reset streams of new entries
|
||||
newEntries.Cast<IWritableArchiveEntry>().ForEach(x => x.Stream.Seek(0, SeekOrigin.Begin));
|
||||
SaveTo(stream, options, OldEntries, newEntries);
|
||||
await SaveToAsync(stream, options, OldEntries, newEntries.ToAsyncEnumerable(), cancellationToken);
|
||||
}
|
||||
|
||||
protected TEntry CreateEntry(string key, Stream source, long size, DateTime? modified,
|
||||
bool closeStream)
|
||||
protected ValueTask<TEntry> CreateEntry(string key, Stream source, long size, DateTime? modified,
|
||||
bool closeStream, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!source.CanRead || !source.CanSeek)
|
||||
{
|
||||
throw new ArgumentException("Streams must be readable and seekable to use the Writing Archive API");
|
||||
}
|
||||
return CreateEntryInternal(key, source, size, modified, closeStream);
|
||||
return CreateEntryInternal(key, source, size, modified, closeStream, cancellationToken);
|
||||
}
|
||||
|
||||
protected abstract TEntry CreateEntryInternal(string key, Stream source, long size, DateTime? modified,
|
||||
bool closeStream);
|
||||
protected abstract ValueTask<TEntry> CreateEntryInternal(string key, Stream source, long size, DateTime? modified,
|
||||
bool closeStream, CancellationToken cancellationToken);
|
||||
|
||||
protected abstract void SaveTo(Stream stream, WriterOptions options, IEnumerable<TEntry> oldEntries, IEnumerable<TEntry> newEntries);
|
||||
protected abstract ValueTask SaveToAsync(Stream stream, WriterOptions options, IAsyncEnumerable<TEntry> oldEntries, IAsyncEnumerable<TEntry> newEntries,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
public override void Dispose()
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
base.Dispose();
|
||||
newEntries.Cast<Entry>().ForEach(x => x.Close());
|
||||
removedEntries.Cast<Entry>().ForEach(x => x.Close());
|
||||
modifiedEntries.Cast<Entry>().ForEach(x => x.Close());
|
||||
await base.DisposeAsync();
|
||||
await newEntries.Cast<Entry>().ForEachAsync(async x => await x.CloseAsync());
|
||||
await removedEntries.Cast<Entry>().ForEachAsync(async x => await x.CloseAsync());
|
||||
await modifiedEntries.Cast<Entry>().ForEachAsync(async x => await x.CloseAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Archives.GZip;
|
||||
using SharpCompress.Archives.Rar;
|
||||
using SharpCompress.Archives.SevenZip;
|
||||
//using SharpCompress.Archives.Rar;
|
||||
//using SharpCompress.Archives.SevenZip;
|
||||
using SharpCompress.Archives.Tar;
|
||||
using SharpCompress.Archives.Zip;
|
||||
using SharpCompress.Common;
|
||||
@@ -18,7 +20,7 @@ namespace SharpCompress.Archives
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
/// <returns></returns>
|
||||
public static IArchive Open(Stream stream, ReaderOptions? readerOptions = null)
|
||||
public static async ValueTask<IArchive> OpenAsync(Stream stream, ReaderOptions? readerOptions = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
stream.CheckNotNull(nameof(stream));
|
||||
if (!stream.CanRead || !stream.CanSeek)
|
||||
@@ -26,35 +28,35 @@ namespace SharpCompress.Archives
|
||||
throw new ArgumentException("Stream should be readable and seekable");
|
||||
}
|
||||
readerOptions ??= new ReaderOptions();
|
||||
if (ZipArchive.IsZipFile(stream, null))
|
||||
if (await ZipArchive.IsZipFileAsync(stream, null, cancellationToken))
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return ZipArchive.Open(stream, readerOptions);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (SevenZipArchive.IsSevenZipFile(stream))
|
||||
/*if (SevenZipArchive.IsSevenZipFile(stream))
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return SevenZipArchive.Open(stream, readerOptions);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (GZipArchive.IsGZipFile(stream))
|
||||
stream.Seek(0, SeekOrigin.Begin); */
|
||||
if (await GZipArchive.IsGZipFileAsync(stream, cancellationToken))
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return GZipArchive.Open(stream, readerOptions);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (RarArchive.IsRarFile(stream, readerOptions))
|
||||
/* if (RarArchive.IsRarFile(stream, readerOptions))
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return RarArchive.Open(stream, readerOptions);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (TarArchive.IsTarFile(stream))
|
||||
stream.Seek(0, SeekOrigin.Begin); */
|
||||
if (await TarArchive.IsTarFileAsync(stream, cancellationToken))
|
||||
{
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return TarArchive.Open(stream, readerOptions);
|
||||
}
|
||||
}
|
||||
throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip, LZip");
|
||||
}
|
||||
|
||||
@@ -63,7 +65,7 @@ namespace SharpCompress.Archives
|
||||
return type switch
|
||||
{
|
||||
ArchiveType.Zip => ZipArchive.Create(),
|
||||
ArchiveType.Tar => TarArchive.Create(),
|
||||
//ArchiveType.Tar => TarArchive.Create(),
|
||||
ArchiveType.GZip => GZipArchive.Create(),
|
||||
_ => throw new NotSupportedException("Cannot create Archives of type: " + type)
|
||||
};
|
||||
@@ -74,10 +76,10 @@ namespace SharpCompress.Archives
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <param name="options"></param>
|
||||
public static IArchive Open(string filePath, ReaderOptions? options = null)
|
||||
public static ValueTask<IArchive> OpenAsync(string filePath, ReaderOptions? options = null)
|
||||
{
|
||||
filePath.CheckNotNullOrEmpty(nameof(filePath));
|
||||
return Open(new FileInfo(filePath), options);
|
||||
return OpenAsync(new FileInfo(filePath), options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -85,28 +87,28 @@ namespace SharpCompress.Archives
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="options"></param>
|
||||
public static IArchive Open(FileInfo fileInfo, ReaderOptions? options = null)
|
||||
public static async ValueTask<IArchive> OpenAsync(FileInfo fileInfo, ReaderOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
fileInfo.CheckNotNull(nameof(fileInfo));
|
||||
options ??= new ReaderOptions { LeaveStreamOpen = false };
|
||||
|
||||
using var stream = fileInfo.OpenRead();
|
||||
if (ZipArchive.IsZipFile(stream, null))
|
||||
await using var stream = fileInfo.OpenRead();
|
||||
if (await ZipArchive.IsZipFileAsync(stream, null, cancellationToken))
|
||||
{
|
||||
return ZipArchive.Open(fileInfo, options);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (SevenZipArchive.IsSevenZipFile(stream))
|
||||
/*if (SevenZipArchive.IsSevenZipFile(stream))
|
||||
{
|
||||
return SevenZipArchive.Open(fileInfo, options);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (GZipArchive.IsGZipFile(stream))
|
||||
stream.Seek(0, SeekOrigin.Begin); */
|
||||
if (await GZipArchive.IsGZipFileAsync(stream, cancellationToken))
|
||||
{
|
||||
return GZipArchive.Open(fileInfo, options);
|
||||
}
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
if (RarArchive.IsRarFile(stream, options))
|
||||
/*if (RarArchive.IsRarFile(stream, options))
|
||||
{
|
||||
return RarArchive.Open(fileInfo, options);
|
||||
}
|
||||
@@ -114,20 +116,22 @@ namespace SharpCompress.Archives
|
||||
if (TarArchive.IsTarFile(stream))
|
||||
{
|
||||
return TarArchive.Open(fileInfo, options);
|
||||
}
|
||||
} */
|
||||
throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract to specific directory, retaining filename
|
||||
/// </summary>
|
||||
public static void WriteToDirectory(string sourceArchive, string destinationDirectory,
|
||||
ExtractionOptions? options = null)
|
||||
public static async ValueTask WriteToDirectory(string sourceArchive,
|
||||
string destinationDirectory,
|
||||
ExtractionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using IArchive archive = Open(sourceArchive);
|
||||
foreach (IArchiveEntry entry in archive.Entries)
|
||||
await using IArchive archive = await OpenAsync(sourceArchive);
|
||||
await foreach (IArchiveEntry entry in archive.Entries.WithCancellation(cancellationToken))
|
||||
{
|
||||
entry.WriteToDirectory(destinationDirectory, options);
|
||||
await entry.WriteEntryToDirectoryAsync(destinationDirectory, options, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.GZip;
|
||||
using SharpCompress.Readers;
|
||||
@@ -29,10 +33,11 @@ namespace SharpCompress.Archives.GZip
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
public static GZipArchive Open(FileInfo fileInfo, ReaderOptions? readerOptions = null)
|
||||
public static GZipArchive Open(FileInfo fileInfo, ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
fileInfo.CheckNotNull(nameof(fileInfo));
|
||||
return new GZipArchive(fileInfo, readerOptions ?? new ReaderOptions());
|
||||
return new GZipArchive(fileInfo, readerOptions ?? new ReaderOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -40,10 +45,11 @@ namespace SharpCompress.Archives.GZip
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
public static GZipArchive Open(Stream stream, ReaderOptions? readerOptions = null)
|
||||
public static GZipArchive Open(Stream stream, ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
stream.CheckNotNull(nameof(stream));
|
||||
return new GZipArchive(stream, readerOptions ?? new ReaderOptions());
|
||||
return new GZipArchive(stream, readerOptions ?? new ReaderOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
public static GZipArchive Create()
|
||||
@@ -56,57 +62,58 @@ namespace SharpCompress.Archives.GZip
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="options"></param>
|
||||
internal GZipArchive(FileInfo fileInfo, ReaderOptions options)
|
||||
: base(ArchiveType.GZip, fileInfo, options)
|
||||
internal GZipArchive(FileInfo fileInfo, ReaderOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
: base(ArchiveType.GZip, fileInfo, options, cancellationToken)
|
||||
{
|
||||
}
|
||||
|
||||
protected override IEnumerable<GZipVolume> LoadVolumes(FileInfo file)
|
||||
protected override IAsyncEnumerable<GZipVolume> LoadVolumes(FileInfo file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return new GZipVolume(file, ReaderOptions).AsEnumerable();
|
||||
return new GZipVolume(file, ReaderOptions).AsAsyncEnumerable();
|
||||
}
|
||||
|
||||
public static bool IsGZipFile(string filePath)
|
||||
public static ValueTask<bool> IsGZipFileAsync(string filePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return IsGZipFile(new FileInfo(filePath));
|
||||
return IsGZipFileAsync(new FileInfo(filePath), cancellationToken);
|
||||
}
|
||||
|
||||
public static bool IsGZipFile(FileInfo fileInfo)
|
||||
public static async ValueTask<bool> IsGZipFileAsync(FileInfo fileInfo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!fileInfo.Exists)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using Stream stream = fileInfo.OpenRead();
|
||||
return IsGZipFile(stream);
|
||||
await using Stream stream = fileInfo.OpenRead();
|
||||
return await IsGZipFileAsync(stream, cancellationToken);
|
||||
}
|
||||
|
||||
public void SaveTo(string filePath)
|
||||
public Task SaveToAsync(string filePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SaveTo(new FileInfo(filePath));
|
||||
return SaveToAsync(new FileInfo(filePath), cancellationToken);
|
||||
}
|
||||
|
||||
public void SaveTo(FileInfo fileInfo)
|
||||
public async Task SaveToAsync(FileInfo fileInfo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
SaveTo(stream, new WriterOptions(CompressionType.GZip));
|
||||
}
|
||||
await using var stream = fileInfo.Open(FileMode.Create, FileAccess.Write);
|
||||
await SaveToAsync(stream, new WriterOptions(CompressionType.GZip), cancellationToken);
|
||||
}
|
||||
|
||||
public static bool IsGZipFile(Stream stream)
|
||||
public static async ValueTask<bool> IsGZipFileAsync(Stream stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// read the header on the first read
|
||||
Span<byte> header = stackalloc byte[10];
|
||||
using var header = MemoryPool<byte>.Shared.Rent(10);
|
||||
var slice = header.Memory.Slice(0, 10);
|
||||
|
||||
// workitem 8501: handle edge case (decompress empty stream)
|
||||
if (!stream.ReadFully(header))
|
||||
if (await stream.ReadAsync(slice, cancellationToken) != 10)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
|
||||
if (slice.Span[0] != 0x1F || slice.Span[1] != 0x8B || slice.Span[2] != 8)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -119,8 +126,9 @@ namespace SharpCompress.Archives.GZip
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="options"></param>
|
||||
internal GZipArchive(Stream stream, ReaderOptions options)
|
||||
: base(ArchiveType.GZip, stream, options)
|
||||
internal GZipArchive(Stream stream, ReaderOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
: base(ArchiveType.GZip, stream, options, cancellationToken)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -129,51 +137,54 @@ namespace SharpCompress.Archives.GZip
|
||||
{
|
||||
}
|
||||
|
||||
protected override GZipArchiveEntry CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified,
|
||||
bool closeStream)
|
||||
protected override async ValueTask<GZipArchiveEntry> CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified,
|
||||
bool closeStream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Entries.Any())
|
||||
if (await Entries.AnyAsync(cancellationToken: cancellationToken))
|
||||
{
|
||||
throw new InvalidOperationException("Only one entry is allowed in a GZip Archive");
|
||||
}
|
||||
return new GZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream);
|
||||
}
|
||||
|
||||
protected override void SaveTo(Stream stream, WriterOptions options,
|
||||
IEnumerable<GZipArchiveEntry> oldEntries,
|
||||
IEnumerable<GZipArchiveEntry> newEntries)
|
||||
protected override async ValueTask SaveToAsync(Stream stream, WriterOptions options,
|
||||
IAsyncEnumerable<GZipArchiveEntry> oldEntries,
|
||||
IAsyncEnumerable<GZipArchiveEntry> newEntries,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Entries.Count > 1)
|
||||
if (await Entries.CountAsync(cancellationToken: cancellationToken) > 1)
|
||||
{
|
||||
throw new InvalidOperationException("Only one entry is allowed in a GZip Archive");
|
||||
}
|
||||
using (var writer = new GZipWriter(stream, new GZipWriterOptions(options)))
|
||||
|
||||
await using var writer = new GZipWriter(stream, new GZipWriterOptions(options));
|
||||
await foreach (var entry in oldEntries.Concat(newEntries)
|
||||
.Where(x => !x.IsDirectory)
|
||||
.WithCancellation(cancellationToken))
|
||||
{
|
||||
foreach (var entry in oldEntries.Concat(newEntries)
|
||||
.Where(x => !x.IsDirectory))
|
||||
{
|
||||
using (var entryStream = entry.OpenEntryStream())
|
||||
{
|
||||
writer.Write(entry.Key, entryStream, entry.LastModifiedTime);
|
||||
}
|
||||
}
|
||||
await using var entryStream = await entry.OpenEntryStreamAsync(cancellationToken);
|
||||
await writer.WriteAsync(entry.Key, entryStream, entry.LastModifiedTime, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
protected override IEnumerable<GZipVolume> LoadVolumes(IEnumerable<Stream> streams)
|
||||
protected override async IAsyncEnumerable<GZipVolume> LoadVolumes(IAsyncEnumerable<Stream> streams,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
return new GZipVolume(streams.First(), ReaderOptions).AsEnumerable();
|
||||
yield return new GZipVolume(await streams.FirstAsync(cancellationToken: cancellationToken), ReaderOptions);
|
||||
}
|
||||
|
||||
protected override IEnumerable<GZipArchiveEntry> LoadEntries(IEnumerable<GZipVolume> volumes)
|
||||
protected override async IAsyncEnumerable<GZipArchiveEntry> LoadEntries(IAsyncEnumerable<GZipVolume> volumes,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
Stream stream = volumes.Single().Stream;
|
||||
yield return new GZipArchiveEntry(this, new GZipFilePart(stream, ReaderOptions.ArchiveEncoding));
|
||||
Stream stream = (await volumes.SingleAsync(cancellationToken: cancellationToken)).Stream;
|
||||
var part = new GZipFilePart(ReaderOptions.ArchiveEncoding);
|
||||
await part.Initialize(stream, cancellationToken);
|
||||
yield return new GZipArchiveEntry(this, part);
|
||||
}
|
||||
|
||||
protected override IReader CreateReaderForSolidExtraction()
|
||||
protected override async ValueTask<IReader> CreateReaderForSolidExtraction()
|
||||
{
|
||||
var stream = Volumes.Single().Stream;
|
||||
var stream = (await Volumes.SingleAsync()).Stream;
|
||||
stream.Position = 0;
|
||||
return GZipReader.Open(stream);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.GZip;
|
||||
|
||||
namespace SharpCompress.Archives.GZip
|
||||
@@ -12,7 +14,7 @@ namespace SharpCompress.Archives.GZip
|
||||
Archive = archive;
|
||||
}
|
||||
|
||||
public virtual Stream OpenEntryStream()
|
||||
public virtual async ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//this is to reset the stream to be read multiple times
|
||||
var part = (GZipFilePart)Parts.Single();
|
||||
@@ -20,7 +22,7 @@ namespace SharpCompress.Archives.GZip
|
||||
{
|
||||
part.GetRawStream().Position = part.EntryStartPosition;
|
||||
}
|
||||
return Parts.Single().GetCompressedStream();
|
||||
return await Parts.Single().GetCompressedStreamAsync(cancellationToken);
|
||||
}
|
||||
|
||||
#region IArchiveEntry Members
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -50,18 +52,18 @@ namespace SharpCompress.Archives.GZip
|
||||
|
||||
Stream IWritableArchiveEntry.Stream => stream;
|
||||
|
||||
public override Stream OpenEntryStream()
|
||||
public override ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//ensure new stream is at the start, this could be reset
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return new NonDisposingStream(stream);
|
||||
return new(new NonDisposingStream(stream));
|
||||
}
|
||||
|
||||
internal override void Close()
|
||||
internal override async ValueTask CloseAsync()
|
||||
{
|
||||
if (closeStream)
|
||||
{
|
||||
stream.Dispose();
|
||||
await stream.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Readers;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
{
|
||||
public interface IArchive : IDisposable
|
||||
public interface IArchive : IAsyncDisposable
|
||||
{
|
||||
event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>> EntryExtractionBegin;
|
||||
event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>> EntryExtractionEnd;
|
||||
|
||||
event EventHandler<CompressedBytesReadEventArgs> CompressedBytesRead;
|
||||
event EventHandler<FilePartExtractionBeginEventArgs> FilePartExtractionBegin;
|
||||
|
||||
IEnumerable<IArchiveEntry> Entries { get; }
|
||||
IEnumerable<IVolume> Volumes { get; }
|
||||
IAsyncEnumerable<IArchiveEntry> Entries { get; }
|
||||
IAsyncEnumerable<IVolume> Volumes { get; }
|
||||
|
||||
ArchiveType Type { get; }
|
||||
|
||||
ValueTask EnsureEntriesLoaded();
|
||||
/// <summary>
|
||||
/// Use this method to extract all entries in an archive in order.
|
||||
/// This is primarily for SOLID Rar Archives or 7Zip Archives as they need to be
|
||||
/// extracted sequentially for the best performance.
|
||||
/// </summary>
|
||||
IReader ExtractAllEntries();
|
||||
ValueTask<IReader> ExtractAllEntries();
|
||||
|
||||
/// <summary>
|
||||
/// Archive is SOLID (this means the Archive saved bytes by reusing information which helps for archives containing many small files).
|
||||
/// Rar Archives can be SOLID while all 7Zip archives are considered SOLID.
|
||||
/// </summary>
|
||||
bool IsSolid { get; }
|
||||
ValueTask<bool> IsSolidAsync();
|
||||
|
||||
/// <summary>
|
||||
/// This checks to see if all the known entries have IsComplete = true
|
||||
/// </summary>
|
||||
bool IsComplete { get; }
|
||||
ValueTask<bool> IsCompleteAsync();
|
||||
|
||||
/// <summary>
|
||||
/// The total size of the files compressed in the archive.
|
||||
/// </summary>
|
||||
long TotalSize { get; }
|
||||
ValueTask<long> TotalSizeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// The total size of the files as uncompressed in the archive.
|
||||
/// </summary>
|
||||
long TotalUncompressSize { get; }
|
||||
ValueTask<long> TotalUncompressedSizeAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
@@ -9,7 +11,7 @@ namespace SharpCompress.Archives
|
||||
/// Opens the current entry as a stream that will decompress as it is read.
|
||||
/// Read the entire stream or use SkipEntry on EntryStream.
|
||||
/// </summary>
|
||||
Stream OpenEntryStream();
|
||||
ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// The archive can find all the parts of the archive needed to extract this entry.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -6,58 +8,53 @@ namespace SharpCompress.Archives
|
||||
{
|
||||
public static class IArchiveEntryExtensions
|
||||
{
|
||||
public static void WriteTo(this IArchiveEntry archiveEntry, Stream streamToWriteTo)
|
||||
public static async ValueTask WriteToAsync(this IArchiveEntry archiveEntry, Stream streamToWriteTo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (archiveEntry.IsDirectory)
|
||||
{
|
||||
throw new ExtractionException("Entry is a file directory and cannot be extracted.");
|
||||
}
|
||||
|
||||
var streamListener = (IArchiveExtractionListener)archiveEntry.Archive;
|
||||
streamListener.EnsureEntriesLoaded();
|
||||
streamListener.FireEntryExtractionBegin(archiveEntry);
|
||||
streamListener.FireFilePartExtractionBegin(archiveEntry.Key, archiveEntry.Size, archiveEntry.CompressedSize);
|
||||
var entryStream = archiveEntry.OpenEntryStream();
|
||||
var archive = archiveEntry.Archive;
|
||||
await archive.EnsureEntriesLoaded();
|
||||
var entryStream = await archiveEntry.OpenEntryStreamAsync(cancellationToken);
|
||||
if (entryStream is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
using (entryStream)
|
||||
await using (entryStream)
|
||||
{
|
||||
using (Stream s = new ListeningStream(streamListener, entryStream))
|
||||
{
|
||||
s.TransferTo(streamToWriteTo);
|
||||
}
|
||||
await entryStream.TransferToAsync(streamToWriteTo, cancellationToken);
|
||||
}
|
||||
streamListener.FireEntryExtractionEnd(archiveEntry);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract to specific directory, retaining filename
|
||||
/// </summary>
|
||||
public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
|
||||
ExtractionOptions? options = null)
|
||||
public static ValueTask WriteEntryToDirectoryAsync(this IArchiveEntry entry,
|
||||
string destinationDirectory,
|
||||
ExtractionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ExtractionMethods.WriteEntryToDirectory(entry, destinationDirectory, options,
|
||||
entry.WriteToFile);
|
||||
return ExtractionMethods.WriteEntryToDirectoryAsync(entry, destinationDirectory, options,
|
||||
entry.WriteToFileAsync, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract to specific file
|
||||
/// </summary>
|
||||
public static void WriteToFile(this IArchiveEntry entry,
|
||||
public static ValueTask WriteToFileAsync(this IArchiveEntry entry,
|
||||
string destinationFileName,
|
||||
ExtractionOptions? options = null)
|
||||
ExtractionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
|
||||
ExtractionMethods.WriteEntryToFile(entry, destinationFileName, options,
|
||||
(x, fm) =>
|
||||
return ExtractionMethods.WriteEntryToFileAsync(entry, destinationFileName, options,
|
||||
async (x, fm, ct) =>
|
||||
{
|
||||
using (FileStream fs = File.Open(destinationFileName, fm))
|
||||
{
|
||||
entry.WriteTo(fs);
|
||||
}
|
||||
});
|
||||
await using FileStream fs = File.Open(x, fm);
|
||||
await entry.WriteToAsync(fs, ct);
|
||||
}, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
@@ -8,12 +10,14 @@ namespace SharpCompress.Archives
|
||||
/// <summary>
|
||||
/// Extract to specific directory, retaining filename
|
||||
/// </summary>
|
||||
public static void WriteToDirectory(this IArchive archive, string destinationDirectory,
|
||||
ExtractionOptions? options = null)
|
||||
public static async ValueTask WriteToDirectoryAsync(this IArchive archive,
|
||||
string destinationDirectory,
|
||||
ExtractionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
foreach (IArchiveEntry entry in archive.Entries.Where(x => !x.IsDirectory))
|
||||
await foreach (IArchiveEntry entry in archive.Entries.Where(x => !x.IsDirectory).WithCancellation(cancellationToken))
|
||||
{
|
||||
entry.WriteToDirectory(destinationDirectory, options);
|
||||
await entry.WriteEntryToDirectoryAsync(destinationDirectory, options, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
{
|
||||
internal interface IArchiveExtractionListener : IExtractionListener
|
||||
{
|
||||
void EnsureEntriesLoaded();
|
||||
void FireEntryExtractionBegin(IArchiveEntry entry);
|
||||
void FireEntryExtractionEnd(IArchiveEntry entry);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Writers;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
{
|
||||
public interface IWritableArchive : IArchive
|
||||
{
|
||||
void RemoveEntry(IArchiveEntry entry);
|
||||
ValueTask RemoveEntryAsync(IArchiveEntry entry, CancellationToken cancellationToken = default);
|
||||
|
||||
IArchiveEntry AddEntry(string key, Stream source, bool closeStream, long size = 0, DateTime? modified = null);
|
||||
ValueTask<IArchiveEntry> AddEntryAsync(string key, Stream source, bool closeStream, long size = 0, DateTime? modified = null, CancellationToken cancellationToken = default);
|
||||
|
||||
void SaveTo(Stream stream, WriterOptions options);
|
||||
ValueTask SaveToAsync(Stream stream, WriterOptions options, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Use this to pause entry rebuilding when adding large collections of entries. Dispose when complete. A using statement is recommended.
|
||||
/// </summary>
|
||||
/// <returns>IDisposeable to resume entry rebuilding</returns>
|
||||
IDisposable PauseEntryRebuilding();
|
||||
IAsyncDisposable PauseEntryRebuilding();
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,62 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Writers;
|
||||
|
||||
namespace SharpCompress.Archives
|
||||
{
|
||||
public static class IWritableArchiveExtensions
|
||||
{
|
||||
public static void AddEntry(this IWritableArchive writableArchive,
|
||||
string entryPath, string filePath)
|
||||
public static async ValueTask AddEntryAsync(this IWritableArchive writableArchive,
|
||||
string entryPath, string filePath,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var fileInfo = new FileInfo(filePath);
|
||||
if (!fileInfo.Exists)
|
||||
{
|
||||
throw new FileNotFoundException("Could not AddEntry: " + filePath);
|
||||
}
|
||||
writableArchive.AddEntry(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length,
|
||||
fileInfo.LastWriteTime);
|
||||
await writableArchive.AddEntryAsync(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length,
|
||||
fileInfo.LastWriteTime, cancellationToken);
|
||||
}
|
||||
|
||||
public static void SaveTo(this IWritableArchive writableArchive, string filePath, WriterOptions options)
|
||||
public static Task SaveToAsync(this IWritableArchive writableArchive, string filePath, WriterOptions options, CancellationToken cancellationToken = default)
|
||||
{
|
||||
writableArchive.SaveTo(new FileInfo(filePath), options);
|
||||
return writableArchive.SaveToAsync(new FileInfo(filePath), options, cancellationToken);
|
||||
}
|
||||
|
||||
public static void SaveTo(this IWritableArchive writableArchive, FileInfo fileInfo, WriterOptions options)
|
||||
public static async Task SaveToAsync(this IWritableArchive writableArchive, FileInfo fileInfo, WriterOptions options, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
writableArchive.SaveTo(stream, options);
|
||||
}
|
||||
await using var stream = fileInfo.Open(FileMode.Create, FileAccess.Write);
|
||||
await writableArchive.SaveToAsync(stream, options, cancellationToken);
|
||||
}
|
||||
|
||||
public static void AddAllFromDirectory(
|
||||
public static async ValueTask AddAllFromDirectoryAsync(
|
||||
this IWritableArchive writableArchive,
|
||||
string filePath, string searchPattern = "*.*", SearchOption searchOption = SearchOption.AllDirectories)
|
||||
string filePath, string searchPattern = "*.*",
|
||||
SearchOption searchOption = SearchOption.AllDirectories,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (writableArchive.PauseEntryRebuilding())
|
||||
await using (writableArchive.PauseEntryRebuilding())
|
||||
{
|
||||
foreach (var path in Directory.EnumerateFiles(filePath, searchPattern, searchOption))
|
||||
{
|
||||
var fileInfo = new FileInfo(path);
|
||||
writableArchive.AddEntry(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length,
|
||||
fileInfo.LastWriteTime);
|
||||
await writableArchive.AddEntryAsync(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length,
|
||||
fileInfo.LastWriteTime,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
public static IArchiveEntry AddEntry(this IWritableArchive writableArchive, string key, FileInfo fileInfo)
|
||||
public static ValueTask<IArchiveEntry> AddEntryAsync(this IWritableArchive writableArchive, string key, FileInfo fileInfo,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!fileInfo.Exists)
|
||||
{
|
||||
throw new ArgumentException("FileInfo does not exist.");
|
||||
}
|
||||
return writableArchive.AddEntry(key, fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime);
|
||||
return writableArchive.AddEntryAsync(key, fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Tar;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
@@ -31,10 +34,11 @@ namespace SharpCompress.Archives.Tar
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
public static TarArchive Open(FileInfo fileInfo, ReaderOptions? readerOptions = null)
|
||||
public static TarArchive Open(FileInfo fileInfo, ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
fileInfo.CheckNotNull(nameof(fileInfo));
|
||||
return new TarArchive(fileInfo, readerOptions ?? new ReaderOptions());
|
||||
return new TarArchive(fileInfo, readerOptions ?? new ReaderOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -42,35 +46,35 @@ namespace SharpCompress.Archives.Tar
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
public static TarArchive Open(Stream stream, ReaderOptions? readerOptions = null)
|
||||
public static TarArchive Open(Stream stream, ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
stream.CheckNotNull(nameof(stream));
|
||||
return new TarArchive(stream, readerOptions ?? new ReaderOptions());
|
||||
return new TarArchive(stream, readerOptions ?? new ReaderOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
public static bool IsTarFile(string filePath)
|
||||
public static ValueTask<bool> IsTarFileAsync(string filePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return IsTarFile(new FileInfo(filePath));
|
||||
return IsTarFileAsync(new FileInfo(filePath), cancellationToken);
|
||||
}
|
||||
|
||||
public static bool IsTarFile(FileInfo fileInfo)
|
||||
public static async ValueTask<bool> IsTarFileAsync(FileInfo fileInfo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!fileInfo.Exists)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
using (Stream stream = fileInfo.OpenRead())
|
||||
{
|
||||
return IsTarFile(stream);
|
||||
}
|
||||
|
||||
await using Stream stream = fileInfo.OpenRead();
|
||||
return await IsTarFileAsync(stream, cancellationToken);
|
||||
}
|
||||
|
||||
public static bool IsTarFile(Stream stream)
|
||||
public static async ValueTask<bool> IsTarFileAsync(Stream stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
TarHeader tarHeader = new TarHeader(new ArchiveEncoding());
|
||||
bool readSucceeded = tarHeader.Read(new BinaryReader(stream));
|
||||
TarHeader tarHeader = new(new ArchiveEncoding());
|
||||
bool readSucceeded = await tarHeader.Read(stream, cancellationToken);
|
||||
bool isEmptyArchive = tarHeader.Name.Length == 0 && tarHeader.Size == 0 && Enum.IsDefined(typeof(EntryType), tarHeader.EntryType);
|
||||
return readSucceeded || isEmptyArchive;
|
||||
}
|
||||
@@ -85,14 +89,15 @@ namespace SharpCompress.Archives.Tar
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
internal TarArchive(FileInfo fileInfo, ReaderOptions readerOptions)
|
||||
: base(ArchiveType.Tar, fileInfo, readerOptions)
|
||||
internal TarArchive(FileInfo fileInfo, ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken)
|
||||
: base(ArchiveType.Tar, fileInfo, readerOptions, cancellationToken)
|
||||
{
|
||||
}
|
||||
|
||||
protected override IEnumerable<TarVolume> LoadVolumes(FileInfo file)
|
||||
protected override IAsyncEnumerable<TarVolume> LoadVolumes(FileInfo file, CancellationToken cancellationToken)
|
||||
{
|
||||
return new TarVolume(file.OpenRead(), ReaderOptions).AsEnumerable();
|
||||
return new TarVolume(file.OpenRead(), ReaderOptions).AsAsyncEnumerable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -100,8 +105,9 @@ namespace SharpCompress.Archives.Tar
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
internal TarArchive(Stream stream, ReaderOptions readerOptions)
|
||||
: base(ArchiveType.Tar, stream, readerOptions)
|
||||
internal TarArchive(Stream stream, ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken)
|
||||
: base(ArchiveType.Tar, stream, readerOptions, cancellationToken)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -110,16 +116,18 @@ namespace SharpCompress.Archives.Tar
|
||||
{
|
||||
}
|
||||
|
||||
protected override IEnumerable<TarVolume> LoadVolumes(IEnumerable<Stream> streams)
|
||||
protected override async IAsyncEnumerable<TarVolume> LoadVolumes(IAsyncEnumerable<Stream> streams,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
return new TarVolume(streams.First(), ReaderOptions).AsEnumerable();
|
||||
yield return new TarVolume(await streams.FirstAsync(cancellationToken: cancellationToken), ReaderOptions);
|
||||
}
|
||||
|
||||
protected override IEnumerable<TarArchiveEntry> LoadEntries(IEnumerable<TarVolume> volumes)
|
||||
protected override async IAsyncEnumerable<TarArchiveEntry> LoadEntries(IAsyncEnumerable<TarVolume> volumes,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
Stream stream = volumes.Single().Stream;
|
||||
Stream stream = (await volumes.SingleAsync(cancellationToken: cancellationToken)).Stream;
|
||||
TarHeader? previousHeader = null;
|
||||
foreach (TarHeader? header in TarHeaderFactory.ReadHeader(StreamingMode.Seekable, stream, ReaderOptions.ArchiveEncoding))
|
||||
await foreach (TarHeader? header in TarHeaderFactory.ReadHeader(StreamingMode.Seekable, stream, ReaderOptions.ArchiveEncoding, cancellationToken))
|
||||
{
|
||||
if (header != null)
|
||||
{
|
||||
@@ -136,11 +144,11 @@ namespace SharpCompress.Archives.Tar
|
||||
|
||||
var oldStreamPos = stream.Position;
|
||||
|
||||
using (var entryStream = entry.OpenEntryStream())
|
||||
await using (var entryStream = await entry.OpenEntryStreamAsync(cancellationToken))
|
||||
{
|
||||
using (var memoryStream = new MemoryStream())
|
||||
await using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
entryStream.TransferTo(memoryStream);
|
||||
await entryStream.TransferToAsync(memoryStream, cancellationToken);
|
||||
memoryStream.Position = 0;
|
||||
var bytes = memoryStream.ToArray();
|
||||
|
||||
@@ -160,38 +168,37 @@ namespace SharpCompress.Archives.Tar
|
||||
|
||||
public static TarArchive Create()
|
||||
{
|
||||
return new TarArchive();
|
||||
return new();
|
||||
}
|
||||
|
||||
protected override TarArchiveEntry CreateEntryInternal(string filePath, Stream source,
|
||||
long size, DateTime? modified, bool closeStream)
|
||||
protected override ValueTask<TarArchiveEntry> CreateEntryInternal(string filePath, Stream source,
|
||||
long size, DateTime? modified, bool closeStream,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return new TarWritableArchiveEntry(this, source, CompressionType.Unknown, filePath, size, modified,
|
||||
closeStream);
|
||||
return new (new TarWritableArchiveEntry(this, source, CompressionType.Unknown, filePath, size, modified,
|
||||
closeStream));
|
||||
}
|
||||
|
||||
protected override void SaveTo(Stream stream, WriterOptions options,
|
||||
IEnumerable<TarArchiveEntry> oldEntries,
|
||||
IEnumerable<TarArchiveEntry> newEntries)
|
||||
protected override async ValueTask SaveToAsync(Stream stream, WriterOptions options,
|
||||
IAsyncEnumerable<TarArchiveEntry> oldEntries,
|
||||
IAsyncEnumerable<TarArchiveEntry> newEntries,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (var writer = new TarWriter(stream, new TarWriterOptions(options)))
|
||||
await using var writer = await TarWriter.CreateAsync(stream, new TarWriterOptions(options), cancellationToken);
|
||||
await foreach (var entry in oldEntries.Concat(newEntries)
|
||||
.Where(x => !x.IsDirectory)
|
||||
.WithCancellation(cancellationToken))
|
||||
{
|
||||
foreach (var entry in oldEntries.Concat(newEntries)
|
||||
.Where(x => !x.IsDirectory))
|
||||
{
|
||||
using (var entryStream = entry.OpenEntryStream())
|
||||
{
|
||||
writer.Write(entry.Key, entryStream, entry.LastModifiedTime, entry.Size);
|
||||
}
|
||||
}
|
||||
await using var entryStream = await entry.OpenEntryStreamAsync(cancellationToken);
|
||||
await writer.WriteAsync(entry.Key, entryStream, entry.LastModifiedTime, entry.Size, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
protected override IReader CreateReaderForSolidExtraction()
|
||||
protected override async ValueTask<IReader> CreateReaderForSolidExtraction()
|
||||
{
|
||||
var stream = Volumes.Single().Stream;
|
||||
var stream = (await Volumes.SingleAsync()).Stream;
|
||||
stream.Position = 0;
|
||||
return TarReader.Open(stream);
|
||||
return await TarReader.OpenAsync(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Tar;
|
||||
|
||||
@@ -13,9 +15,9 @@ namespace SharpCompress.Archives.Tar
|
||||
Archive = archive;
|
||||
}
|
||||
|
||||
public virtual Stream OpenEntryStream()
|
||||
public virtual async ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Parts.Single().GetCompressedStream();
|
||||
return await Parts.Single().GetCompressedStreamAsync(cancellationToken);
|
||||
}
|
||||
|
||||
#region IArchiveEntry Members
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -49,18 +51,18 @@ namespace SharpCompress.Archives.Tar
|
||||
internal override IEnumerable<FilePart> Parts => throw new NotImplementedException();
|
||||
Stream IWritableArchiveEntry.Stream => stream;
|
||||
|
||||
public override Stream OpenEntryStream()
|
||||
public override ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//ensure new stream is at the start, this could be reset
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return new NonDisposingStream(stream);
|
||||
return new(new NonDisposingStream(stream));
|
||||
}
|
||||
|
||||
internal override void Close()
|
||||
internal override async ValueTask CloseAsync()
|
||||
{
|
||||
if (closeStream)
|
||||
{
|
||||
stream.Dispose();
|
||||
await stream.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Zip;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
using SharpCompress.IO;
|
||||
using SharpCompress.Readers;
|
||||
using SharpCompress.Readers.Zip;
|
||||
using SharpCompress.Writers;
|
||||
@@ -41,10 +45,11 @@ namespace SharpCompress.Archives.Zip
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
public static ZipArchive Open(FileInfo fileInfo, ReaderOptions? readerOptions = null)
|
||||
public static ZipArchive Open(FileInfo fileInfo, ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
fileInfo.CheckNotNull(nameof(fileInfo));
|
||||
return new ZipArchive(fileInfo, readerOptions ?? new ReaderOptions());
|
||||
return new ZipArchive(fileInfo, readerOptions ?? new ReaderOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -52,35 +57,45 @@ namespace SharpCompress.Archives.Zip
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
public static ZipArchive Open(Stream stream, ReaderOptions? readerOptions = null)
|
||||
public static ZipArchive Open(Stream stream, ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
stream.CheckNotNull(nameof(stream));
|
||||
return new ZipArchive(stream, readerOptions ?? new ReaderOptions());
|
||||
return new ZipArchive(stream, readerOptions ?? new ReaderOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
public static bool IsZipFile(string filePath, string? password = null)
|
||||
public static ValueTask<bool> IsZipFile(string filePath, string? password = null)
|
||||
{
|
||||
return IsZipFile(new FileInfo(filePath), password);
|
||||
return IsZipFileAsync(new FileInfo(filePath), password);
|
||||
}
|
||||
|
||||
public static bool IsZipFile(FileInfo fileInfo, string? password = null)
|
||||
public static async ValueTask<bool> IsZipFileAsync(FileInfo fileInfo, string? password = null)
|
||||
{
|
||||
if (!fileInfo.Exists)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
using (Stream stream = fileInfo.OpenRead())
|
||||
{
|
||||
return IsZipFile(stream, password);
|
||||
}
|
||||
|
||||
await using Stream stream = fileInfo.OpenRead();
|
||||
return await IsZipFileAsync(stream, password);
|
||||
}
|
||||
|
||||
public static bool IsZipFile(Stream stream, string? password = null)
|
||||
public static async ValueTask<bool> IsZipFileAsync(Stream stream, string? password = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
StreamingZipHeaderFactory headerFactory = new StreamingZipHeaderFactory(password, new ArchiveEncoding());
|
||||
StreamingZipHeaderFactory headerFactory = new(password, new ArchiveEncoding());
|
||||
try
|
||||
{
|
||||
ZipHeader? header = headerFactory.ReadStreamHeader(stream).FirstOrDefault(x => x.ZipHeaderType != ZipHeaderType.Split);
|
||||
RewindableStream rewindableStream;
|
||||
if (stream is RewindableStream rs)
|
||||
{
|
||||
rewindableStream = rs;
|
||||
}
|
||||
else
|
||||
{
|
||||
rewindableStream = new RewindableStream(stream);
|
||||
}
|
||||
ZipHeader? header = await headerFactory.ReadStreamHeader(rewindableStream, cancellationToken)
|
||||
.FirstOrDefaultAsync(x => x.ZipHeaderType != ZipHeaderType.Split, cancellationToken: cancellationToken);
|
||||
if (header is null)
|
||||
{
|
||||
return false;
|
||||
@@ -102,15 +117,17 @@ namespace SharpCompress.Archives.Zip
|
||||
/// </summary>
|
||||
/// <param name="fileInfo"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
internal ZipArchive(FileInfo fileInfo, ReaderOptions readerOptions)
|
||||
: base(ArchiveType.Zip, fileInfo, readerOptions)
|
||||
internal ZipArchive(FileInfo fileInfo, ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken)
|
||||
: base(ArchiveType.Zip, fileInfo, readerOptions, cancellationToken)
|
||||
{
|
||||
headerFactory = new SeekableZipHeaderFactory(readerOptions.Password, readerOptions.ArchiveEncoding);
|
||||
}
|
||||
|
||||
protected override IEnumerable<ZipVolume> LoadVolumes(FileInfo file)
|
||||
protected override IAsyncEnumerable<ZipVolume> LoadVolumes(FileInfo file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return new ZipVolume(file.OpenRead(), ReaderOptions).AsEnumerable();
|
||||
return new ZipVolume(file.OpenRead(), ReaderOptions).AsAsyncEnumerable();
|
||||
}
|
||||
|
||||
internal ZipArchive()
|
||||
@@ -123,82 +140,86 @@ namespace SharpCompress.Archives.Zip
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="readerOptions"></param>
|
||||
internal ZipArchive(Stream stream, ReaderOptions readerOptions)
|
||||
: base(ArchiveType.Zip, stream, readerOptions)
|
||||
internal ZipArchive(Stream stream, ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken)
|
||||
: base(ArchiveType.Zip, stream, readerOptions, cancellationToken)
|
||||
{
|
||||
headerFactory = new SeekableZipHeaderFactory(readerOptions.Password, readerOptions.ArchiveEncoding);
|
||||
}
|
||||
|
||||
protected override IEnumerable<ZipVolume> LoadVolumes(IEnumerable<Stream> streams)
|
||||
protected override async IAsyncEnumerable<ZipVolume> LoadVolumes(IAsyncEnumerable<Stream> streams,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
return new ZipVolume(streams.First(), ReaderOptions).AsEnumerable();
|
||||
yield return new ZipVolume(await streams.FirstAsync(cancellationToken: cancellationToken), ReaderOptions);
|
||||
}
|
||||
|
||||
protected override IEnumerable<ZipArchiveEntry> LoadEntries(IEnumerable<ZipVolume> volumes)
|
||||
protected override async IAsyncEnumerable<ZipArchiveEntry> LoadEntries(IAsyncEnumerable<ZipVolume> volumes,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
var volume = volumes.Single();
|
||||
await Task.CompletedTask;
|
||||
var volume = await volumes.SingleAsync(cancellationToken: cancellationToken);
|
||||
Stream stream = volume.Stream;
|
||||
foreach (ZipHeader h in headerFactory.ReadSeekableHeader(stream))
|
||||
await foreach (ZipHeader h in headerFactory.ReadSeekableHeader(stream, cancellationToken))
|
||||
{
|
||||
if (h != null)
|
||||
{
|
||||
switch (h.ZipHeaderType)
|
||||
{
|
||||
case ZipHeaderType.DirectoryEntry:
|
||||
{
|
||||
yield return new ZipArchiveEntry(this,
|
||||
new SeekableZipFilePart(headerFactory,
|
||||
(DirectoryEntryHeader)h,
|
||||
stream));
|
||||
}
|
||||
{
|
||||
yield return new ZipArchiveEntry(this,
|
||||
new SeekableZipFilePart(headerFactory,
|
||||
(DirectoryEntryHeader)h,
|
||||
stream));
|
||||
}
|
||||
break;
|
||||
case ZipHeaderType.DirectoryEnd:
|
||||
{
|
||||
byte[] bytes = ((DirectoryEndHeader)h).Comment ?? Array.Empty<byte>();
|
||||
volume.Comment = ReaderOptions.ArchiveEncoding.Decode(bytes);
|
||||
yield break;
|
||||
}
|
||||
{
|
||||
byte[] bytes = ((DirectoryEndHeader)h).Comment ?? Array.Empty<byte>();
|
||||
volume.Comment = ReaderOptions.ArchiveEncoding.Decode(bytes);
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveTo(Stream stream)
|
||||
public ValueTask SaveToAsync(Stream stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SaveTo(stream, new WriterOptions(CompressionType.Deflate));
|
||||
return SaveToAsync(stream, new WriterOptions(CompressionType.Deflate), cancellationToken);
|
||||
}
|
||||
|
||||
protected override void SaveTo(Stream stream, WriterOptions options,
|
||||
IEnumerable<ZipArchiveEntry> oldEntries,
|
||||
IEnumerable<ZipArchiveEntry> newEntries)
|
||||
protected override async ValueTask SaveToAsync(Stream stream, WriterOptions options,
|
||||
IAsyncEnumerable<ZipArchiveEntry> oldEntries,
|
||||
IAsyncEnumerable<ZipArchiveEntry> newEntries,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (var writer = new ZipWriter(stream, new ZipWriterOptions(options)))
|
||||
await using var writer = new ZipWriter(stream, new ZipWriterOptions(options));
|
||||
await foreach (var entry in oldEntries.Concat(newEntries)
|
||||
.Where(x => !x.IsDirectory)
|
||||
.WithCancellation(cancellationToken))
|
||||
{
|
||||
foreach (var entry in oldEntries.Concat(newEntries)
|
||||
.Where(x => !x.IsDirectory))
|
||||
await using (var entryStream = await entry.OpenEntryStreamAsync(cancellationToken))
|
||||
{
|
||||
using (var entryStream = entry.OpenEntryStream())
|
||||
{
|
||||
writer.Write(entry.Key, entryStream, entry.LastModifiedTime);
|
||||
}
|
||||
await writer.WriteAsync(entry.Key, entryStream, entry.LastModifiedTime, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override ZipArchiveEntry CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified,
|
||||
bool closeStream)
|
||||
protected override ValueTask<ZipArchiveEntry> CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified,
|
||||
bool closeStream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream);
|
||||
return new(new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream));
|
||||
}
|
||||
|
||||
public static ZipArchive Create()
|
||||
{
|
||||
return new ZipArchive();
|
||||
return new();
|
||||
}
|
||||
|
||||
protected override IReader CreateReaderForSolidExtraction()
|
||||
protected override async ValueTask<IReader> CreateReaderForSolidExtraction()
|
||||
{
|
||||
var stream = Volumes.Single().Stream;
|
||||
var stream = (await Volumes.SingleAsync()).Stream;
|
||||
stream.Position = 0;
|
||||
return ZipReader.Open(stream, ReaderOptions);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Zip;
|
||||
|
||||
namespace SharpCompress.Archives.Zip
|
||||
@@ -12,9 +14,9 @@ namespace SharpCompress.Archives.Zip
|
||||
Archive = archive;
|
||||
}
|
||||
|
||||
public virtual Stream OpenEntryStream()
|
||||
public virtual ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Parts.Single().GetCompressedStream();
|
||||
return Parts.Single().GetCompressedStreamAsync(cancellationToken);
|
||||
}
|
||||
|
||||
#region IArchiveEntry Members
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -49,18 +51,18 @@ namespace SharpCompress.Archives.Zip
|
||||
|
||||
Stream IWritableArchiveEntry.Stream => stream;
|
||||
|
||||
public override Stream OpenEntryStream()
|
||||
public override ValueTask<Stream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//ensure new stream is at the start, this could be reset
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return new NonDisposingStream(stream);
|
||||
return new(new NonDisposingStream(stream));
|
||||
}
|
||||
|
||||
internal override void Close()
|
||||
internal override async ValueTask CloseAsync()
|
||||
{
|
||||
if (closeStream && !isDisposed)
|
||||
{
|
||||
stream.Dispose();
|
||||
await stream.DisposeAsync();
|
||||
isDisposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
25
src/SharpCompress/AsyncEnumerable.cs
Normal file
25
src/SharpCompress/AsyncEnumerable.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress
|
||||
{
|
||||
public static class AsyncEnumerable
|
||||
{
|
||||
public static IAsyncEnumerable<T> Empty<T>() => EmptyAsyncEnumerable<T>.Instance;
|
||||
|
||||
|
||||
private class EmptyAsyncEnumerable<T> : IAsyncEnumerator<T>, IAsyncEnumerable<T>
|
||||
{
|
||||
public static readonly EmptyAsyncEnumerable<T> Instance =
|
||||
new();
|
||||
public T Current => default!;
|
||||
public ValueTask DisposeAsync() => default;
|
||||
public ValueTask<bool> MoveNextAsync() => new(false);
|
||||
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ namespace SharpCompress.Common
|
||||
/// Set this when you want to use a custom method for all decoding operations.
|
||||
/// </summary>
|
||||
/// <returns>string Func(bytes, index, length)</returns>
|
||||
public Func<byte[], int, int, string>? CustomDecoder { get; set; }
|
||||
//public Func<byte[], int, int, string>? CustomDecoder { get; set; }
|
||||
|
||||
public ArchiveEncoding()
|
||||
: this(Encoding.Default, Encoding.Default)
|
||||
@@ -50,7 +50,12 @@ namespace SharpCompress.Common
|
||||
|
||||
public string Decode(byte[] bytes, int start, int length)
|
||||
{
|
||||
return GetDecoder().Invoke(bytes, start, length);
|
||||
return GetEncoding().GetString(bytes, start, length);
|
||||
}
|
||||
|
||||
public string Decode(ReadOnlySpan<byte> span)
|
||||
{
|
||||
return GetEncoding().GetString(span);
|
||||
}
|
||||
|
||||
public string DecodeUTF8(byte[] bytes)
|
||||
@@ -67,10 +72,5 @@ namespace SharpCompress.Common
|
||||
{
|
||||
return Forced ?? Default ?? Encoding.UTF8;
|
||||
}
|
||||
|
||||
public Func<byte[], int, int, string> GetDecoder()
|
||||
{
|
||||
return CustomDecoder ?? ((bytes, index, count) => GetEncoding().GetString(bytes, index, count));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common
|
||||
{
|
||||
@@ -77,8 +78,9 @@ namespace SharpCompress.Common
|
||||
|
||||
internal bool IsSolid { get; set; }
|
||||
|
||||
internal virtual void Close()
|
||||
internal virtual ValueTask CloseAsync()
|
||||
{
|
||||
return new ();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
using SharpCompress.Readers;
|
||||
|
||||
namespace SharpCompress.Common
|
||||
{
|
||||
public class EntryStream : Stream
|
||||
public class EntryStream : AsyncStream
|
||||
{
|
||||
private readonly IReader _reader;
|
||||
private readonly Stream _stream;
|
||||
@@ -20,25 +23,24 @@ namespace SharpCompress.Common
|
||||
/// <summary>
|
||||
/// When reading a stream from OpenEntryStream, the stream must be completed so use this to finish reading the entire entry.
|
||||
/// </summary>
|
||||
public void SkipEntry()
|
||||
public async ValueTask SkipEntryAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
this.Skip();
|
||||
await this.SkipAsync(cancellationToken);
|
||||
_completed = true;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (!(_completed || _reader.Cancelled))
|
||||
{
|
||||
SkipEntry();
|
||||
await SkipEntryAsync();
|
||||
}
|
||||
if (_isDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_isDisposed = true;
|
||||
base.Dispose(disposing);
|
||||
_stream.Dispose();
|
||||
await _stream.DisposeAsync();
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
@@ -46,18 +48,13 @@ namespace SharpCompress.Common
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override long Length => _stream.Length;
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
int read = _stream.Read(buffer, offset, count);
|
||||
int read = await _stream.ReadAsync(buffer, cancellationToken);
|
||||
if (read <= 0)
|
||||
{
|
||||
_completed = true;
|
||||
@@ -65,14 +62,14 @@ namespace SharpCompress.Common
|
||||
return read;
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
int value = _stream.ReadByte();
|
||||
if (value == -1)
|
||||
{
|
||||
_completed = true;
|
||||
}
|
||||
return value;
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
@@ -84,10 +81,5 @@ namespace SharpCompress.Common
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common
|
||||
{
|
||||
@@ -8,10 +10,11 @@ namespace SharpCompress.Common
|
||||
/// <summary>
|
||||
/// Extract to specific directory, retaining filename
|
||||
/// </summary>
|
||||
public static void WriteEntryToDirectory(IEntry entry,
|
||||
public static async ValueTask WriteEntryToDirectoryAsync(IEntry entry,
|
||||
string destinationDirectory,
|
||||
ExtractionOptions? options,
|
||||
Action<string, ExtractionOptions?> write)
|
||||
Func<string, ExtractionOptions?, CancellationToken, ValueTask> write,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
string destinationFileName;
|
||||
string file = Path.GetFileName(entry.Key);
|
||||
@@ -52,7 +55,7 @@ namespace SharpCompress.Common
|
||||
{
|
||||
throw new ExtractionException("Entry is trying to write a file outside of the destination directory.");
|
||||
}
|
||||
write(destinationFileName, options);
|
||||
await write(destinationFileName, options, cancellationToken);
|
||||
}
|
||||
else if (options.ExtractFullPath && !Directory.Exists(destinationFileName))
|
||||
{
|
||||
@@ -60,11 +63,12 @@ namespace SharpCompress.Common
|
||||
}
|
||||
}
|
||||
|
||||
public static void WriteEntryToFile(IEntry entry, string destinationFileName,
|
||||
public static async ValueTask WriteEntryToFileAsync(IEntry entry, string destinationFileName,
|
||||
ExtractionOptions? options,
|
||||
Action<string, FileMode> openAndWrite)
|
||||
Func<string, FileMode, CancellationToken, ValueTask> openAndWrite,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (entry.LinkTarget != null)
|
||||
if (entry.LinkTarget is not null)
|
||||
{
|
||||
if (options?.WriteSymbolicLink is null)
|
||||
{
|
||||
@@ -85,7 +89,7 @@ namespace SharpCompress.Common
|
||||
fm = FileMode.CreateNew;
|
||||
}
|
||||
|
||||
openAndWrite(destinationFileName, fm);
|
||||
await openAndWrite(destinationFileName, fm, cancellationToken);
|
||||
entry.PreserveExtractionOptions(destinationFileName, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common
|
||||
{
|
||||
@@ -11,9 +13,9 @@ namespace SharpCompress.Common
|
||||
|
||||
internal ArchiveEncoding ArchiveEncoding { get; }
|
||||
|
||||
internal abstract string FilePartName { get; }
|
||||
internal abstract string? FilePartName { get; }
|
||||
|
||||
internal abstract Stream GetCompressedStream();
|
||||
internal abstract ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken);
|
||||
internal abstract Stream? GetRawStream();
|
||||
internal bool Skipped { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace SharpCompress.Common.GZip
|
||||
{
|
||||
@@ -17,7 +19,7 @@ namespace SharpCompress.Common.GZip
|
||||
|
||||
public override long Crc => _filePart.Crc ?? 0;
|
||||
|
||||
public override string Key => _filePart.FilePartName;
|
||||
public override string Key => _filePart.FilePartName ?? string.Empty;
|
||||
|
||||
public override string? LinkTarget => null;
|
||||
|
||||
@@ -41,9 +43,12 @@ namespace SharpCompress.Common.GZip
|
||||
|
||||
internal override IEnumerable<FilePart> Parts => _filePart.AsEnumerable<FilePart>();
|
||||
|
||||
internal static IEnumerable<GZipEntry> GetEntries(Stream stream, OptionsBase options)
|
||||
internal static async IAsyncEnumerable<GZipEntry> GetEntries(Stream stream, OptionsBase options,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
yield return new GZipEntry(new GZipFilePart(stream, options.ArchiveEncoding));
|
||||
var part = new GZipFilePart(options.ArchiveEncoding);
|
||||
await part.Initialize(stream, cancellationToken);
|
||||
yield return new GZipEntry(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
using SharpCompress.Compressors;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
@@ -11,34 +14,44 @@ namespace SharpCompress.Common.GZip
|
||||
internal sealed class GZipFilePart : FilePart
|
||||
{
|
||||
private string? _name;
|
||||
private readonly Stream _stream;
|
||||
//init only
|
||||
#nullable disable
|
||||
private Stream _stream;
|
||||
#nullable enable
|
||||
|
||||
internal GZipFilePart(Stream stream, ArchiveEncoding archiveEncoding)
|
||||
internal GZipFilePart(ArchiveEncoding archiveEncoding)
|
||||
: base(archiveEncoding)
|
||||
{
|
||||
}
|
||||
|
||||
internal async ValueTask Initialize(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
_stream = stream;
|
||||
ReadAndValidateGzipHeader();
|
||||
if (stream.CanSeek)
|
||||
{
|
||||
long position = stream.Position;
|
||||
stream.Position = stream.Length - 8;
|
||||
ReadTrailer();
|
||||
await ReadTrailerAsync(cancellationToken);
|
||||
stream.Position = position;
|
||||
}
|
||||
EntryStartPosition = stream.Position;
|
||||
}
|
||||
|
||||
internal long EntryStartPosition { get; }
|
||||
internal long EntryStartPosition { get; private set; }
|
||||
|
||||
internal DateTime? DateModified { get; private set; }
|
||||
internal int? Crc { get; private set; }
|
||||
internal int? UncompressedSize { get; private set; }
|
||||
|
||||
internal override string FilePartName => _name!;
|
||||
internal override string? FilePartName => _name;
|
||||
|
||||
internal override Stream GetCompressedStream()
|
||||
internal override async ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return new DeflateStream(_stream, CompressionMode.Decompress, CompressionLevel.Default);
|
||||
var stream = new GZipStream(_stream, CompressionMode.Decompress, CompressionLevel.Default);
|
||||
await stream.ReadAsync(Array.Empty<byte>(), 0, 0, cancellationToken);
|
||||
_name = stream.FileName;
|
||||
DateModified = stream.LastModified;
|
||||
return stream;
|
||||
}
|
||||
|
||||
internal override Stream GetRawStream()
|
||||
@@ -46,93 +59,12 @@ namespace SharpCompress.Common.GZip
|
||||
return _stream;
|
||||
}
|
||||
|
||||
private void ReadTrailer()
|
||||
private async ValueTask ReadTrailerAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32
|
||||
Span<byte> trailer = stackalloc byte[8];
|
||||
int n = _stream.Read(trailer);
|
||||
|
||||
Crc = BinaryPrimitives.ReadInt32LittleEndian(trailer);
|
||||
UncompressedSize = BinaryPrimitives.ReadInt32LittleEndian(trailer.Slice(4));
|
||||
}
|
||||
|
||||
private void ReadAndValidateGzipHeader()
|
||||
{
|
||||
// read the header on the first read
|
||||
Span<byte> header = stackalloc byte[10];
|
||||
int n = _stream.Read(header);
|
||||
|
||||
// workitem 8501: handle edge case (decompress empty stream)
|
||||
if (n == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (n != 10)
|
||||
{
|
||||
throw new ZlibException("Not a valid GZIP stream.");
|
||||
}
|
||||
|
||||
if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
|
||||
{
|
||||
throw new ZlibException("Bad GZIP header.");
|
||||
}
|
||||
|
||||
int timet = BinaryPrimitives.ReadInt32LittleEndian(header.Slice(4));
|
||||
DateModified = TarHeader.EPOCH.AddSeconds(timet);
|
||||
if ((header[3] & 0x04) == 0x04)
|
||||
{
|
||||
// read and discard extra field
|
||||
n = _stream.Read(header.Slice(0, 2)); // 2-byte length field
|
||||
|
||||
short extraLength = (short)(header[0] + header[1] * 256);
|
||||
byte[] extra = new byte[extraLength];
|
||||
|
||||
if (!_stream.ReadFully(extra))
|
||||
{
|
||||
throw new ZlibException("Unexpected end-of-file reading GZIP header.");
|
||||
}
|
||||
n = extraLength;
|
||||
}
|
||||
if ((header[3] & 0x08) == 0x08)
|
||||
{
|
||||
_name = ReadZeroTerminatedString(_stream);
|
||||
}
|
||||
if ((header[3] & 0x10) == 0x010)
|
||||
{
|
||||
ReadZeroTerminatedString(_stream);
|
||||
}
|
||||
if ((header[3] & 0x02) == 0x02)
|
||||
{
|
||||
_stream.ReadByte(); // CRC16, ignore
|
||||
}
|
||||
}
|
||||
|
||||
private string ReadZeroTerminatedString(Stream stream)
|
||||
{
|
||||
Span<byte> buf1 = stackalloc byte[1];
|
||||
var list = new List<byte>();
|
||||
bool done = false;
|
||||
do
|
||||
{
|
||||
// workitem 7740
|
||||
int n = stream.Read(buf1);
|
||||
if (n != 1)
|
||||
{
|
||||
throw new ZlibException("Unexpected EOF reading GZIP header.");
|
||||
}
|
||||
if (buf1[0] == 0)
|
||||
{
|
||||
done = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(buf1[0]);
|
||||
}
|
||||
}
|
||||
while (!done);
|
||||
byte[] buffer = list.ToArray();
|
||||
return ArchiveEncoding.Decode(buffer);
|
||||
Crc = await _stream.ReadInt32(cancellationToken);
|
||||
UncompressedSize = await _stream.ReadInt32(cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace SharpCompress.Common
|
||||
{
|
||||
public interface IVolume : IDisposable
|
||||
public interface IVolume : IAsyncDisposable
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors.LZMA;
|
||||
using SharpCompress.Compressors.LZMA.Utilites;
|
||||
using SharpCompress.IO;
|
||||
@@ -783,7 +785,7 @@ namespace SharpCompress.Common.SevenZip
|
||||
}
|
||||
}
|
||||
|
||||
private List<byte[]> ReadAndDecodePackedStreams(long baseOffset, IPasswordProvider pass)
|
||||
private async ValueTask<List<byte[]>> ReadAndDecodePackedStreams(long baseOffset, IPasswordProvider pass, CancellationToken cancellationToken)
|
||||
{
|
||||
#if DEBUG
|
||||
Log.WriteLine("-- ReadAndDecodePackedStreams --");
|
||||
@@ -815,8 +817,8 @@ namespace SharpCompress.Common.SevenZip
|
||||
dataStartPos += packSize;
|
||||
}
|
||||
|
||||
var outStream = DecoderStreamHelper.CreateDecoderStream(_stream, oldDataStartPos, myPackSizes,
|
||||
folder, pass);
|
||||
var outStream = await DecoderStreamHelper.CreateDecoderStream(_stream, oldDataStartPos, myPackSizes,
|
||||
folder, pass, cancellationToken);
|
||||
|
||||
int unpackSize = checked((int)folder.GetUnpackSize());
|
||||
byte[] data = new byte[unpackSize];
|
||||
@@ -845,7 +847,7 @@ namespace SharpCompress.Common.SevenZip
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadHeader(ArchiveDatabase db, IPasswordProvider getTextPassword)
|
||||
private async ValueTask ReadHeader(ArchiveDatabase db, IPasswordProvider getTextPassword, CancellationToken cancellationToken)
|
||||
{
|
||||
#if DEBUG
|
||||
Log.WriteLine("-- ReadHeader --");
|
||||
@@ -864,7 +866,7 @@ namespace SharpCompress.Common.SevenZip
|
||||
List<byte[]> dataVector = null;
|
||||
if (type == BlockType.AdditionalStreamsInfo)
|
||||
{
|
||||
dataVector = ReadAndDecodePackedStreams(db._startPositionAfterHeader, getTextPassword);
|
||||
dataVector = await ReadAndDecodePackedStreams(db._startPositionAfterHeader, getTextPassword, cancellationToken);
|
||||
type = ReadId();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Common.SevenZip
|
||||
@@ -35,11 +37,11 @@ namespace SharpCompress.Common.SevenZip
|
||||
return null;
|
||||
}
|
||||
|
||||
internal override Stream GetCompressedStream()
|
||||
internal override async ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Header.HasStream)
|
||||
{
|
||||
return null!;
|
||||
return Stream.Null;
|
||||
}
|
||||
var folderStream = _database.GetFolderStream(_stream, Folder!, _database.PasswordProvider);
|
||||
|
||||
@@ -52,7 +54,7 @@ namespace SharpCompress.Common.SevenZip
|
||||
}
|
||||
if (skipSize > 0)
|
||||
{
|
||||
folderStream.Skip(skipSize);
|
||||
await folderStream.SkipAsync(skipSize, cancellationToken);
|
||||
}
|
||||
return new ReadOnlySubStream(folderStream, Header.Size);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Tar.Headers
|
||||
{
|
||||
@@ -32,48 +35,48 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
|
||||
internal const int BLOCK_SIZE = 512;
|
||||
|
||||
internal void Write(Stream output)
|
||||
internal async Task WriteAsync(Stream output)
|
||||
{
|
||||
byte[] buffer = new byte[BLOCK_SIZE];
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(BLOCK_SIZE);
|
||||
|
||||
WriteOctalBytes(511, buffer, 100, 8); // file mode
|
||||
WriteOctalBytes(0, buffer, 108, 8); // owner ID
|
||||
WriteOctalBytes(0, buffer, 116, 8); // group ID
|
||||
WriteOctalBytes(511, buffer.Memory.Span, 100, 8); // file mode
|
||||
WriteOctalBytes(0, buffer.Memory.Span, 108, 8); // owner ID
|
||||
WriteOctalBytes(0, buffer.Memory.Span, 116, 8); // group ID
|
||||
|
||||
//ArchiveEncoding.UTF8.GetBytes("magic").CopyTo(buffer, 257);
|
||||
var nameByteCount = ArchiveEncoding.GetEncoding().GetByteCount(Name);
|
||||
if (nameByteCount > 100)
|
||||
{
|
||||
// Set mock filename and filetype to indicate the next block is the actual name of the file
|
||||
WriteStringBytes("././@LongLink", buffer, 0, 100);
|
||||
buffer[156] = (byte)EntryType.LongName;
|
||||
WriteOctalBytes(nameByteCount + 1, buffer, 124, 12);
|
||||
WriteStringBytes("././@LongLink", buffer.Memory.Span, 0, 100);
|
||||
buffer.Memory.Span[156] = (byte)EntryType.LongName;
|
||||
WriteOctalBytes(nameByteCount + 1, buffer.Memory.Span, 124, 12);
|
||||
}
|
||||
else
|
||||
{
|
||||
WriteStringBytes(ArchiveEncoding.Encode(Name), buffer, 100);
|
||||
WriteOctalBytes(Size, buffer, 124, 12);
|
||||
WriteStringBytes(ArchiveEncoding.Encode(Name), buffer.Memory, 100);
|
||||
WriteOctalBytes(Size, buffer.Memory.Span, 124, 12);
|
||||
var time = (long)(LastModifiedTime.ToUniversalTime() - EPOCH).TotalSeconds;
|
||||
WriteOctalBytes(time, buffer, 136, 12);
|
||||
buffer[156] = (byte)EntryType;
|
||||
WriteOctalBytes(time, buffer.Memory.Span, 136, 12);
|
||||
buffer.Memory.Span[156] = (byte)EntryType;
|
||||
|
||||
if (Size >= 0x1FFFFFFFF)
|
||||
{
|
||||
Span<byte> bytes12 = stackalloc byte[12];
|
||||
BinaryPrimitives.WriteInt64BigEndian(bytes12.Slice(4), Size);
|
||||
bytes12[0] |= 0x80;
|
||||
bytes12.CopyTo(buffer.AsSpan(124));
|
||||
using var bytes12 = MemoryPool<byte>.Shared.Rent(12);
|
||||
BinaryPrimitives.WriteInt64BigEndian(bytes12.Memory.Span.Slice(4), Size);
|
||||
bytes12.Memory.Span[0] |= 0x80;
|
||||
bytes12.Memory.CopyTo(buffer.Memory.Slice(124));
|
||||
}
|
||||
}
|
||||
|
||||
int crc = RecalculateChecksum(buffer);
|
||||
WriteOctalBytes(crc, buffer, 148, 8);
|
||||
int crc = RecalculateChecksum(buffer.Memory);
|
||||
WriteOctalBytes(crc, buffer.Memory.Span, 148, 8);
|
||||
|
||||
output.Write(buffer, 0, buffer.Length);
|
||||
await output.WriteAsync(buffer.Memory.Slice(0, BLOCK_SIZE));
|
||||
|
||||
if (nameByteCount > 100)
|
||||
{
|
||||
WriteLongFilenameHeader(output);
|
||||
await WriteLongFilenameHeaderAsync(output);
|
||||
// update to short name lower than 100 - [max bytes of one character].
|
||||
// subtracting bytes is needed because preventing infinite loop(example code is here).
|
||||
//
|
||||
@@ -82,14 +85,14 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
//
|
||||
// and then infinite recursion is occured in WriteLongFilenameHeader because truncated.Length is 102.
|
||||
Name = ArchiveEncoding.Decode(ArchiveEncoding.Encode(Name), 0, 100 - ArchiveEncoding.GetEncoding().GetMaxByteCount(1));
|
||||
Write(output);
|
||||
await WriteAsync(output);
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteLongFilenameHeader(Stream output)
|
||||
private async Task WriteLongFilenameHeaderAsync(Stream output)
|
||||
{
|
||||
byte[] nameBytes = ArchiveEncoding.Encode(Name);
|
||||
output.Write(nameBytes, 0, nameBytes.Length);
|
||||
await output.WriteAsync(nameBytes.AsMemory());
|
||||
|
||||
// pad to multiple of BlockSize bytes, and make sure a terminating null is added
|
||||
int numPaddingBytes = BLOCK_SIZE - (nameBytes.Length % BLOCK_SIZE);
|
||||
@@ -97,48 +100,56 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
{
|
||||
numPaddingBytes = BLOCK_SIZE;
|
||||
}
|
||||
output.Write(stackalloc byte[numPaddingBytes]);
|
||||
|
||||
using var padding = MemoryPool<byte>.Shared.Rent(numPaddingBytes);
|
||||
padding.Memory.Span.Clear();
|
||||
await output.WriteAsync(padding.Memory.Slice(0, numPaddingBytes));
|
||||
}
|
||||
|
||||
internal bool Read(BinaryReader reader)
|
||||
internal async ValueTask<bool> Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var buffer = ReadBlock(reader);
|
||||
if (buffer.Length == 0)
|
||||
var block = MemoryPool<byte>.Shared.Rent(BLOCK_SIZE);
|
||||
bool readFullyAsync = await stream.ReadAsync(block.Memory.Slice(0, BLOCK_SIZE), cancellationToken) == BLOCK_SIZE;
|
||||
if (readFullyAsync is false)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// for symlinks, additionally read the linkname
|
||||
if (ReadEntryType(buffer) == EntryType.SymLink)
|
||||
if (ReadEntryType(block.Memory.Span) == EntryType.SymLink)
|
||||
{
|
||||
LinkName = ArchiveEncoding.Decode(buffer, 157, 100).TrimNulls();
|
||||
LinkName = ArchiveEncoding.Decode(block.Memory.Span.Slice(157, 100)).TrimNulls();
|
||||
}
|
||||
|
||||
if (ReadEntryType(buffer) == EntryType.LongName)
|
||||
if (ReadEntryType(block.Memory.Span) == EntryType.LongName)
|
||||
{
|
||||
Name = ReadLongName(reader, buffer);
|
||||
buffer = ReadBlock(reader);
|
||||
Name = await ReadLongName(stream, block.Memory.Slice(0,BLOCK_SIZE), cancellationToken);
|
||||
readFullyAsync = await stream.ReadAsync(block.Memory.Slice(0, BLOCK_SIZE), cancellationToken) == BLOCK_SIZE;
|
||||
if (readFullyAsync is false)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Name = ArchiveEncoding.Decode(buffer, 0, 100).TrimNulls();
|
||||
Name = ArchiveEncoding.Decode(block.Memory.Span.Slice( 0, 100)).TrimNulls();
|
||||
}
|
||||
|
||||
EntryType = ReadEntryType(buffer);
|
||||
Size = ReadSize(buffer);
|
||||
EntryType = ReadEntryType(block.Memory.Span);
|
||||
Size = ReadSize(block.Memory.Slice(0, BLOCK_SIZE));
|
||||
|
||||
//Mode = ReadASCIIInt32Base8(buffer, 100, 7);
|
||||
//UserId = ReadASCIIInt32Base8(buffer, 108, 7);
|
||||
//GroupId = ReadASCIIInt32Base8(buffer, 116, 7);
|
||||
long unixTimeStamp = ReadAsciiInt64Base8(buffer, 136, 11);
|
||||
long unixTimeStamp = ReadAsciiInt64Base8(block.Memory.Span.Slice(136, 11));
|
||||
LastModifiedTime = EPOCH.AddSeconds(unixTimeStamp).ToLocalTime();
|
||||
|
||||
Magic = ArchiveEncoding.Decode(buffer, 257, 6).TrimNulls();
|
||||
Magic = ArchiveEncoding.Decode(block.Memory.Span.Slice( 257, 6)).TrimNulls();
|
||||
|
||||
if (!string.IsNullOrEmpty(Magic)
|
||||
&& "ustar".Equals(Magic))
|
||||
{
|
||||
string namePrefix = ArchiveEncoding.Decode(buffer, 345, 157);
|
||||
string namePrefix = ArchiveEncoding.Decode(block.Memory.Span.Slice( 345, 157));
|
||||
namePrefix = namePrefix.TrimNulls();
|
||||
if (!string.IsNullOrEmpty(namePrefix))
|
||||
{
|
||||
@@ -153,55 +164,46 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
return true;
|
||||
}
|
||||
|
||||
private string ReadLongName(BinaryReader reader, byte[] buffer)
|
||||
private async ValueTask<string> ReadLongName(Stream reader, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
|
||||
{
|
||||
var size = ReadSize(buffer);
|
||||
var nameLength = (int)size;
|
||||
var nameBytes = reader.ReadBytes(nameLength);
|
||||
using var rented = MemoryPool<byte>.Shared.Rent(nameLength);
|
||||
var nameBytes = rented.Memory.Slice(0, nameLength);
|
||||
await reader.ReadAsync(nameBytes, cancellationToken);
|
||||
var remainingBytesToRead = BLOCK_SIZE - (nameLength % BLOCK_SIZE);
|
||||
|
||||
// Read the rest of the block and discard the data
|
||||
if (remainingBytesToRead < BLOCK_SIZE)
|
||||
{
|
||||
reader.ReadBytes(remainingBytesToRead);
|
||||
using var remaining = MemoryPool<byte>.Shared.Rent(remainingBytesToRead);
|
||||
await reader.ReadAsync(remaining.Memory.Slice(0, remainingBytesToRead), cancellationToken);
|
||||
}
|
||||
return ArchiveEncoding.Decode(nameBytes, 0, nameBytes.Length).TrimNulls();
|
||||
return ArchiveEncoding.Decode(nameBytes.Span).TrimNulls();
|
||||
}
|
||||
|
||||
private static EntryType ReadEntryType(byte[] buffer)
|
||||
private static EntryType ReadEntryType(Span<byte> buffer)
|
||||
{
|
||||
return (EntryType)buffer[156];
|
||||
}
|
||||
|
||||
private long ReadSize(byte[] buffer)
|
||||
private long ReadSize(ReadOnlyMemory<byte> buffer)
|
||||
{
|
||||
if ((buffer[124] & 0x80) == 0x80) // if size in binary
|
||||
if ((buffer.Span[124] & 0x80) == 0x80) // if size in binary
|
||||
{
|
||||
return BinaryPrimitives.ReadInt64BigEndian(buffer.AsSpan(0x80));
|
||||
return BinaryPrimitives.ReadInt64BigEndian(buffer.Span.Slice(0x80));
|
||||
}
|
||||
|
||||
return ReadAsciiInt64Base8(buffer, 124, 11);
|
||||
return ReadAsciiInt64Base8(buffer.Span.Slice(124, 11));
|
||||
}
|
||||
|
||||
private static byte[] ReadBlock(BinaryReader reader)
|
||||
private static void WriteStringBytes(ReadOnlySpan<byte> name, Memory<byte> buffer, int length)
|
||||
{
|
||||
byte[] buffer = reader.ReadBytes(BLOCK_SIZE);
|
||||
|
||||
if (buffer.Length != 0 && buffer.Length < BLOCK_SIZE)
|
||||
{
|
||||
throw new InvalidOperationException("Buffer is invalid size");
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static void WriteStringBytes(ReadOnlySpan<byte> name, Span<byte> buffer, int length)
|
||||
{
|
||||
name.CopyTo(buffer);
|
||||
name.CopyTo(buffer.Span.Slice(0));
|
||||
int i = Math.Min(length, name.Length);
|
||||
buffer.Slice(i, length - i).Clear();
|
||||
buffer.Slice(i, length - i).Span.Clear();
|
||||
}
|
||||
|
||||
private static void WriteStringBytes(string name, byte[] buffer, int offset, int length)
|
||||
private static void WriteStringBytes(string name, Span<byte> buffer, int offset, int length)
|
||||
{
|
||||
int i;
|
||||
|
||||
@@ -216,7 +218,7 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteOctalBytes(long value, byte[] buffer, int offset, int length)
|
||||
private static void WriteOctalBytes(long value, Span<byte> buffer, int offset, int length)
|
||||
{
|
||||
string val = Convert.ToString(value, 8);
|
||||
int shift = length - val.Length - 1;
|
||||
@@ -230,19 +232,9 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
}
|
||||
}
|
||||
|
||||
private static int ReadAsciiInt32Base8(byte[] buffer, int offset, int count)
|
||||
private static long ReadAsciiInt64Base8(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
string s = Encoding.UTF8.GetString(buffer, offset, count).TrimNulls();
|
||||
if (string.IsNullOrEmpty(s))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return Convert.ToInt32(s, 8);
|
||||
}
|
||||
|
||||
private static long ReadAsciiInt64Base8(byte[] buffer, int offset, int count)
|
||||
{
|
||||
string s = Encoding.UTF8.GetString(buffer, offset, count).TrimNulls();
|
||||
string s = Encoding.UTF8.GetString(buffer).TrimNulls();
|
||||
if (string.IsNullOrEmpty(s))
|
||||
{
|
||||
return 0;
|
||||
@@ -266,38 +258,20 @@ namespace SharpCompress.Common.Tar.Headers
|
||||
(byte)' ', (byte)' ', (byte)' ', (byte)' '
|
||||
};
|
||||
|
||||
internal static int RecalculateChecksum(byte[] buf)
|
||||
private static int RecalculateChecksum(Memory<byte> buf)
|
||||
{
|
||||
// Set default value for checksum. That is 8 spaces.
|
||||
eightSpaces.CopyTo(buf, 148);
|
||||
eightSpaces.CopyTo(buf.Slice(148));
|
||||
|
||||
// Calculate checksum
|
||||
int headerChecksum = 0;
|
||||
foreach (byte b in buf)
|
||||
foreach (byte b in buf.Span)
|
||||
{
|
||||
headerChecksum += b;
|
||||
}
|
||||
return headerChecksum;
|
||||
}
|
||||
|
||||
internal static int RecalculateAltChecksum(byte[] buf)
|
||||
{
|
||||
eightSpaces.CopyTo(buf, 148);
|
||||
int headerChecksum = 0;
|
||||
foreach (byte b in buf)
|
||||
{
|
||||
if ((b & 0x80) == 0x80)
|
||||
{
|
||||
headerChecksum -= b ^ 0x80;
|
||||
}
|
||||
else
|
||||
{
|
||||
headerChecksum += b;
|
||||
}
|
||||
}
|
||||
return headerChecksum;
|
||||
}
|
||||
|
||||
public long? DataStartPosition { get; set; }
|
||||
|
||||
public string Magic { get; set; }
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -46,10 +48,11 @@ namespace SharpCompress.Common.Tar
|
||||
|
||||
internal override IEnumerable<FilePart> Parts => _filePart.AsEnumerable<FilePart>();
|
||||
|
||||
internal static IEnumerable<TarEntry> GetEntries(StreamingMode mode, Stream stream,
|
||||
CompressionType compressionType, ArchiveEncoding archiveEncoding)
|
||||
internal static async IAsyncEnumerable<TarEntry> GetEntries(StreamingMode mode, Stream stream,
|
||||
CompressionType compressionType, ArchiveEncoding archiveEncoding,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (TarHeader h in TarHeaderFactory.ReadHeader(mode, stream, archiveEncoding))
|
||||
await foreach (TarHeader h in TarHeaderFactory.ReadHeader(mode, stream, archiveEncoding, cancellationToken))
|
||||
{
|
||||
if (h != null)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Common.Tar
|
||||
{
|
||||
@@ -19,14 +20,14 @@ namespace SharpCompress.Common.Tar
|
||||
|
||||
internal override string FilePartName => Header.Name;
|
||||
|
||||
internal override Stream GetCompressedStream()
|
||||
internal override ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_seekableStream != null)
|
||||
{
|
||||
_seekableStream.Position = Header.DataStartPosition!.Value;
|
||||
return new TarReadOnlySubStream(_seekableStream, Header.Size);
|
||||
return new(new TarReadOnlySubStream(_seekableStream, Header.Size));
|
||||
}
|
||||
return Header.PackedStream;
|
||||
return new(Header.PackedStream);
|
||||
}
|
||||
|
||||
internal override Stream? GetRawStream()
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -7,17 +9,17 @@ namespace SharpCompress.Common.Tar
|
||||
{
|
||||
internal static class TarHeaderFactory
|
||||
{
|
||||
internal static IEnumerable<TarHeader?> ReadHeader(StreamingMode mode, Stream stream, ArchiveEncoding archiveEncoding)
|
||||
internal static async IAsyncEnumerable<TarHeader?> ReadHeader(StreamingMode mode, Stream stream, ArchiveEncoding archiveEncoding,
|
||||
[EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
TarHeader? header = null;
|
||||
try
|
||||
{
|
||||
BinaryReader reader = new BinaryReader(stream);
|
||||
header = new TarHeader(archiveEncoding);
|
||||
|
||||
if (!header.Read(reader))
|
||||
if (!await header.Read(stream, cancellationToken))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
@@ -25,10 +27,10 @@ namespace SharpCompress.Common.Tar
|
||||
{
|
||||
case StreamingMode.Seekable:
|
||||
{
|
||||
header.DataStartPosition = reader.BaseStream.Position;
|
||||
header.DataStartPosition = stream.Position;
|
||||
|
||||
//skip to nearest 512
|
||||
reader.BaseStream.Position += PadTo512(header.Size);
|
||||
stream.Position += PadTo512(header.Size);
|
||||
}
|
||||
break;
|
||||
case StreamingMode.Streaming:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using SharpCompress.IO;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Tar
|
||||
{
|
||||
@@ -14,7 +16,7 @@ namespace SharpCompress.Common.Tar
|
||||
BytesLeftToRead = bytesToRead;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_isDisposed)
|
||||
{
|
||||
@@ -23,22 +25,17 @@ namespace SharpCompress.Common.Tar
|
||||
|
||||
_isDisposed = true;
|
||||
|
||||
if (disposing)
|
||||
// Ensure we read all remaining blocks for this entry.
|
||||
await Stream.SkipAsync(BytesLeftToRead);
|
||||
_amountRead += BytesLeftToRead;
|
||||
|
||||
// If the last block wasn't a full 512 bytes, skip the remaining padding bytes.
|
||||
var bytesInLastBlock = _amountRead % 512;
|
||||
|
||||
if (bytesInLastBlock != 0)
|
||||
{
|
||||
// Ensure we read all remaining blocks for this entry.
|
||||
Stream.Skip(BytesLeftToRead);
|
||||
_amountRead += BytesLeftToRead;
|
||||
|
||||
// If the last block wasn't a full 512 bytes, skip the remaining padding bytes.
|
||||
var bytesInLastBlock = _amountRead % 512;
|
||||
|
||||
if (bytesInLastBlock != 0)
|
||||
{
|
||||
Stream.Skip(512 - bytesInLastBlock);
|
||||
}
|
||||
await Stream.SkipAsync(512 - bytesInLastBlock);
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private long BytesLeftToRead { get; set; }
|
||||
@@ -49,22 +46,18 @@ namespace SharpCompress.Common.Tar
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (BytesLeftToRead < count)
|
||||
var count = buffer.Length;
|
||||
if (BytesLeftToRead < buffer.Length)
|
||||
{
|
||||
count = (int)BytesLeftToRead;
|
||||
}
|
||||
int read = Stream.Read(buffer, offset, count);
|
||||
int read = await Stream.ReadAsync(buffer.Slice(0, count), cancellationToken);
|
||||
if (read > 0)
|
||||
{
|
||||
BytesLeftToRead -= read;
|
||||
@@ -73,20 +66,9 @@ namespace SharpCompress.Common.Tar
|
||||
return read;
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (BytesLeftToRead <= 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
int value = Stream.ReadByte();
|
||||
if (value != -1)
|
||||
{
|
||||
--BytesLeftToRead;
|
||||
++_amountRead;
|
||||
}
|
||||
return value;
|
||||
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
@@ -98,10 +80,5 @@ namespace SharpCompress.Common.Tar
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
using SharpCompress.Readers;
|
||||
|
||||
@@ -33,19 +33,10 @@ namespace SharpCompress.Common
|
||||
/// RarArchive is part of a multi-part archive.
|
||||
/// </summary>
|
||||
public virtual bool IsMultiVolume => true;
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_actualStream.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
return _actualStream.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -9,29 +11,29 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override async ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
VolumeNumber = reader.ReadUInt16();
|
||||
FirstVolumeWithDirectory = reader.ReadUInt16();
|
||||
TotalNumberOfEntriesInDisk = reader.ReadUInt16();
|
||||
TotalNumberOfEntries = reader.ReadUInt16();
|
||||
DirectorySize = reader.ReadUInt32();
|
||||
DirectoryStartOffsetRelativeToDisk = reader.ReadUInt32();
|
||||
CommentLength = reader.ReadUInt16();
|
||||
Comment = reader.ReadBytes(CommentLength);
|
||||
VolumeNumber = await stream.ReadUInt16(cancellationToken);
|
||||
FirstVolumeWithDirectory = await stream.ReadUInt16(cancellationToken);
|
||||
TotalNumberOfEntriesInDisk = await stream.ReadUInt16(cancellationToken);
|
||||
TotalNumberOfEntries = await stream.ReadUInt16(cancellationToken);
|
||||
DirectorySize = await stream.ReadUInt32(cancellationToken);
|
||||
DirectoryStartOffsetRelativeToDisk = await stream.ReadUInt32(cancellationToken);
|
||||
CommentLength = await stream.ReadUInt16(cancellationToken);
|
||||
Comment = await stream.ReadBytes(CommentLength ?? 0, cancellationToken);
|
||||
}
|
||||
|
||||
public ushort VolumeNumber { get; private set; }
|
||||
public ushort? VolumeNumber { get; private set; }
|
||||
|
||||
public ushort FirstVolumeWithDirectory { get; private set; }
|
||||
public ushort? FirstVolumeWithDirectory { get; private set; }
|
||||
|
||||
public ushort TotalNumberOfEntriesInDisk { get; private set; }
|
||||
public ushort? TotalNumberOfEntriesInDisk { get; private set; }
|
||||
|
||||
public uint DirectorySize { get; private set; }
|
||||
public uint? DirectorySize { get; private set; }
|
||||
|
||||
public uint DirectoryStartOffsetRelativeToDisk { get; private set; }
|
||||
public uint? DirectoryStartOffsetRelativeToDisk { get; private set; }
|
||||
|
||||
public ushort CommentLength { get; private set; }
|
||||
public ushort? CommentLength { get; private set; }
|
||||
|
||||
public byte[]? Comment { get; private set; }
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -10,28 +12,28 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override async ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
Version = reader.ReadUInt16();
|
||||
VersionNeededToExtract = reader.ReadUInt16();
|
||||
Flags = (HeaderFlags)reader.ReadUInt16();
|
||||
CompressionMethod = (ZipCompressionMethod)reader.ReadUInt16();
|
||||
LastModifiedTime = reader.ReadUInt16();
|
||||
LastModifiedDate = reader.ReadUInt16();
|
||||
Crc = reader.ReadUInt32();
|
||||
CompressedSize = reader.ReadUInt32();
|
||||
UncompressedSize = reader.ReadUInt32();
|
||||
ushort nameLength = reader.ReadUInt16();
|
||||
ushort extraLength = reader.ReadUInt16();
|
||||
ushort commentLength = reader.ReadUInt16();
|
||||
DiskNumberStart = reader.ReadUInt16();
|
||||
InternalFileAttributes = reader.ReadUInt16();
|
||||
ExternalFileAttributes = reader.ReadUInt32();
|
||||
RelativeOffsetOfEntryHeader = reader.ReadUInt32();
|
||||
Version = await stream.ReadUInt16(cancellationToken);
|
||||
VersionNeededToExtract = await stream.ReadUInt16(cancellationToken);
|
||||
Flags = (HeaderFlags)await stream.ReadUInt16(cancellationToken);
|
||||
CompressionMethod = (ZipCompressionMethod)await stream.ReadUInt16(cancellationToken);
|
||||
LastModifiedTime = await stream.ReadUInt16(cancellationToken);
|
||||
LastModifiedDate = await stream.ReadUInt16(cancellationToken);
|
||||
Crc = await stream.ReadUInt32(cancellationToken);
|
||||
CompressedSize = await stream.ReadUInt32(cancellationToken);
|
||||
UncompressedSize = await stream.ReadUInt32(cancellationToken);
|
||||
ushort nameLength = await stream.ReadUInt16(cancellationToken);
|
||||
ushort extraLength = await stream.ReadUInt16(cancellationToken);
|
||||
ushort commentLength = await stream.ReadUInt16(cancellationToken);
|
||||
DiskNumberStart = await stream.ReadUInt16(cancellationToken);
|
||||
InternalFileAttributes = await stream.ReadUInt16(cancellationToken);
|
||||
ExternalFileAttributes = await stream.ReadUInt32(cancellationToken);
|
||||
RelativeOffsetOfEntryHeader = await stream.ReadUInt32(cancellationToken);
|
||||
|
||||
byte[] name = reader.ReadBytes(nameLength);
|
||||
byte[] extra = reader.ReadBytes(extraLength);
|
||||
byte[] comment = reader.ReadBytes(commentLength);
|
||||
byte[] name = await stream.ReadBytes(nameLength, cancellationToken);
|
||||
byte[] extra = await stream.ReadBytes(extraLength, cancellationToken);
|
||||
byte[] comment = await stream.ReadBytes(commentLength, cancellationToken);
|
||||
|
||||
// According to .ZIP File Format Specification
|
||||
//
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -9,8 +11,9 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return new();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -10,20 +12,20 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override async ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
Version = reader.ReadUInt16();
|
||||
Flags = (HeaderFlags)reader.ReadUInt16();
|
||||
CompressionMethod = (ZipCompressionMethod)reader.ReadUInt16();
|
||||
LastModifiedTime = reader.ReadUInt16();
|
||||
LastModifiedDate = reader.ReadUInt16();
|
||||
Crc = reader.ReadUInt32();
|
||||
CompressedSize = reader.ReadUInt32();
|
||||
UncompressedSize = reader.ReadUInt32();
|
||||
ushort nameLength = reader.ReadUInt16();
|
||||
ushort extraLength = reader.ReadUInt16();
|
||||
byte[] name = reader.ReadBytes(nameLength);
|
||||
byte[] extra = reader.ReadBytes(extraLength);
|
||||
Version = await stream.ReadUInt16(cancellationToken);
|
||||
Flags = (HeaderFlags)await stream.ReadUInt16(cancellationToken);
|
||||
CompressionMethod = (ZipCompressionMethod)await stream.ReadUInt16(cancellationToken);
|
||||
LastModifiedTime = await stream.ReadUInt16(cancellationToken);
|
||||
LastModifiedDate = await stream.ReadUInt16(cancellationToken);
|
||||
Crc = await stream.ReadUInt32(cancellationToken);
|
||||
CompressedSize = await stream.ReadUInt32(cancellationToken);
|
||||
UncompressedSize = await stream.ReadUInt32(cancellationToken);
|
||||
ushort nameLength = await stream.ReadUInt16(cancellationToken);
|
||||
ushort extraLength = await stream.ReadUInt16(cancellationToken);
|
||||
byte[] name = await stream.ReadBytes(nameLength, cancellationToken);
|
||||
byte[] extra = await stream.ReadBytes(extraLength, cancellationToken);
|
||||
|
||||
// According to .ZIP File Format Specification
|
||||
//
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -10,7 +12,7 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -9,18 +11,18 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override async ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
SizeOfDirectoryEndRecord = (long)reader.ReadUInt64();
|
||||
VersionMadeBy = reader.ReadUInt16();
|
||||
VersionNeededToExtract = reader.ReadUInt16();
|
||||
VolumeNumber = reader.ReadUInt32();
|
||||
FirstVolumeWithDirectory = reader.ReadUInt32();
|
||||
TotalNumberOfEntriesInDisk = (long)reader.ReadUInt64();
|
||||
TotalNumberOfEntries = (long)reader.ReadUInt64();
|
||||
DirectorySize = (long)reader.ReadUInt64();
|
||||
DirectoryStartOffsetRelativeToDisk = (long)reader.ReadUInt64();
|
||||
DataSector = reader.ReadBytes((int)(SizeOfDirectoryEndRecord - SIZE_OF_FIXED_HEADER_DATA_EXCEPT_SIGNATURE_AND_SIZE_FIELDS));
|
||||
SizeOfDirectoryEndRecord = (long)await stream.ReadUInt64(cancellationToken);
|
||||
VersionMadeBy = await stream.ReadUInt16(cancellationToken);
|
||||
VersionNeededToExtract = await stream.ReadUInt16(cancellationToken);
|
||||
VolumeNumber = await stream.ReadUInt32(cancellationToken);
|
||||
FirstVolumeWithDirectory = await stream.ReadUInt32(cancellationToken);
|
||||
TotalNumberOfEntriesInDisk = (long)await stream.ReadUInt64(cancellationToken);
|
||||
TotalNumberOfEntries = (long)await stream.ReadUInt64(cancellationToken);
|
||||
DirectorySize = (long)await stream.ReadUInt64(cancellationToken);
|
||||
DirectoryStartOffsetRelativeToDisk = (long)await stream.ReadUInt64(cancellationToken);
|
||||
DataSector = await stream.ReadBytes((int)(SizeOfDirectoryEndRecord - SIZE_OF_FIXED_HEADER_DATA_EXCEPT_SIGNATURE_AND_SIZE_FIELDS), cancellationToken);
|
||||
}
|
||||
|
||||
private const int SIZE_OF_FIXED_HEADER_DATA_EXCEPT_SIGNATURE_AND_SIZE_FIELDS = 44;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -9,11 +11,11 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
}
|
||||
|
||||
internal override void Read(BinaryReader reader)
|
||||
internal override async ValueTask Read(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
FirstVolumeWithDirectory = reader.ReadUInt32();
|
||||
RelativeOffsetOfTheEndOfDirectoryRecord = (long)reader.ReadUInt64();
|
||||
TotalNumberOfVolumes = reader.ReadUInt32();
|
||||
FirstVolumeWithDirectory = await stream.ReadUInt32(cancellationToken);
|
||||
RelativeOffsetOfTheEndOfDirectoryRecord = (long)await stream.ReadUInt64(cancellationToken);
|
||||
TotalNumberOfVolumes = await stream.ReadUInt32(cancellationToken);
|
||||
}
|
||||
|
||||
public uint FirstVolumeWithDirectory { get; private set; }
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Common.Zip.Headers
|
||||
{
|
||||
@@ -12,7 +14,7 @@ namespace SharpCompress.Common.Zip.Headers
|
||||
|
||||
internal ZipHeaderType ZipHeaderType { get; }
|
||||
|
||||
internal abstract void Read(BinaryReader reader);
|
||||
internal abstract ValueTask Read(Stream stream, CancellationToken cancellationToken);
|
||||
|
||||
internal bool HasData { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -17,22 +19,22 @@ namespace SharpCompress.Common.Zip
|
||||
_directoryEntryHeader = header;
|
||||
}
|
||||
|
||||
internal override Stream GetCompressedStream()
|
||||
internal override async ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_isLocalHeaderLoaded)
|
||||
{
|
||||
LoadLocalHeader();
|
||||
await LoadLocalHeader(cancellationToken);
|
||||
_isLocalHeaderLoaded = true;
|
||||
}
|
||||
return base.GetCompressedStream();
|
||||
return await base.GetCompressedStreamAsync(cancellationToken);
|
||||
}
|
||||
|
||||
internal string? Comment => ((DirectoryEntryHeader)Header).Comment;
|
||||
|
||||
private void LoadLocalHeader()
|
||||
private async ValueTask LoadLocalHeader(CancellationToken cancellationToken)
|
||||
{
|
||||
bool hasData = Header.HasData;
|
||||
Header = _headerFactory.GetLocalHeader(BaseStream, ((DirectoryEntryHeader)Header));
|
||||
Header = await _headerFactory.GetLocalHeader(BaseStream, (DirectoryEntryHeader)Header, cancellationToken);
|
||||
Header.HasData = hasData;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.Compressors.Xz;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Common.Zip
|
||||
@@ -19,15 +24,13 @@ namespace SharpCompress.Common.Zip
|
||||
{
|
||||
}
|
||||
|
||||
internal IEnumerable<ZipHeader> ReadSeekableHeader(Stream stream)
|
||||
internal async IAsyncEnumerable<ZipHeader> ReadSeekableHeader(Stream stream, [EnumeratorCancellation]CancellationToken cancellationToken)
|
||||
{
|
||||
var reader = new BinaryReader(stream);
|
||||
|
||||
SeekBackToHeader(stream, reader);
|
||||
await SeekBackToHeaderAsync(stream);
|
||||
|
||||
var eocd_location = stream.Position;
|
||||
var entry = new DirectoryEndHeader();
|
||||
entry.Read(reader);
|
||||
await entry.Read(stream, cancellationToken);
|
||||
|
||||
if (entry.IsZip64)
|
||||
{
|
||||
@@ -35,37 +38,37 @@ namespace SharpCompress.Common.Zip
|
||||
|
||||
// ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR should be before the EOCD
|
||||
stream.Seek(eocd_location - ZIP64_EOCD_LENGTH - 4, SeekOrigin.Begin);
|
||||
uint zip64_locator = reader.ReadUInt32();
|
||||
uint zip64_locator = await stream.ReadUInt32(cancellationToken);
|
||||
if( zip64_locator != ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR )
|
||||
{
|
||||
throw new ArchiveException("Failed to locate the Zip64 Directory Locator");
|
||||
}
|
||||
|
||||
var zip64Locator = new Zip64DirectoryEndLocatorHeader();
|
||||
zip64Locator.Read(reader);
|
||||
await zip64Locator.Read(stream, cancellationToken);
|
||||
|
||||
stream.Seek(zip64Locator.RelativeOffsetOfTheEndOfDirectoryRecord, SeekOrigin.Begin);
|
||||
uint zip64Signature = reader.ReadUInt32();
|
||||
uint zip64Signature = await stream.ReadUInt32(cancellationToken);
|
||||
if (zip64Signature != ZIP64_END_OF_CENTRAL_DIRECTORY)
|
||||
{
|
||||
throw new ArchiveException("Failed to locate the Zip64 Header");
|
||||
}
|
||||
|
||||
var zip64Entry = new Zip64DirectoryEndHeader();
|
||||
zip64Entry.Read(reader);
|
||||
await zip64Entry.Read(stream, cancellationToken);
|
||||
stream.Seek(zip64Entry.DirectoryStartOffsetRelativeToDisk, SeekOrigin.Begin);
|
||||
}
|
||||
else
|
||||
{
|
||||
stream.Seek(entry.DirectoryStartOffsetRelativeToDisk, SeekOrigin.Begin);
|
||||
stream.Seek(entry.DirectoryStartOffsetRelativeToDisk ?? 0, SeekOrigin.Begin);
|
||||
}
|
||||
|
||||
long position = stream.Position;
|
||||
while (true)
|
||||
{
|
||||
stream.Position = position;
|
||||
uint signature = reader.ReadUInt32();
|
||||
var nextHeader = ReadHeader(signature, reader, _zip64);
|
||||
uint signature = await stream.ReadUInt32(cancellationToken);
|
||||
var nextHeader = await ReadHeader(signature, stream, cancellationToken, _zip64);
|
||||
position = stream.Position;
|
||||
|
||||
if (nextHeader is null)
|
||||
@@ -86,7 +89,7 @@ namespace SharpCompress.Common.Zip
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsMatch( byte[] haystack, int position, byte[] needle)
|
||||
private static bool IsMatch (Span<byte> haystack, int position, byte[] needle)
|
||||
{
|
||||
for( int i = 0; i < needle.Length; i++ )
|
||||
{
|
||||
@@ -98,7 +101,7 @@ namespace SharpCompress.Common.Zip
|
||||
|
||||
return true;
|
||||
}
|
||||
private static void SeekBackToHeader(Stream stream, BinaryReader reader)
|
||||
private static async ValueTask SeekBackToHeaderAsync(Stream stream)
|
||||
{
|
||||
// Minimum EOCD length
|
||||
if (stream.Length < MINIMUM_EOCD_LENGTH)
|
||||
@@ -112,16 +115,18 @@ namespace SharpCompress.Common.Zip
|
||||
|
||||
stream.Seek(-len, SeekOrigin.End);
|
||||
|
||||
byte[] seek = reader.ReadBytes(len);
|
||||
using var rented = MemoryPool<byte>.Shared.Rent(len);
|
||||
var buffer = rented.Memory.Slice(0, len);
|
||||
await stream.ReadAsync(buffer);
|
||||
|
||||
// Search in reverse
|
||||
Array.Reverse(seek);
|
||||
buffer.Span.Reverse();
|
||||
|
||||
var max_search_area = len - MINIMUM_EOCD_LENGTH;
|
||||
|
||||
for( int pos_from_end = 0; pos_from_end < max_search_area; ++pos_from_end)
|
||||
{
|
||||
if( IsMatch(seek, pos_from_end, needle) )
|
||||
if( IsMatch( buffer.Span, pos_from_end, needle) )
|
||||
{
|
||||
stream.Seek(-pos_from_end, SeekOrigin.End);
|
||||
return;
|
||||
@@ -131,12 +136,11 @@ namespace SharpCompress.Common.Zip
|
||||
throw new ArchiveException("Failed to locate the Zip Header");
|
||||
}
|
||||
|
||||
internal LocalEntryHeader GetLocalHeader(Stream stream, DirectoryEntryHeader directoryEntryHeader)
|
||||
internal async ValueTask<LocalEntryHeader> GetLocalHeader(Stream stream, DirectoryEntryHeader directoryEntryHeader, CancellationToken cancellationToken)
|
||||
{
|
||||
stream.Seek(directoryEntryHeader.RelativeOffsetOfEntryHeader, SeekOrigin.Begin);
|
||||
BinaryReader reader = new BinaryReader(stream);
|
||||
uint signature = reader.ReadUInt32();
|
||||
var localEntryHeader = ReadHeader(signature, reader, _zip64) as LocalEntryHeader;
|
||||
uint signature = await stream.ReadUInt32(cancellationToken);
|
||||
var localEntryHeader = await ReadHeader(signature, stream, cancellationToken, _zip64) as LocalEntryHeader;
|
||||
if (localEntryHeader is null)
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
using SharpCompress.IO;
|
||||
@@ -19,13 +21,13 @@ namespace SharpCompress.Common.Zip
|
||||
return Header.PackedStream;
|
||||
}
|
||||
|
||||
internal override Stream GetCompressedStream()
|
||||
internal override async ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Header.HasData)
|
||||
{
|
||||
return Stream.Null;
|
||||
}
|
||||
_decompressionStream = CreateDecompressionStream(GetCryptoStream(CreateBaseStream()), Header.CompressionMethod);
|
||||
_decompressionStream = await CreateDecompressionStream(GetCryptoStream(CreateBaseStream()), Header.CompressionMethod, cancellationToken);
|
||||
if (LeaveStreamOpen)
|
||||
{
|
||||
return new NonDisposingStream(_decompressionStream);
|
||||
@@ -33,17 +35,17 @@ namespace SharpCompress.Common.Zip
|
||||
return _decompressionStream;
|
||||
}
|
||||
|
||||
internal BinaryReader FixStreamedFileLocation(ref RewindableStream rewindableStream)
|
||||
internal async ValueTask FixStreamedFileLocation(RewindableStream rewindableStream, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Header.IsDirectory)
|
||||
{
|
||||
return new BinaryReader(rewindableStream);
|
||||
return;
|
||||
}
|
||||
if (Header.HasData && !Skipped)
|
||||
{
|
||||
_decompressionStream ??= GetCompressedStream();
|
||||
_decompressionStream ??= await GetCompressedStreamAsync(cancellationToken);
|
||||
|
||||
_decompressionStream.Skip();
|
||||
await _decompressionStream.SkipAsync(cancellationToken);
|
||||
|
||||
if (_decompressionStream is DeflateStream deflateStream)
|
||||
{
|
||||
@@ -51,9 +53,7 @@ namespace SharpCompress.Common.Zip
|
||||
}
|
||||
Skipped = true;
|
||||
}
|
||||
var reader = new BinaryReader(rewindableStream);
|
||||
_decompressionStream = null;
|
||||
return reader;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -12,43 +13,36 @@ namespace SharpCompress.Common.Zip
|
||||
{
|
||||
}
|
||||
|
||||
internal IEnumerable<ZipHeader> ReadStreamHeader(Stream stream)
|
||||
internal async IAsyncEnumerable<ZipHeader> ReadStreamHeader(RewindableStream rewindableStream, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
RewindableStream rewindableStream;
|
||||
|
||||
if (stream is RewindableStream rs)
|
||||
{
|
||||
rewindableStream = rs;
|
||||
}
|
||||
else
|
||||
{
|
||||
rewindableStream = new RewindableStream(stream);
|
||||
}
|
||||
while (true)
|
||||
{
|
||||
ZipHeader? header;
|
||||
BinaryReader reader = new BinaryReader(rewindableStream);
|
||||
if (_lastEntryHeader != null &&
|
||||
(FlagUtility.HasFlag(_lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor) || _lastEntryHeader.IsZip64))
|
||||
{
|
||||
reader = ((StreamingZipFilePart)_lastEntryHeader.Part).FixStreamedFileLocation(ref rewindableStream);
|
||||
await ((StreamingZipFilePart)_lastEntryHeader.Part).FixStreamedFileLocation(rewindableStream, cancellationToken);
|
||||
long? pos = rewindableStream.CanSeek ? (long?)rewindableStream.Position : null;
|
||||
uint crc = reader.ReadUInt32();
|
||||
uint crc = await rewindableStream.ReadUInt32(cancellationToken);
|
||||
if (crc == POST_DATA_DESCRIPTOR)
|
||||
{
|
||||
crc = reader.ReadUInt32();
|
||||
crc = await rewindableStream.ReadUInt32(cancellationToken);
|
||||
}
|
||||
_lastEntryHeader.Crc = crc;
|
||||
_lastEntryHeader.CompressedSize = reader.ReadUInt32();
|
||||
_lastEntryHeader.UncompressedSize = reader.ReadUInt32();
|
||||
_lastEntryHeader.CompressedSize = await rewindableStream.ReadUInt32(cancellationToken);
|
||||
_lastEntryHeader.UncompressedSize = await rewindableStream.ReadUInt32(cancellationToken);
|
||||
if (pos.HasValue)
|
||||
{
|
||||
_lastEntryHeader.DataStartPosition = pos - _lastEntryHeader.CompressedSize;
|
||||
}
|
||||
}
|
||||
_lastEntryHeader = null;
|
||||
uint headerBytes = reader.ReadUInt32();
|
||||
header = ReadHeader(headerBytes, reader);
|
||||
var headerBytes = await rewindableStream.ReadUInt32OrNull(cancellationToken);
|
||||
if (headerBytes is null)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
header = await ReadHeader(headerBytes.Value, rewindableStream, cancellationToken);
|
||||
if (header is null)
|
||||
{
|
||||
yield break;
|
||||
@@ -71,10 +65,10 @@ namespace SharpCompress.Common.Zip
|
||||
{
|
||||
rewindableStream.StartRecording();
|
||||
}
|
||||
uint nextHeaderBytes = reader.ReadUInt32();
|
||||
uint nextHeaderBytes = await rewindableStream.ReadUInt32(cancellationToken);
|
||||
|
||||
// Check if next data is PostDataDescriptor, streamed file with 0 length
|
||||
header.HasData = !IsHeader(nextHeaderBytes);
|
||||
header.HasData = nextHeaderBytes != POST_DATA_DESCRIPTOR;
|
||||
rewindableStream.Rewind(!isRecording);
|
||||
}
|
||||
else // We are not streaming and compressed size is 0, we have no data
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.Compressors;
|
||||
using SharpCompress.Compressors.BZip2;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
using SharpCompress.Compressors.Deflate64;
|
||||
using SharpCompress.Compressors.LZMA;
|
||||
using SharpCompress.Compressors.PPMd;
|
||||
//using SharpCompress.Compressors.PPMd;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Common.Zip
|
||||
@@ -28,13 +30,13 @@ namespace SharpCompress.Common.Zip
|
||||
|
||||
internal override string FilePartName => Header.Name;
|
||||
|
||||
internal override Stream GetCompressedStream()
|
||||
internal override async ValueTask<Stream> GetCompressedStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Header.HasData)
|
||||
{
|
||||
return Stream.Null;
|
||||
}
|
||||
Stream decompressionStream = CreateDecompressionStream(GetCryptoStream(CreateBaseStream()), Header.CompressionMethod);
|
||||
Stream decompressionStream = await CreateDecompressionStream(GetCryptoStream(CreateBaseStream()), Header.CompressionMethod, cancellationToken);
|
||||
if (LeaveStreamOpen)
|
||||
{
|
||||
return new NonDisposingStream(decompressionStream);
|
||||
@@ -55,7 +57,7 @@ namespace SharpCompress.Common.Zip
|
||||
|
||||
protected bool LeaveStreamOpen => FlagUtility.HasFlag(Header.Flags, HeaderFlags.UsePostDataDescriptor) || Header.IsZip64;
|
||||
|
||||
protected Stream CreateDecompressionStream(Stream stream, ZipCompressionMethod method)
|
||||
protected async ValueTask<Stream> CreateDecompressionStream(Stream stream, ZipCompressionMethod method, CancellationToken cancellationToken)
|
||||
{
|
||||
switch (method)
|
||||
{
|
||||
@@ -73,30 +75,29 @@ namespace SharpCompress.Common.Zip
|
||||
}
|
||||
case ZipCompressionMethod.BZip2:
|
||||
{
|
||||
return new BZip2Stream(stream, CompressionMode.Decompress, false);
|
||||
}
|
||||
return await BZip2Stream.CreateAsync(stream, CompressionMode.Decompress, false, cancellationToken);
|
||||
}
|
||||
case ZipCompressionMethod.LZMA:
|
||||
{
|
||||
if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted))
|
||||
{
|
||||
throw new NotSupportedException("LZMA with pkware encryption.");
|
||||
}
|
||||
var reader = new BinaryReader(stream);
|
||||
reader.ReadUInt16(); //LZMA version
|
||||
var props = new byte[reader.ReadUInt16()];
|
||||
reader.Read(props, 0, props.Length);
|
||||
return new LzmaStream(props, stream,
|
||||
await stream.ReadUInt16(cancellationToken); //LZMA version
|
||||
var props = new byte[await stream.ReadUInt16(cancellationToken)];
|
||||
await stream.ReadAsync(props, 0, props.Length, cancellationToken);
|
||||
return await LzmaStream.CreateAsync(props, stream,
|
||||
Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1,
|
||||
FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1)
|
||||
? -1
|
||||
: (long)Header.UncompressedSize);
|
||||
: (long)Header.UncompressedSize,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
case ZipCompressionMethod.PPMd:
|
||||
{
|
||||
Span<byte> props = stackalloc byte[2];
|
||||
stream.ReadFully(props);
|
||||
/* case ZipCompressionMethod.PPMd:
|
||||
{
|
||||
var props = await stream.ReadBytes(2, cancellationToken);
|
||||
return new PpmdStream(new PpmdProperties(props), stream, false);
|
||||
}
|
||||
} */
|
||||
case ZipCompressionMethod.WinzipAes:
|
||||
{
|
||||
ExtraData? data = Header.Extra.SingleOrDefault(x => x.Type == ExtraDataType.WinZipAes);
|
||||
@@ -120,7 +121,7 @@ namespace SharpCompress.Common.Zip
|
||||
{
|
||||
throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata");
|
||||
}
|
||||
return CreateDecompressionStream(stream, (ZipCompressionMethod)BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes.AsSpan(5)));
|
||||
return await CreateDecompressionStream(stream, (ZipCompressionMethod)BinaryPrimitives.ReadUInt16LittleEndian(data.DataBytes.AsSpan(5)), cancellationToken);
|
||||
}
|
||||
default:
|
||||
{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -30,15 +32,15 @@ namespace SharpCompress.Common.Zip
|
||||
this._archiveEncoding = archiveEncoding;
|
||||
}
|
||||
|
||||
protected ZipHeader? ReadHeader(uint headerBytes, BinaryReader reader, bool zip64 = false)
|
||||
protected async ValueTask<ZipHeader?> ReadHeader(uint headerBytes, Stream stream, CancellationToken cancellationToken, bool zip64 = false)
|
||||
{
|
||||
switch (headerBytes)
|
||||
{
|
||||
case ENTRY_HEADER_BYTES:
|
||||
{
|
||||
var entryHeader = new LocalEntryHeader(_archiveEncoding);
|
||||
entryHeader.Read(reader);
|
||||
LoadHeader(entryHeader, reader.BaseStream);
|
||||
await entryHeader.Read(stream, cancellationToken);
|
||||
await LoadHeader(entryHeader, stream, cancellationToken);
|
||||
|
||||
_lastEntryHeader = entryHeader;
|
||||
return entryHeader;
|
||||
@@ -46,20 +48,20 @@ namespace SharpCompress.Common.Zip
|
||||
case DIRECTORY_START_HEADER_BYTES:
|
||||
{
|
||||
var entry = new DirectoryEntryHeader(_archiveEncoding);
|
||||
entry.Read(reader);
|
||||
await entry.Read(stream, cancellationToken);
|
||||
return entry;
|
||||
}
|
||||
case POST_DATA_DESCRIPTOR:
|
||||
{
|
||||
if (FlagUtility.HasFlag(_lastEntryHeader!.Flags, HeaderFlags.UsePostDataDescriptor))
|
||||
{
|
||||
_lastEntryHeader.Crc = reader.ReadUInt32();
|
||||
_lastEntryHeader.CompressedSize = zip64 ? (long)reader.ReadUInt64() : reader.ReadUInt32();
|
||||
_lastEntryHeader.UncompressedSize = zip64 ? (long)reader.ReadUInt64() : reader.ReadUInt32();
|
||||
_lastEntryHeader.Crc = await stream.ReadUInt32(cancellationToken);
|
||||
_lastEntryHeader.CompressedSize = zip64 ? (long)await stream.ReadUInt64(cancellationToken) : await stream.ReadUInt32(cancellationToken);
|
||||
_lastEntryHeader.UncompressedSize = zip64 ? (long)await stream.ReadUInt64(cancellationToken) : await stream.ReadUInt32(cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.ReadBytes(zip64 ? 20 : 12);
|
||||
await stream.ReadBytes(zip64 ? 20 : 12, cancellationToken);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -68,7 +70,7 @@ namespace SharpCompress.Common.Zip
|
||||
case DIRECTORY_END_HEADER_BYTES:
|
||||
{
|
||||
var entry = new DirectoryEndHeader();
|
||||
entry.Read(reader);
|
||||
await entry.Read(stream, cancellationToken);
|
||||
return entry;
|
||||
}
|
||||
case SPLIT_ARCHIVE_HEADER_BYTES:
|
||||
@@ -78,13 +80,13 @@ namespace SharpCompress.Common.Zip
|
||||
case ZIP64_END_OF_CENTRAL_DIRECTORY:
|
||||
{
|
||||
var entry = new Zip64DirectoryEndHeader();
|
||||
entry.Read(reader);
|
||||
await entry.Read(stream, cancellationToken);
|
||||
return entry;
|
||||
}
|
||||
case ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR:
|
||||
{
|
||||
var entry = new Zip64DirectoryEndLocatorHeader();
|
||||
entry.Read(reader);
|
||||
await entry.Read(stream, cancellationToken);
|
||||
return entry;
|
||||
}
|
||||
default:
|
||||
@@ -110,7 +112,7 @@ namespace SharpCompress.Common.Zip
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadHeader(ZipFileEntry entryHeader, Stream stream)
|
||||
private async ValueTask LoadHeader(ZipFileEntry entryHeader, Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
if (FlagUtility.HasFlag(entryHeader.Flags, HeaderFlags.Encrypted))
|
||||
{
|
||||
@@ -134,10 +136,8 @@ namespace SharpCompress.Common.Zip
|
||||
{
|
||||
var keySize = (WinzipAesKeySize)data.DataBytes[4];
|
||||
|
||||
var salt = new byte[WinzipAesEncryptionData.KeyLengthInBytes(keySize) / 2];
|
||||
var passwordVerifyValue = new byte[2];
|
||||
stream.Read(salt, 0, salt.Length);
|
||||
stream.Read(passwordVerifyValue, 0, 2);
|
||||
var salt = await stream.ReadBytes(WinzipAesEncryptionData.KeyLengthInBytes(keySize) / 2, cancellationToken);
|
||||
var passwordVerifyValue = await stream.ReadBytes(2, cancellationToken);
|
||||
entryHeader.WinzipAesEncryptionData =
|
||||
new WinzipAesEncryptionData(keySize, salt, passwordVerifyValue, _password);
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.BZip2
|
||||
{
|
||||
public sealed class BZip2Stream : Stream
|
||||
public sealed class BZip2Stream : AsyncStream
|
||||
{
|
||||
private readonly Stream stream;
|
||||
private bool isDisposed;
|
||||
@@ -33,17 +37,14 @@ namespace SharpCompress.Compressors.BZip2
|
||||
(stream as CBZip2OutputStream)?.Finish();
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (isDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
isDisposed = true;
|
||||
if (disposing)
|
||||
{
|
||||
stream.Dispose();
|
||||
}
|
||||
await stream.DisposeAsync();
|
||||
}
|
||||
|
||||
public CompressionMode Mode { get; }
|
||||
@@ -54,23 +55,18 @@ namespace SharpCompress.Compressors.BZip2
|
||||
|
||||
public override bool CanWrite => stream.CanWrite;
|
||||
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
stream.Flush();
|
||||
return stream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override long Length => stream.Length;
|
||||
|
||||
public override long Position { get => stream.Position; set => stream.Position = value; }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return stream.Read(buffer, offset, count);
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
{
|
||||
return stream.ReadByte();
|
||||
return stream.ReadAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
@@ -83,28 +79,14 @@ namespace SharpCompress.Compressors.BZip2
|
||||
stream.SetLength(value);
|
||||
}
|
||||
|
||||
#if !NET461 && !NETSTANDARD2_0
|
||||
|
||||
public override int Read(Span<byte> buffer)
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return stream.Read(buffer);
|
||||
return stream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
stream.Write(buffer);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
stream.Write(buffer, offset, count);
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
stream.WriteByte(value);
|
||||
return stream.WriteAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,11 +94,12 @@ namespace SharpCompress.Compressors.BZip2
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsBZip2(Stream stream)
|
||||
public static async ValueTask<bool> IsBZip2Async(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
BinaryReader br = new BinaryReader(stream);
|
||||
byte[] chars = br.ReadBytes(2);
|
||||
if (chars.Length < 2 || chars[0] != 'B' || chars[1] != 'Z')
|
||||
using var rented = MemoryPool<byte>.Shared.Rent(2);
|
||||
var chars = rented.Memory.Slice(0, 2);
|
||||
await stream.ReadAsync(chars, cancellationToken);
|
||||
if (chars.Length < 2 || chars.Span[0] != 'B' || chars.Span[1] != 'Z')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -27,10 +27,13 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
public class DeflateStream : Stream
|
||||
public class DeflateStream : AsyncStream
|
||||
{
|
||||
private readonly ZlibBaseStream _baseStream;
|
||||
private bool _disposed;
|
||||
@@ -216,35 +219,25 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <remarks>
|
||||
/// This may or may not result in a <c>Close()</c> call on the captive stream.
|
||||
/// </remarks>
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
if (!_disposed)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_baseStream?.Dispose();
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
await _baseStream.DisposeAsync();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flush the stream.
|
||||
/// </summary>
|
||||
public override void Flush()
|
||||
public override async Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("DeflateStream");
|
||||
}
|
||||
_baseStream.Flush();
|
||||
await _baseStream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -273,24 +266,14 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <param name="offset">the offset within that data array to put the first byte read.</param>
|
||||
/// <param name="count">the number of bytes to read.</param>
|
||||
/// <returns>the number of bytes actually read</returns>
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("DeflateStream");
|
||||
}
|
||||
return _baseStream.Read(buffer, offset, count);
|
||||
return await _baseStream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("DeflateStream");
|
||||
}
|
||||
return _baseStream.ReadByte();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calling this method always throws a <see cref="NotImplementedException"/>.
|
||||
/// </summary>
|
||||
@@ -340,22 +323,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <param name="buffer">The buffer holding data to write to the stream.</param>
|
||||
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
|
||||
/// <param name="count">the number of bytes to write.</param>
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("DeflateStream");
|
||||
}
|
||||
_baseStream.Write(buffer, offset, count);
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("DeflateStream");
|
||||
}
|
||||
_baseStream.WriteByte(value);
|
||||
await _baseStream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -27,21 +27,25 @@
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
public class GZipStream : Stream
|
||||
public class GZipStream : AsyncStream
|
||||
{
|
||||
internal static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private string? _comment;
|
||||
private string? _fileName;
|
||||
private DateTime? _lastModified;
|
||||
|
||||
internal ZlibBaseStream BaseStream;
|
||||
private readonly ZlibBaseStream _baseStream;
|
||||
private bool _disposed;
|
||||
private bool _firstReadDone;
|
||||
private int _headerByteCount;
|
||||
@@ -60,7 +64,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
|
||||
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, Encoding encoding)
|
||||
{
|
||||
BaseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, encoding);
|
||||
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, encoding);
|
||||
_encoding = encoding;
|
||||
}
|
||||
|
||||
@@ -68,27 +72,27 @@ namespace SharpCompress.Compressors.Deflate
|
||||
|
||||
public virtual FlushType FlushMode
|
||||
{
|
||||
get => (BaseStream._flushMode);
|
||||
get => (_baseStream._flushMode);
|
||||
set
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
BaseStream._flushMode = value;
|
||||
_baseStream._flushMode = value;
|
||||
}
|
||||
}
|
||||
|
||||
public int BufferSize
|
||||
{
|
||||
get => BaseStream._bufferSize;
|
||||
get => _baseStream._bufferSize;
|
||||
set
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
if (BaseStream._workingBuffer != null)
|
||||
if (_baseStream._workingBuffer != null)
|
||||
{
|
||||
throw new ZlibException("The working buffer is already set.");
|
||||
}
|
||||
@@ -98,13 +102,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value,
|
||||
ZlibConstants.WorkingBufferSizeMin));
|
||||
}
|
||||
BaseStream._bufferSize = value;
|
||||
_baseStream._bufferSize = value;
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual long TotalIn => BaseStream._z.TotalBytesIn;
|
||||
internal virtual long TotalIn => _baseStream._z.TotalBytesIn;
|
||||
|
||||
internal virtual long TotalOut => BaseStream._z.TotalBytesOut;
|
||||
internal virtual long TotalOut => _baseStream._z.TotalBytesOut;
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -124,7 +128,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
return BaseStream._stream.CanRead;
|
||||
return _baseStream._stream.CanRead;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +154,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
return BaseStream._stream.CanWrite;
|
||||
return _baseStream._stream.CanWrite;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,13 +178,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
get
|
||||
{
|
||||
if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
|
||||
if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
|
||||
{
|
||||
return BaseStream._z.TotalBytesOut + _headerByteCount;
|
||||
return _baseStream._z.TotalBytesOut + _headerByteCount;
|
||||
}
|
||||
if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
|
||||
if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
|
||||
{
|
||||
return BaseStream._z.TotalBytesIn + BaseStream._gzipHeaderByteCount;
|
||||
return _baseStream._z.TotalBytesIn + _baseStream._gzipHeaderByteCount;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -194,36 +198,29 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <remarks>
|
||||
/// This may or may not result in a <c>Close()</c> call on the captive stream.
|
||||
/// </remarks>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
try
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing && (BaseStream != null))
|
||||
if (_baseStream is not null)
|
||||
{
|
||||
BaseStream.Dispose();
|
||||
Crc32 = BaseStream.Crc32;
|
||||
await _baseStream.DisposeAsync();
|
||||
Crc32 = _baseStream.Crc32;
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flush the stream.
|
||||
/// </summary>
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
BaseStream.Flush();
|
||||
return _baseStream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -257,13 +254,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <param name="offset">the offset within that data array to put the first byte read.</param>
|
||||
/// <param name="count">the number of bytes to read.</param>
|
||||
/// <returns>the number of bytes actually read</returns>
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
int n = BaseStream.Read(buffer, offset, count);
|
||||
int n = await _baseStream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
|
||||
// Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
|
||||
// Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
|
||||
@@ -271,9 +268,9 @@ namespace SharpCompress.Compressors.Deflate
|
||||
if (!_firstReadDone)
|
||||
{
|
||||
_firstReadDone = true;
|
||||
FileName = BaseStream._GzipFileName;
|
||||
Comment = BaseStream._GzipComment;
|
||||
LastModified = BaseStream._GzipMtime;
|
||||
FileName = _baseStream._GzipFileName;
|
||||
Comment = _baseStream._GzipComment;
|
||||
LastModified = _baseStream._GzipMtime;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -320,19 +317,19 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <param name="buffer">The buffer holding data to write to the stream.</param>
|
||||
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
|
||||
/// <param name="count">the number of bytes to write.</param>
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("GZipStream");
|
||||
}
|
||||
if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Undefined)
|
||||
if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Undefined)
|
||||
{
|
||||
//Console.WriteLine("GZipStream: First write");
|
||||
if (BaseStream._wantCompress)
|
||||
if (_baseStream._wantCompress)
|
||||
{
|
||||
// first write in compression, therefore, emit the GZIP header
|
||||
_headerByteCount = EmitHeader();
|
||||
_headerByteCount = await EmitHeaderAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -340,7 +337,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
}
|
||||
|
||||
BaseStream.Write(buffer, offset, count);
|
||||
await _baseStream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
#endregion Stream methods
|
||||
@@ -405,7 +402,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
|
||||
public int Crc32 { get; private set; }
|
||||
|
||||
private int EmitHeader()
|
||||
private async ValueTask<int> EmitHeaderAsync()
|
||||
{
|
||||
byte[]? commentBytes = (Comment is null) ? null
|
||||
: _encoding.GetBytes(Comment);
|
||||
@@ -474,7 +471,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
header[i++] = 0; // terminate
|
||||
}
|
||||
|
||||
BaseStream._stream.Write(header, 0, header.Length);
|
||||
await _baseStream._stream.WriteAsync(header, 0, header.Length);
|
||||
|
||||
return header.Length; // bytes written
|
||||
}
|
||||
|
||||
@@ -27,11 +27,15 @@
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
@@ -42,18 +46,18 @@ namespace SharpCompress.Compressors.Deflate
|
||||
GZIP = 1952
|
||||
}
|
||||
|
||||
internal class ZlibBaseStream : Stream
|
||||
internal class ZlibBaseStream : AsyncStream
|
||||
{
|
||||
protected internal ZlibCodec _z; // deferred init... new ZlibCodec();
|
||||
|
||||
protected internal StreamMode _streamMode = StreamMode.Undefined;
|
||||
protected internal FlushType _flushMode;
|
||||
protected internal ZlibStreamFlavor _flavor;
|
||||
protected internal CompressionMode _compressionMode;
|
||||
protected internal CompressionLevel _level;
|
||||
private readonly ZlibStreamFlavor _flavor;
|
||||
private readonly CompressionMode _compressionMode;
|
||||
private readonly CompressionLevel _level;
|
||||
protected internal byte[] _workingBuffer;
|
||||
protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault;
|
||||
protected internal byte[] _buf1 = new byte[1];
|
||||
private readonly byte[] _buf1 = new byte[1];
|
||||
|
||||
protected internal Stream _stream;
|
||||
protected internal CompressionStrategy Strategy = CompressionStrategy.Default;
|
||||
@@ -116,19 +120,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] workingBuffer
|
||||
{
|
||||
get => _workingBuffer ??= new byte[_bufferSize];
|
||||
}
|
||||
private byte[] workingBuffer => _workingBuffer ??= new byte[_bufferSize];
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
// workitem 7159
|
||||
// calculate the CRC on the unccompressed data (before writing)
|
||||
if (crc != null)
|
||||
{
|
||||
crc.SlurpBlock(buffer, offset, count);
|
||||
}
|
||||
crc?.SlurpBlock(buffer, offset, count);
|
||||
|
||||
if (_streamMode == StreamMode.Undefined)
|
||||
{
|
||||
@@ -148,7 +146,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
z.InputBuffer = buffer;
|
||||
_z.NextIn = offset;
|
||||
_z.AvailableBytesIn = count;
|
||||
bool done = false;
|
||||
var done = false;
|
||||
do
|
||||
{
|
||||
_z.OutputBuffer = workingBuffer;
|
||||
@@ -163,7 +161,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
|
||||
//if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
|
||||
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
|
||||
await _stream.WriteAsync(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut, cancellationToken);
|
||||
|
||||
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
|
||||
|
||||
@@ -176,7 +174,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
while (!done);
|
||||
}
|
||||
|
||||
private void finish()
|
||||
private async Task FinishAsync()
|
||||
{
|
||||
if (_z is null)
|
||||
{
|
||||
@@ -185,7 +183,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
|
||||
if (_streamMode == StreamMode.Writer)
|
||||
{
|
||||
bool done = false;
|
||||
var done = false;
|
||||
do
|
||||
{
|
||||
_z.OutputBuffer = workingBuffer;
|
||||
@@ -200,14 +198,14 @@ namespace SharpCompress.Compressors.Deflate
|
||||
string verb = (_wantCompress ? "de" : "in") + "flating";
|
||||
if (_z.Message is null)
|
||||
{
|
||||
throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc));
|
||||
throw new ZlibException($"{verb}: (rc = {rc})");
|
||||
}
|
||||
throw new ZlibException(verb + ": " + _z.Message);
|
||||
}
|
||||
|
||||
if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
|
||||
{
|
||||
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
|
||||
await _stream.WriteAsync(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
|
||||
}
|
||||
|
||||
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
|
||||
@@ -220,7 +218,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
while (!done);
|
||||
|
||||
Flush();
|
||||
await FlushAsync();
|
||||
|
||||
// workitem 7159
|
||||
if (_flavor == ZlibStreamFlavor.GZIP)
|
||||
@@ -228,12 +226,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
if (_wantCompress)
|
||||
{
|
||||
// Emit the GZIP trailer: CRC32 and size mod 2^32
|
||||
Span<byte> intBuf = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteInt32LittleEndian(intBuf, crc.Crc32Result);
|
||||
_stream.Write(intBuf);
|
||||
using var rented = MemoryPool<byte>.Shared.Rent(4);
|
||||
var intBuf = rented.Memory.Slice(0, 4);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(intBuf.Span, crc.Crc32Result);
|
||||
await _stream.WriteAsync(intBuf, CancellationToken.None);
|
||||
int c2 = (int)(crc.TotalBytesRead & 0x00000000FFFFFFFF);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(intBuf, c2);
|
||||
_stream.Write(intBuf);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(intBuf.Span, c2);
|
||||
await _stream.WriteAsync(intBuf, CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -256,44 +255,41 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
|
||||
// Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32
|
||||
Span<byte> trailer = stackalloc byte[8];
|
||||
using var rented = MemoryPool<byte>.Shared.Rent(8);
|
||||
var trailer = rented.Memory.Slice(0, 8);
|
||||
|
||||
// workitem 8679
|
||||
if (_z.AvailableBytesIn != 8)
|
||||
{
|
||||
// Make sure we have read to the end of the stream
|
||||
_z.InputBuffer.AsSpan(_z.NextIn, _z.AvailableBytesIn).CopyTo(trailer);
|
||||
_z.InputBuffer.AsSpan(_z.NextIn, _z.AvailableBytesIn).CopyTo(trailer.Span);
|
||||
int bytesNeeded = 8 - _z.AvailableBytesIn;
|
||||
int bytesRead = _stream.Read(trailer.Slice(_z.AvailableBytesIn, bytesNeeded));
|
||||
int bytesRead = await _stream.ReadAsync(trailer.Slice(_z.AvailableBytesIn, bytesNeeded));
|
||||
if (bytesNeeded != bytesRead)
|
||||
{
|
||||
throw new ZlibException(String.Format(
|
||||
"Protocol error. AvailableBytesIn={0}, expected 8",
|
||||
_z.AvailableBytesIn + bytesRead));
|
||||
throw new ZlibException($"Protocol error. AvailableBytesIn={_z.AvailableBytesIn + bytesRead}, expected 8");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_z.InputBuffer.AsSpan(_z.NextIn, trailer.Length).CopyTo(trailer);
|
||||
_z.InputBuffer.AsSpan(_z.NextIn, trailer.Length).CopyTo(trailer.Span);
|
||||
}
|
||||
|
||||
Int32 crc32_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer);
|
||||
Int32 crc32_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer.Span);
|
||||
Int32 crc32_actual = crc.Crc32Result;
|
||||
Int32 isize_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer.Slice(4));
|
||||
Int32 isize_expected = BinaryPrimitives.ReadInt32LittleEndian(trailer.Span.Slice(4));
|
||||
Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF);
|
||||
|
||||
if (crc32_actual != crc32_expected)
|
||||
{
|
||||
throw new ZlibException(
|
||||
String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))",
|
||||
crc32_actual, crc32_expected));
|
||||
$"Bad CRC32 in GZIP stream. (actual({crc32_actual:X8})!=expected({crc32_expected:X8}))");
|
||||
}
|
||||
|
||||
if (isize_actual != isize_expected)
|
||||
{
|
||||
throw new ZlibException(
|
||||
String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual,
|
||||
isize_expected));
|
||||
$"Bad size in GZIP stream. (actual({isize_actual})!=expected({isize_expected}))");
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -304,7 +300,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
}
|
||||
|
||||
private void end()
|
||||
private void End()
|
||||
{
|
||||
if (z is null)
|
||||
{
|
||||
@@ -321,36 +317,32 @@ namespace SharpCompress.Compressors.Deflate
|
||||
_z = null;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (isDisposed)
|
||||
if (_isDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
isDisposed = true;
|
||||
base.Dispose(disposing);
|
||||
if (disposing)
|
||||
{
|
||||
_isDisposed = true;
|
||||
if (_stream is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
finish();
|
||||
await FinishAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
end();
|
||||
_stream?.Dispose();
|
||||
End();
|
||||
_stream?.DisposeAsync();
|
||||
_stream = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_stream.Flush();
|
||||
return _stream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override Int64 Seek(Int64 offset, SeekOrigin origin)
|
||||
@@ -365,7 +357,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
_stream.SetLength(value);
|
||||
}
|
||||
|
||||
#if NOT
|
||||
/*
|
||||
public int Read()
|
||||
{
|
||||
if (Read(_buf1, 0, 1) == 0)
|
||||
@@ -375,19 +367,19 @@ namespace SharpCompress.Compressors.Deflate
|
||||
crc.SlurpBlock(_buf1,0,1);
|
||||
return (_buf1[0] & 0xFF);
|
||||
}
|
||||
#endif
|
||||
*/
|
||||
|
||||
private bool nomoreinput;
|
||||
private bool isDisposed;
|
||||
private bool _nomoreinput;
|
||||
private bool _isDisposed;
|
||||
|
||||
private string ReadZeroTerminatedString()
|
||||
private async Task<string> ReadZeroTerminatedStringAsync()
|
||||
{
|
||||
var list = new List<byte>();
|
||||
bool done = false;
|
||||
var done = false;
|
||||
do
|
||||
{
|
||||
// workitem 7740
|
||||
int n = _stream.Read(_buf1, 0, 1);
|
||||
int n = await _stream.ReadAsync(_buf1, 0, 1);
|
||||
if (n != 1)
|
||||
{
|
||||
throw new ZlibException("Unexpected EOF reading GZIP header.");
|
||||
@@ -406,13 +398,14 @@ namespace SharpCompress.Compressors.Deflate
|
||||
return _encoding.GetString(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
private int _ReadAndValidateGzipHeader()
|
||||
private async Task<int> ReadAndValidateGzipHeaderAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
int totalBytesRead = 0;
|
||||
var totalBytesRead = 0;
|
||||
|
||||
// read the header on the first read
|
||||
Span<byte> header = stackalloc byte[10];
|
||||
int n = _stream.Read(header);
|
||||
using var rented = MemoryPool<byte>.Shared.Rent(10);
|
||||
var header = rented.Memory.Slice(0, 10);
|
||||
int n = await _stream.ReadAsync(header, cancellationToken);
|
||||
|
||||
// workitem 8501: handle edge case (decompress empty stream)
|
||||
if (n == 0)
|
||||
@@ -425,46 +418,46 @@ namespace SharpCompress.Compressors.Deflate
|
||||
throw new ZlibException("Not a valid GZIP stream.");
|
||||
}
|
||||
|
||||
if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
|
||||
if (header.Span[0] != 0x1F || header.Span[1] != 0x8B || header.Span[2] != 8)
|
||||
{
|
||||
throw new ZlibException("Bad GZIP header.");
|
||||
}
|
||||
|
||||
int timet = BinaryPrimitives.ReadInt32LittleEndian(header.Slice(4));
|
||||
int timet = BinaryPrimitives.ReadInt32LittleEndian(header.Span.Slice(4));
|
||||
_GzipMtime = TarHeader.EPOCH.AddSeconds(timet);
|
||||
totalBytesRead += n;
|
||||
if ((header[3] & 0x04) == 0x04)
|
||||
if ((header.Span[3] & 0x04) == 0x04)
|
||||
{
|
||||
// read and discard extra field
|
||||
n = _stream.Read(header.Slice(0, 2)); // 2-byte length field
|
||||
n = await _stream.ReadAsync(header.Slice(0, 2), cancellationToken); // 2-byte length field
|
||||
totalBytesRead += n;
|
||||
|
||||
short extraLength = (short)(header[0] + header[1] * 256);
|
||||
short extraLength = (short)(header.Span[0] + header.Span[1] * 256);
|
||||
byte[] extra = new byte[extraLength];
|
||||
n = _stream.Read(extra, 0, extra.Length);
|
||||
n = await _stream.ReadAsync(extra, 0, extra.Length, cancellationToken);
|
||||
if (n != extraLength)
|
||||
{
|
||||
throw new ZlibException("Unexpected end-of-file reading GZIP header.");
|
||||
}
|
||||
totalBytesRead += n;
|
||||
}
|
||||
if ((header[3] & 0x08) == 0x08)
|
||||
if ((header.Span[3] & 0x08) == 0x08)
|
||||
{
|
||||
_GzipFileName = ReadZeroTerminatedString();
|
||||
_GzipFileName = await ReadZeroTerminatedStringAsync();
|
||||
}
|
||||
if ((header[3] & 0x10) == 0x010)
|
||||
if ((header.Span[3] & 0x10) == 0x010)
|
||||
{
|
||||
_GzipComment = ReadZeroTerminatedString();
|
||||
_GzipComment = await ReadZeroTerminatedStringAsync();
|
||||
}
|
||||
if ((header[3] & 0x02) == 0x02)
|
||||
if ((header.Span[3] & 0x02) == 0x02)
|
||||
{
|
||||
Read(_buf1, 0, 1); // CRC16, ignore
|
||||
await ReadAsync(_buf1, 0, 1, cancellationToken); // CRC16, ignore
|
||||
}
|
||||
|
||||
return totalBytesRead;
|
||||
}
|
||||
|
||||
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
// According to MS documentation, any implementation of the IO.Stream.Read function must:
|
||||
// (a) throw an exception if offset & count reference an invalid part of the buffer,
|
||||
@@ -487,7 +480,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
z.AvailableBytesIn = 0;
|
||||
if (_flavor == ZlibStreamFlavor.GZIP)
|
||||
{
|
||||
_gzipHeaderByteCount = _ReadAndValidateGzipHeader();
|
||||
_gzipHeaderByteCount = await ReadAndValidateGzipHeaderAsync(cancellationToken);
|
||||
|
||||
// workitem 8501: handle edge case (decompress empty stream)
|
||||
if (_gzipHeaderByteCount == 0)
|
||||
@@ -506,7 +499,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if (nomoreinput && _wantCompress)
|
||||
if (_nomoreinput && _wantCompress)
|
||||
{
|
||||
return 0; // workitem 8557
|
||||
}
|
||||
@@ -527,7 +520,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
throw new ArgumentOutOfRangeException(nameof(count));
|
||||
}
|
||||
|
||||
int rc = 0;
|
||||
var rc = 0;
|
||||
|
||||
// set up the output of the deflate/inflate codec:
|
||||
_z.OutputBuffer = buffer;
|
||||
@@ -542,14 +535,14 @@ namespace SharpCompress.Compressors.Deflate
|
||||
do
|
||||
{
|
||||
// need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any.
|
||||
if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
|
||||
if ((_z.AvailableBytesIn == 0) && (!_nomoreinput))
|
||||
{
|
||||
// No data available, so try to Read data from the captive stream.
|
||||
_z.NextIn = 0;
|
||||
_z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
|
||||
_z.AvailableBytesIn = await _stream.ReadAsync(_workingBuffer, 0, _workingBuffer.Length, cancellationToken);
|
||||
if (_z.AvailableBytesIn == 0)
|
||||
{
|
||||
nomoreinput = true;
|
||||
_nomoreinput = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,23 +551,22 @@ namespace SharpCompress.Compressors.Deflate
|
||||
? _z.Deflate(_flushMode)
|
||||
: _z.Inflate(_flushMode);
|
||||
|
||||
if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
|
||||
if (_nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
|
||||
{
|
||||
throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"),
|
||||
rc, _z.Message));
|
||||
throw new ZlibException($"{(_wantCompress ? "de" : "in")}flating: rc={rc} msg={_z.Message}");
|
||||
}
|
||||
|
||||
if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
|
||||
if ((_nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
|
||||
{
|
||||
break; // nothing more to read
|
||||
}
|
||||
} //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
|
||||
while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
|
||||
while (_z.AvailableBytesOut > 0 && !_nomoreinput && rc == ZlibConstants.Z_OK);
|
||||
|
||||
// workitem 8557
|
||||
// is there more room in output?
|
||||
@@ -586,7 +578,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
}
|
||||
|
||||
// are we completely done reading?
|
||||
if (nomoreinput)
|
||||
if (_nomoreinput)
|
||||
{
|
||||
// and in compression?
|
||||
if (_wantCompress)
|
||||
@@ -597,7 +589,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
|
||||
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
|
||||
{
|
||||
throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message));
|
||||
throw new ZlibException($"Deflating: rc={rc} msg={_z.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -606,10 +598,7 @@ namespace SharpCompress.Compressors.Deflate
|
||||
rc = (count - _z.AvailableBytesOut);
|
||||
|
||||
// calculate CRC after reading
|
||||
if (crc != null)
|
||||
{
|
||||
crc.SlurpBlock(buffer, offset, rc);
|
||||
}
|
||||
crc?.SlurpBlock(buffer, offset, rc);
|
||||
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -28,10 +28,13 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.Deflate
|
||||
{
|
||||
public class ZlibStream : Stream
|
||||
public class ZlibStream : AsyncStream
|
||||
{
|
||||
private readonly ZlibBaseStream _baseStream;
|
||||
private bool _disposed;
|
||||
@@ -204,35 +207,25 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <remarks>
|
||||
/// This may or may not result in a <c>Close()</c> call on the captive stream.
|
||||
/// </remarks>
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
if (!_disposed)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_baseStream?.Dispose();
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
await _baseStream.DisposeAsync();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flush the stream.
|
||||
/// </summary>
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("ZlibStream");
|
||||
}
|
||||
_baseStream.Flush();
|
||||
return _baseStream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -261,22 +254,13 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <param name="buffer">The buffer into which the read data should be placed.</param>
|
||||
/// <param name="offset">the offset within that data array to put the first byte read.</param>
|
||||
/// <param name="count">the number of bytes to read.</param>
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("ZlibStream");
|
||||
}
|
||||
return _baseStream.Read(buffer, offset, count);
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("ZlibStream");
|
||||
}
|
||||
return _baseStream.ReadByte();
|
||||
return await _baseStream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -321,24 +305,14 @@ namespace SharpCompress.Compressors.Deflate
|
||||
/// <param name="buffer">The buffer holding data to write to the stream.</param>
|
||||
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
|
||||
/// <param name="count">the number of bytes to write.</param>
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("ZlibStream");
|
||||
}
|
||||
_baseStream.Write(buffer, offset, count);
|
||||
await _baseStream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
throw new ObjectDisposedException("ZlibStream");
|
||||
}
|
||||
_baseStream.WriteByte(value);
|
||||
}
|
||||
|
||||
#endregion System.IO.Stream methods
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.SevenZip;
|
||||
using SharpCompress.Compressors.LZMA.Utilites;
|
||||
using SharpCompress.IO;
|
||||
@@ -91,8 +93,9 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream CreateDecoderStream(Stream[] packStreams, long[] packSizes, Stream[] outStreams,
|
||||
CFolder folderInfo, int coderIndex, IPasswordProvider pass)
|
||||
private static async ValueTask<Stream> CreateDecoderStream(Stream[] packStreams, long[] packSizes, Stream[] outStreams,
|
||||
CFolder folderInfo, int coderIndex, IPasswordProvider pass,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var coderInfo = folderInfo._coders[coderIndex];
|
||||
if (coderInfo._numOutStreams != 1)
|
||||
@@ -127,8 +130,8 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
|
||||
int otherCoderIndex = FindCoderIndexForOutStreamIndex(folderInfo, pairedOutIndex);
|
||||
inStreams[i] = CreateDecoderStream(packStreams, packSizes, outStreams, folderInfo, otherCoderIndex,
|
||||
pass);
|
||||
inStreams[i] = await CreateDecoderStream(packStreams, packSizes, outStreams, folderInfo, otherCoderIndex,
|
||||
pass, cancellationToken);
|
||||
|
||||
//inStreamSizes[i] = folderInfo.UnpackSizes[pairedOutIndex];
|
||||
|
||||
@@ -154,11 +157,11 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
|
||||
long unpackSize = folderInfo._unpackSizes[outStreamId];
|
||||
return DecoderRegistry.CreateDecoderStream(coderInfo._methodId, inStreams, coderInfo._props, pass, unpackSize);
|
||||
return await DecoderRegistry.CreateDecoderStream(coderInfo._methodId, inStreams, coderInfo._props, pass, unpackSize, cancellationToken);
|
||||
}
|
||||
|
||||
internal static Stream CreateDecoderStream(Stream inStream, long startPos, long[] packSizes, CFolder folderInfo,
|
||||
IPasswordProvider pass)
|
||||
internal static async ValueTask<Stream> CreateDecoderStream(Stream inStream, long startPos, long[] packSizes, CFolder folderInfo,
|
||||
IPasswordProvider pass, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!folderInfo.CheckStructure())
|
||||
{
|
||||
@@ -176,7 +179,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
int primaryCoderIndex, primaryOutStreamIndex;
|
||||
FindPrimaryOutStreamIndex(folderInfo, out primaryCoderIndex, out primaryOutStreamIndex);
|
||||
return CreateDecoderStream(inStreams, packSizes, outStreams, folderInfo, primaryCoderIndex, pass);
|
||||
return await CreateDecoderStream(inStreams, packSizes, outStreams, folderInfo, primaryCoderIndex, pass, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
@@ -59,8 +61,8 @@ namespace SharpCompress.Compressors.LZMA
|
||||
/// <param name="progress">
|
||||
/// callback progress reference.
|
||||
/// </param>
|
||||
void Code(Stream inStream, Stream outStream,
|
||||
Int64 inSize, Int64 outSize, ICodeProgress progress);
|
||||
ValueTask CodeAsync(Stream inStream, Stream outStream,
|
||||
Int64 inSize, Int64 outSize, ICodeProgress progress, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Crypto;
|
||||
using SharpCompress.IO;
|
||||
|
||||
@@ -14,61 +17,70 @@ namespace SharpCompress.Compressors.LZMA
|
||||
/// <summary>
|
||||
/// Stream supporting the LZIP format, as documented at http://www.nongnu.org/lzip/manual/lzip_manual.html
|
||||
/// </summary>
|
||||
public sealed class LZipStream : Stream
|
||||
public sealed class LZipStream : AsyncStream
|
||||
{
|
||||
private readonly Stream _stream;
|
||||
private readonly CountingWritableSubStream? _countingWritableSubStream;
|
||||
#nullable disable
|
||||
private Stream _stream;
|
||||
#nullable enable
|
||||
private CountingWritableSubStream? _countingWritableSubStream;
|
||||
private bool _disposed;
|
||||
private bool _finished;
|
||||
|
||||
private long _writeCount;
|
||||
|
||||
public LZipStream(Stream stream, CompressionMode mode)
|
||||
private LZipStream()
|
||||
{
|
||||
Mode = mode;
|
||||
|
||||
}
|
||||
|
||||
public static async ValueTask<LZipStream> CreateAsync(Stream stream, CompressionMode mode)
|
||||
{
|
||||
var lzip = new LZipStream();
|
||||
lzip.Mode = mode;
|
||||
|
||||
if (mode == CompressionMode.Decompress)
|
||||
{
|
||||
int dSize = ValidateAndReadSize(stream);
|
||||
int dSize = await ValidateAndReadSize(stream);
|
||||
if (dSize == 0)
|
||||
{
|
||||
throw new IOException("Not an LZip stream");
|
||||
}
|
||||
byte[] properties = GetProperties(dSize);
|
||||
_stream = new LzmaStream(properties, stream);
|
||||
lzip._stream = await LzmaStream.CreateAsync(properties, stream);
|
||||
}
|
||||
else
|
||||
{
|
||||
//default
|
||||
int dSize = 104 * 1024;
|
||||
WriteHeaderSize(stream);
|
||||
await WriteHeaderSizeAsync(stream);
|
||||
|
||||
_countingWritableSubStream = new CountingWritableSubStream(stream);
|
||||
_stream = new Crc32Stream(new LzmaStream(new LzmaEncoderProperties(true, dSize), false, _countingWritableSubStream));
|
||||
lzip._countingWritableSubStream = new CountingWritableSubStream(stream);
|
||||
lzip._stream = new Crc32Stream(new LzmaStream(new LzmaEncoderProperties(true, dSize), false, lzip._countingWritableSubStream));
|
||||
}
|
||||
return lzip;
|
||||
}
|
||||
|
||||
public void Finish()
|
||||
public async ValueTask FinishAsync()
|
||||
{
|
||||
if (!_finished)
|
||||
{
|
||||
if (Mode == CompressionMode.Compress)
|
||||
{
|
||||
var crc32Stream = (Crc32Stream)_stream;
|
||||
crc32Stream.WrappedStream.Dispose();
|
||||
crc32Stream.Dispose();
|
||||
await crc32Stream.WrappedStream.DisposeAsync();
|
||||
await crc32Stream.DisposeAsync();
|
||||
var compressedCount = _countingWritableSubStream!.Count;
|
||||
|
||||
Span<byte> intBuf = stackalloc byte[8];
|
||||
byte[] intBuf = new byte[8];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, crc32Stream.Crc);
|
||||
_countingWritableSubStream.Write(intBuf.Slice(0, 4));
|
||||
await _countingWritableSubStream.WriteAsync(intBuf, 0, 4);
|
||||
|
||||
BinaryPrimitives.WriteInt64LittleEndian(intBuf, _writeCount);
|
||||
_countingWritableSubStream.Write(intBuf);
|
||||
await _countingWritableSubStream.WriteAsync(intBuf, 0, 8);
|
||||
|
||||
//total with headers
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, compressedCount + 6 + 20);
|
||||
_countingWritableSubStream.Write(intBuf);
|
||||
await _countingWritableSubStream.WriteAsync(intBuf, 0, 8);
|
||||
}
|
||||
_finished = true;
|
||||
}
|
||||
@@ -76,21 +88,18 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
#region Stream methods
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_disposed = true;
|
||||
if (disposing)
|
||||
{
|
||||
Finish();
|
||||
_stream.Dispose();
|
||||
}
|
||||
await FinishAsync();
|
||||
await _stream.DisposeAsync();
|
||||
}
|
||||
|
||||
public CompressionMode Mode { get; }
|
||||
public CompressionMode Mode { get; private set; }
|
||||
|
||||
public override bool CanRead => Mode == CompressionMode.Decompress;
|
||||
|
||||
@@ -98,54 +107,38 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
public override bool CanWrite => Mode == CompressionMode.Compress;
|
||||
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_stream.Flush();
|
||||
return _stream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
// TODO: Both Length and Position are sometimes feasible, but would require
|
||||
// reading the output length when we initialize.
|
||||
public override long Length => throw new NotImplementedException();
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
|
||||
public override long Position { get => throw new NotImplementedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
|
||||
|
||||
public override int ReadByte() => _stream.ReadByte();
|
||||
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
return _stream.ReadAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotImplementedException();
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
|
||||
#if !NET461 && !NETSTANDARD2_0
|
||||
|
||||
public override int Read(Span<byte> buffer)
|
||||
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
return _stream.Read(buffer);
|
||||
}
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
_stream.Write(buffer);
|
||||
|
||||
await _stream.WriteAsync(buffer, cancellationToken);
|
||||
_writeCount += buffer.Length;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
_stream.Write(buffer, offset, count);
|
||||
await _stream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
_writeCount += count;
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
_stream.WriteByte(value);
|
||||
++_writeCount;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
@@ -155,14 +148,14 @@ namespace SharpCompress.Compressors.LZMA
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to read from. Must not be null.</param>
|
||||
/// <returns><c>true</c> if the given stream is an LZip file, <c>false</c> otherwise.</returns>
|
||||
public static bool IsLZipFile(Stream stream) => ValidateAndReadSize(stream) != 0;
|
||||
public static async ValueTask<bool> IsLZipFileAsync(Stream stream) => await ValidateAndReadSize(stream) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the 6-byte header of the stream, and returns 0 if either the header
|
||||
/// couldn't be read or it isn't a validate LZIP header, or the dictionary
|
||||
/// size if it *is* a valid LZIP file.
|
||||
/// </summary>
|
||||
public static int ValidateAndReadSize(Stream stream)
|
||||
private static async ValueTask<int> ValidateAndReadSize(Stream stream)
|
||||
{
|
||||
if (stream is null)
|
||||
{
|
||||
@@ -170,8 +163,9 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
|
||||
// Read the header
|
||||
Span<byte> header = stackalloc byte[6];
|
||||
int n = stream.Read(header);
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(6);
|
||||
var header = buffer.Memory.Slice(0,6);
|
||||
int n = await stream.ReadAsync(header);
|
||||
|
||||
// TODO: Handle reading only part of the header?
|
||||
|
||||
@@ -180,18 +174,18 @@ namespace SharpCompress.Compressors.LZMA
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (header[0] != 'L' || header[1] != 'Z' || header[2] != 'I' || header[3] != 'P' || header[4] != 1 /* version 1 */)
|
||||
if (header.Span[0] != 'L' || header.Span[1] != 'Z' || header.Span[2] != 'I' || header.Span[3] != 'P' || header.Span[4] != 1 /* version 1 */)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
int basePower = header[5] & 0x1F;
|
||||
int subtractionNumerator = (header[5] & 0xE0) >> 5;
|
||||
int basePower = header.Span[5] & 0x1F;
|
||||
int subtractionNumerator = (header.Span[5] & 0xE0) >> 5;
|
||||
return (1 << basePower) - subtractionNumerator * (1 << (basePower - 4));
|
||||
}
|
||||
|
||||
private static readonly byte[] headerBytes = new byte[6] { (byte)'L', (byte)'Z', (byte)'I', (byte)'P', 1, 113 };
|
||||
|
||||
public static void WriteHeaderSize(Stream stream)
|
||||
public static async ValueTask WriteHeaderSizeAsync(Stream stream)
|
||||
{
|
||||
if (stream is null)
|
||||
{
|
||||
@@ -199,7 +193,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
|
||||
// hard coding the dictionary size encoding
|
||||
stream.Write(headerBytes, 0, 6);
|
||||
await stream.WriteAsync(headerBytes, 0, 6);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors.LZMA.LZ;
|
||||
using SharpCompress.Compressors.LZMA.RangeCoder;
|
||||
|
||||
@@ -11,11 +11,11 @@ namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
private class LenDecoder
|
||||
{
|
||||
private BitDecoder _choice = new BitDecoder();
|
||||
private BitDecoder _choice2 = new BitDecoder();
|
||||
private BitDecoder _choice = new();
|
||||
private BitDecoder _choice2 = new();
|
||||
private readonly BitTreeDecoder[] _lowCoder = new BitTreeDecoder[Base.K_NUM_POS_STATES_MAX];
|
||||
private readonly BitTreeDecoder[] _midCoder = new BitTreeDecoder[Base.K_NUM_POS_STATES_MAX];
|
||||
private BitTreeDecoder _highCoder = new BitTreeDecoder(Base.K_NUM_HIGH_LEN_BITS);
|
||||
private BitTreeDecoder _highCoder = new(Base.K_NUM_HIGH_LEN_BITS);
|
||||
private uint _numPosStates;
|
||||
|
||||
public void Create(uint numPosStates)
|
||||
@@ -40,21 +40,21 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_highCoder.Init();
|
||||
}
|
||||
|
||||
public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState)
|
||||
public async ValueTask<uint> DecodeAsync(RangeCoder.Decoder rangeDecoder, uint posState, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_choice.Decode(rangeDecoder) == 0)
|
||||
if (await _choice.DecodeAsync(rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
return _lowCoder[posState].Decode(rangeDecoder);
|
||||
return await _lowCoder[posState].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
uint symbol = Base.K_NUM_LOW_LEN_SYMBOLS;
|
||||
if (_choice2.Decode(rangeDecoder) == 0)
|
||||
if (await _choice2.DecodeAsync(rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
symbol += _midCoder[posState].Decode(rangeDecoder);
|
||||
symbol += await _midCoder[posState].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
symbol += Base.K_NUM_MID_LEN_SYMBOLS;
|
||||
symbol += _highCoder.Decode(rangeDecoder);
|
||||
symbol += await _highCoder.DecodeAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
return symbol;
|
||||
}
|
||||
@@ -79,31 +79,31 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
public byte DecodeNormal(RangeCoder.Decoder rangeDecoder)
|
||||
public async ValueTask<byte> DecodeNormalAsync(RangeCoder.Decoder rangeDecoder, CancellationToken cancellationToken)
|
||||
{
|
||||
uint symbol = 1;
|
||||
do
|
||||
{
|
||||
symbol = (symbol << 1) | _decoders[symbol].Decode(rangeDecoder);
|
||||
symbol = (symbol << 1) | await _decoders[symbol].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
while (symbol < 0x100);
|
||||
return (byte)symbol;
|
||||
}
|
||||
|
||||
public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte)
|
||||
public async ValueTask<byte> DecodeWithMatchByteAsync(RangeCoder.Decoder rangeDecoder, byte matchByte, CancellationToken cancellationToken)
|
||||
{
|
||||
uint symbol = 1;
|
||||
do
|
||||
{
|
||||
uint matchBit = (uint)(matchByte >> 7) & 1;
|
||||
matchByte <<= 1;
|
||||
uint bit = _decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder);
|
||||
uint bit = await _decoders[((1 + matchBit) << 8) + symbol].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
symbol = (symbol << 1) | bit;
|
||||
if (matchBit != bit)
|
||||
{
|
||||
while (symbol < 0x100)
|
||||
{
|
||||
symbol = (symbol << 1) | _decoders[symbol].Decode(rangeDecoder);
|
||||
symbol = (symbol << 1) | await _decoders[symbol].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -113,12 +113,12 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
private Decoder2[] _coders;
|
||||
private int _numPrevBits;
|
||||
private int _numPosBits;
|
||||
private uint _posMask;
|
||||
|
||||
public void Create(int numPosBits, int numPrevBits)
|
||||
private readonly Decoder2[]_coders;
|
||||
private readonly int _numPrevBits;
|
||||
private readonly int _numPosBits;
|
||||
private readonly uint _posMask;
|
||||
|
||||
public LiteralDecoder(int numPosBits, int numPrevBits)
|
||||
{
|
||||
if (_coders != null && _numPrevBits == numPrevBits &&
|
||||
_numPosBits == numPosBits)
|
||||
@@ -150,18 +150,18 @@ namespace SharpCompress.Compressors.LZMA
|
||||
return ((pos & _posMask) << _numPrevBits) + (uint)(prevByte >> (8 - _numPrevBits));
|
||||
}
|
||||
|
||||
public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte)
|
||||
public ValueTask<byte> DecodeNormalAsync(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, CancellationToken cancellationToken)
|
||||
{
|
||||
return _coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder);
|
||||
return _coders[GetState(pos, prevByte)].DecodeNormalAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
|
||||
public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte)
|
||||
public ValueTask<byte> DecodeWithMatchByteAsync(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte, CancellationToken cancellationToken)
|
||||
{
|
||||
return _coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte);
|
||||
return _coders[GetState(pos, prevByte)].DecodeWithMatchByteAsync(rangeDecoder, matchByte, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private OutWindow _outWindow;
|
||||
private OutWindow? _outWindow;
|
||||
|
||||
private readonly BitDecoder[] _isMatchDecoders = new BitDecoder[Base.K_NUM_STATES << Base.K_NUM_POS_STATES_BITS_MAX];
|
||||
private readonly BitDecoder[] _isRepDecoders = new BitDecoder[Base.K_NUM_STATES];
|
||||
@@ -173,18 +173,18 @@ namespace SharpCompress.Compressors.LZMA
|
||||
private readonly BitTreeDecoder[] _posSlotDecoder = new BitTreeDecoder[Base.K_NUM_LEN_TO_POS_STATES];
|
||||
private readonly BitDecoder[] _posDecoders = new BitDecoder[Base.K_NUM_FULL_DISTANCES - Base.K_END_POS_MODEL_INDEX];
|
||||
|
||||
private BitTreeDecoder _posAlignDecoder = new BitTreeDecoder(Base.K_NUM_ALIGN_BITS);
|
||||
private BitTreeDecoder _posAlignDecoder = new(Base.K_NUM_ALIGN_BITS);
|
||||
|
||||
private readonly LenDecoder _lenDecoder = new LenDecoder();
|
||||
private readonly LenDecoder _repLenDecoder = new LenDecoder();
|
||||
private readonly LenDecoder _lenDecoder = new();
|
||||
private readonly LenDecoder _repLenDecoder = new();
|
||||
|
||||
private readonly LiteralDecoder _literalDecoder = new LiteralDecoder();
|
||||
private LiteralDecoder? _literalDecoder;
|
||||
|
||||
private int _dictionarySize;
|
||||
|
||||
private uint _posStateMask;
|
||||
|
||||
private Base.State _state = new Base.State();
|
||||
private Base.State _state = new();
|
||||
private uint _rep0, _rep1, _rep2, _rep3;
|
||||
|
||||
public Decoder()
|
||||
@@ -196,15 +196,16 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateDictionary()
|
||||
private OutWindow CreateDictionary()
|
||||
{
|
||||
if (_dictionarySize < 0)
|
||||
{
|
||||
throw new InvalidParamException();
|
||||
}
|
||||
_outWindow = new OutWindow();
|
||||
var outWindow = new OutWindow();
|
||||
int blockSize = Math.Max(_dictionarySize, (1 << 12));
|
||||
_outWindow.Create(blockSize);
|
||||
outWindow.Create(blockSize);
|
||||
return outWindow;
|
||||
}
|
||||
|
||||
private void SetLiteralProperties(int lp, int lc)
|
||||
@@ -217,7 +218,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
throw new InvalidParamException();
|
||||
}
|
||||
_literalDecoder.Create(lp, lc);
|
||||
_literalDecoder = new(lp, lc);
|
||||
}
|
||||
|
||||
private void SetPosBitsProperties(int pb)
|
||||
@@ -249,7 +250,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_isRepG2Decoders[i].Init();
|
||||
}
|
||||
|
||||
_literalDecoder.Init();
|
||||
_literalDecoder!.Init();
|
||||
for (i = 0; i < Base.K_NUM_LEN_TO_POS_STATES; i++)
|
||||
{
|
||||
_posSlotDecoder[i].Init();
|
||||
@@ -272,12 +273,12 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_rep3 = 0;
|
||||
}
|
||||
|
||||
public void Code(Stream inStream, Stream outStream,
|
||||
Int64 inSize, Int64 outSize, ICodeProgress progress)
|
||||
public async ValueTask CodeAsync(Stream inStream, Stream outStream,
|
||||
Int64 inSize, Int64 outSize, ICodeProgress progress, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_outWindow is null)
|
||||
{
|
||||
CreateDictionary();
|
||||
_outWindow = CreateDictionary();
|
||||
}
|
||||
_outWindow.Init(outStream);
|
||||
if (outSize > 0)
|
||||
@@ -290,9 +291,9 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
|
||||
RangeCoder.Decoder rangeDecoder = new RangeCoder.Decoder();
|
||||
rangeDecoder.Init(inStream);
|
||||
await rangeDecoder.InitAsync(inStream, cancellationToken);
|
||||
|
||||
Code(_dictionarySize, _outWindow, rangeDecoder);
|
||||
await CodeAsync(_dictionarySize, _outWindow, rangeDecoder, cancellationToken);
|
||||
|
||||
_outWindow.ReleaseStream();
|
||||
rangeDecoder.ReleaseStream();
|
||||
@@ -308,8 +309,9 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_outWindow = null;
|
||||
}
|
||||
|
||||
internal bool Code(int dictionarySize, OutWindow outWindow, RangeCoder.Decoder rangeDecoder)
|
||||
internal async ValueTask<bool> CodeAsync(int dictionarySize, OutWindow outWindow, RangeCoder.Decoder rangeDecoder, CancellationToken cancellationToken)
|
||||
{
|
||||
_literalDecoder ??= _literalDecoder.CheckNotNull(nameof(_literalDecoder));
|
||||
int dictionarySizeCheck = Math.Max(dictionarySize, 1);
|
||||
|
||||
outWindow.CopyPending();
|
||||
@@ -317,19 +319,19 @@ namespace SharpCompress.Compressors.LZMA
|
||||
while (outWindow.HasSpace)
|
||||
{
|
||||
uint posState = (uint)outWindow._total & _posStateMask;
|
||||
if (_isMatchDecoders[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].Decode(rangeDecoder) == 0)
|
||||
if (await _isMatchDecoders[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].DecodeAsync(rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
byte b;
|
||||
byte prevByte = outWindow.GetByte(0);
|
||||
if (!_state.IsCharState())
|
||||
{
|
||||
b = _literalDecoder.DecodeWithMatchByte(rangeDecoder,
|
||||
b = await _literalDecoder.DecodeWithMatchByteAsync(rangeDecoder,
|
||||
(uint)outWindow._total, prevByte,
|
||||
outWindow.GetByte((int)_rep0));
|
||||
outWindow.GetByte((int)_rep0), cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
b = _literalDecoder.DecodeNormal(rangeDecoder, (uint)outWindow._total, prevByte);
|
||||
b = await _literalDecoder.DecodeNormalAsync(rangeDecoder, (uint)outWindow._total, prevByte, cancellationToken);
|
||||
}
|
||||
outWindow.PutByte(b);
|
||||
_state.UpdateChar();
|
||||
@@ -337,13 +339,13 @@ namespace SharpCompress.Compressors.LZMA
|
||||
else
|
||||
{
|
||||
uint len;
|
||||
if (_isRepDecoders[_state._index].Decode(rangeDecoder) == 1)
|
||||
if (await _isRepDecoders[_state._index].DecodeAsync(rangeDecoder, cancellationToken) == 1)
|
||||
{
|
||||
if (_isRepG0Decoders[_state._index].Decode(rangeDecoder) == 0)
|
||||
if (await _isRepG0Decoders[_state._index].DecodeAsync(rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
if (
|
||||
_isRep0LongDecoders[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].Decode(
|
||||
rangeDecoder) == 0)
|
||||
await _isRep0LongDecoders[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].DecodeAsync(
|
||||
rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
_state.UpdateShortRep();
|
||||
outWindow.PutByte(outWindow.GetByte((int)_rep0));
|
||||
@@ -353,13 +355,13 @@ namespace SharpCompress.Compressors.LZMA
|
||||
else
|
||||
{
|
||||
UInt32 distance;
|
||||
if (_isRepG1Decoders[_state._index].Decode(rangeDecoder) == 0)
|
||||
if (await _isRepG1Decoders[_state._index].DecodeAsync(rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
distance = _rep1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_isRepG2Decoders[_state._index].Decode(rangeDecoder) == 0)
|
||||
if (await _isRepG2Decoders[_state._index].DecodeAsync(rangeDecoder, cancellationToken) == 0)
|
||||
{
|
||||
distance = _rep2;
|
||||
}
|
||||
@@ -373,7 +375,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_rep1 = _rep0;
|
||||
_rep0 = distance;
|
||||
}
|
||||
len = _repLenDecoder.Decode(rangeDecoder, posState) + Base.K_MATCH_MIN_LEN;
|
||||
len = await _repLenDecoder.DecodeAsync(rangeDecoder, posState, cancellationToken) + Base.K_MATCH_MIN_LEN;
|
||||
_state.UpdateRep();
|
||||
}
|
||||
else
|
||||
@@ -381,23 +383,22 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_rep3 = _rep2;
|
||||
_rep2 = _rep1;
|
||||
_rep1 = _rep0;
|
||||
len = Base.K_MATCH_MIN_LEN + _lenDecoder.Decode(rangeDecoder, posState);
|
||||
len = Base.K_MATCH_MIN_LEN + await _lenDecoder.DecodeAsync(rangeDecoder, posState, cancellationToken);
|
||||
_state.UpdateMatch();
|
||||
uint posSlot = _posSlotDecoder[Base.GetLenToPosState(len)].Decode(rangeDecoder);
|
||||
uint posSlot = await _posSlotDecoder[Base.GetLenToPosState(len)].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
if (posSlot >= Base.K_START_POS_MODEL_INDEX)
|
||||
{
|
||||
int numDirectBits = (int)((posSlot >> 1) - 1);
|
||||
_rep0 = ((2 | (posSlot & 1)) << numDirectBits);
|
||||
if (posSlot < Base.K_END_POS_MODEL_INDEX)
|
||||
{
|
||||
_rep0 += BitTreeDecoder.ReverseDecode(_posDecoders,
|
||||
_rep0 - posSlot - 1, rangeDecoder, numDirectBits);
|
||||
_rep0 += await BitTreeDecoder.ReverseDecode(_posDecoders,
|
||||
_rep0 - posSlot - 1, rangeDecoder, numDirectBits, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
_rep0 += (rangeDecoder.DecodeDirectBits(
|
||||
numDirectBits - Base.K_NUM_ALIGN_BITS) << Base.K_NUM_ALIGN_BITS);
|
||||
_rep0 += _posAlignDecoder.ReverseDecode(rangeDecoder);
|
||||
_rep0 += (await rangeDecoder.DecodeDirectBitsAsync(numDirectBits - Base.K_NUM_ALIGN_BITS, cancellationToken) << Base.K_NUM_ALIGN_BITS);
|
||||
_rep0 += await _posAlignDecoder.ReverseDecode(rangeDecoder, cancellationToken);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -450,7 +451,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
if (_outWindow is null)
|
||||
{
|
||||
CreateDictionary();
|
||||
_outWindow = CreateDictionary();
|
||||
}
|
||||
_outWindow.Train(stream);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors.LZMA.LZ;
|
||||
using SharpCompress.Compressors.LZMA.RangeCoder;
|
||||
|
||||
@@ -61,7 +63,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
return (UInt32)(G_FAST_POS[pos >> 26] + 52);
|
||||
}
|
||||
|
||||
private Base.State _state = new Base.State();
|
||||
private Base.State _state = new();
|
||||
private Byte _previousByte;
|
||||
private readonly UInt32[] _repDistances = new UInt32[Base.K_NUM_REP_DISTANCES];
|
||||
|
||||
@@ -97,18 +99,18 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol)
|
||||
public async ValueTask EncodeAsync(RangeCoder.Encoder rangeEncoder, byte symbol)
|
||||
{
|
||||
uint context = 1;
|
||||
for (int i = 7; i >= 0; i--)
|
||||
{
|
||||
uint bit = (uint)((symbol >> i) & 1);
|
||||
_encoders[context].Encode(rangeEncoder, bit);
|
||||
await _encoders[context].EncodeAsync(rangeEncoder, bit);
|
||||
context = (context << 1) | bit;
|
||||
}
|
||||
}
|
||||
|
||||
public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
|
||||
public async ValueTask EncodeMatchedAsync(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
|
||||
{
|
||||
uint context = 1;
|
||||
bool same = true;
|
||||
@@ -122,7 +124,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
state += ((1 + matchBit) << 8);
|
||||
same = (matchBit == bit);
|
||||
}
|
||||
_encoders[state].Encode(rangeEncoder, bit);
|
||||
await _encoders[state].EncodeAsync(rangeEncoder, bit);
|
||||
context = (context << 1) | bit;
|
||||
}
|
||||
}
|
||||
@@ -196,11 +198,11 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
private class LenEncoder
|
||||
{
|
||||
private BitEncoder _choice = new BitEncoder();
|
||||
private BitEncoder _choice2 = new BitEncoder();
|
||||
private BitEncoder _choice = new();
|
||||
private BitEncoder _choice2 = new();
|
||||
private readonly BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.K_NUM_POS_STATES_ENCODING_MAX];
|
||||
private readonly BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.K_NUM_POS_STATES_ENCODING_MAX];
|
||||
private BitTreeEncoder _highCoder = new BitTreeEncoder(Base.K_NUM_HIGH_LEN_BITS);
|
||||
private BitTreeEncoder _highCoder = new(Base.K_NUM_HIGH_LEN_BITS);
|
||||
|
||||
public LenEncoder()
|
||||
{
|
||||
@@ -223,26 +225,26 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_highCoder.Init();
|
||||
}
|
||||
|
||||
public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
|
||||
public async ValueTask EncodeAsync(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
|
||||
{
|
||||
if (symbol < Base.K_NUM_LOW_LEN_SYMBOLS)
|
||||
{
|
||||
_choice.Encode(rangeEncoder, 0);
|
||||
_lowCoder[posState].Encode(rangeEncoder, symbol);
|
||||
await _choice.EncodeAsync(rangeEncoder, 0);
|
||||
await _lowCoder[posState].EncodeAsync(rangeEncoder, symbol);
|
||||
}
|
||||
else
|
||||
{
|
||||
symbol -= Base.K_NUM_LOW_LEN_SYMBOLS;
|
||||
_choice.Encode(rangeEncoder, 1);
|
||||
await _choice.EncodeAsync(rangeEncoder, 1);
|
||||
if (symbol < Base.K_NUM_MID_LEN_SYMBOLS)
|
||||
{
|
||||
_choice2.Encode(rangeEncoder, 0);
|
||||
_midCoder[posState].Encode(rangeEncoder, symbol);
|
||||
await _choice2.EncodeAsync(rangeEncoder, 0);
|
||||
await _midCoder[posState].EncodeAsync(rangeEncoder, symbol);
|
||||
}
|
||||
else
|
||||
{
|
||||
_choice2.Encode(rangeEncoder, 1);
|
||||
_highCoder.Encode(rangeEncoder, symbol - Base.K_NUM_MID_LEN_SYMBOLS);
|
||||
await _choice2.EncodeAsync(rangeEncoder, 1);
|
||||
await _highCoder.EncodeAsync(rangeEncoder, symbol - Base.K_NUM_MID_LEN_SYMBOLS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -309,9 +311,9 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
|
||||
public new async ValueTask EncodeAsync(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
|
||||
{
|
||||
base.Encode(rangeEncoder, symbol, posState);
|
||||
await base.EncodeAsync(rangeEncoder, symbol, posState);
|
||||
if (--_counters[posState] == 0)
|
||||
{
|
||||
UpdateTable(posState);
|
||||
@@ -361,7 +363,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
private readonly Optimal[] _optimum = new Optimal[K_NUM_OPTS];
|
||||
private BinTree _matchFinder;
|
||||
private readonly RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder();
|
||||
private readonly RangeCoder.Encoder _rangeEncoder = new();
|
||||
|
||||
private readonly BitEncoder[] _isMatch =
|
||||
new BitEncoder[Base.K_NUM_STATES << Base.K_NUM_POS_STATES_BITS_MAX];
|
||||
@@ -379,12 +381,12 @@ namespace SharpCompress.Compressors.LZMA
|
||||
private readonly BitEncoder[] _posEncoders =
|
||||
new BitEncoder[Base.K_NUM_FULL_DISTANCES - Base.K_END_POS_MODEL_INDEX];
|
||||
|
||||
private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.K_NUM_ALIGN_BITS);
|
||||
private BitTreeEncoder _posAlignEncoder = new(Base.K_NUM_ALIGN_BITS);
|
||||
|
||||
private readonly LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();
|
||||
private readonly LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();
|
||||
private readonly LenPriceTableEncoder _lenEncoder = new();
|
||||
private readonly LenPriceTableEncoder _repMatchLenEncoder = new();
|
||||
|
||||
private readonly LiteralEncoder _literalEncoder = new LiteralEncoder();
|
||||
private readonly LiteralEncoder _literalEncoder = new();
|
||||
|
||||
private readonly UInt32[] _matchDistances = new UInt32[Base.K_MATCH_MAX_LEN * 2 + 2];
|
||||
|
||||
@@ -1189,40 +1191,40 @@ namespace SharpCompress.Compressors.LZMA
|
||||
return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif));
|
||||
}
|
||||
|
||||
private void WriteEndMarker(UInt32 posState)
|
||||
private async ValueTask WriteEndMarkerAsync(UInt32 posState)
|
||||
{
|
||||
if (!_writeEndMark)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isMatch[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].Encode(_rangeEncoder, 1);
|
||||
_isRep[_state._index].Encode(_rangeEncoder, 0);
|
||||
await _isMatch[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].EncodeAsync(_rangeEncoder, 1);
|
||||
await _isRep[_state._index].EncodeAsync(_rangeEncoder, 0);
|
||||
_state.UpdateMatch();
|
||||
UInt32 len = Base.K_MATCH_MIN_LEN;
|
||||
_lenEncoder.Encode(_rangeEncoder, len - Base.K_MATCH_MIN_LEN, posState);
|
||||
await _lenEncoder.EncodeAsync(_rangeEncoder, len - Base.K_MATCH_MIN_LEN, posState);
|
||||
UInt32 posSlot = (1 << Base.K_NUM_POS_SLOT_BITS) - 1;
|
||||
UInt32 lenToPosState = Base.GetLenToPosState(len);
|
||||
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
|
||||
await _posSlotEncoder[lenToPosState].EncodeAsync(_rangeEncoder, posSlot);
|
||||
int footerBits = 30;
|
||||
UInt32 posReduced = (((UInt32)1) << footerBits) - 1;
|
||||
_rangeEncoder.EncodeDirectBits(posReduced >> Base.K_NUM_ALIGN_BITS, footerBits - Base.K_NUM_ALIGN_BITS);
|
||||
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.K_ALIGN_MASK);
|
||||
await _rangeEncoder.EncodeDirectBits(posReduced >> Base.K_NUM_ALIGN_BITS, footerBits - Base.K_NUM_ALIGN_BITS);
|
||||
await _posAlignEncoder.ReverseEncodeAsync(_rangeEncoder, posReduced & Base.K_ALIGN_MASK);
|
||||
}
|
||||
|
||||
private void Flush(UInt32 nowPos)
|
||||
private async ValueTask FlushAsync(UInt32 nowPos)
|
||||
{
|
||||
ReleaseMfStream();
|
||||
WriteEndMarker(nowPos & _posStateMask);
|
||||
_rangeEncoder.FlushData();
|
||||
_rangeEncoder.FlushStream();
|
||||
await WriteEndMarkerAsync(nowPos & _posStateMask);
|
||||
await _rangeEncoder.FlushData();
|
||||
await _rangeEncoder.FlushAsync();
|
||||
}
|
||||
|
||||
public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished)
|
||||
public async ValueTask<(Int64, Int64, bool)> CodeOneBlockAsync()
|
||||
{
|
||||
inSize = 0;
|
||||
outSize = 0;
|
||||
finished = true;
|
||||
long inSize = 0;
|
||||
long outSize = 0;
|
||||
var finished = true;
|
||||
|
||||
if (_inStream != null)
|
||||
{
|
||||
@@ -1233,7 +1235,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
if (_finished)
|
||||
{
|
||||
return;
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
_finished = true;
|
||||
|
||||
@@ -1254,20 +1256,20 @@ namespace SharpCompress.Compressors.LZMA
|
||||
if (_processingMode && _matchFinder.IsDataStarved)
|
||||
{
|
||||
_finished = false;
|
||||
return;
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
if (_matchFinder.GetNumAvailableBytes() == 0)
|
||||
{
|
||||
Flush((UInt32)_nowPos64);
|
||||
return;
|
||||
await FlushAsync((UInt32)_nowPos64);
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
UInt32 len, numDistancePairs; // it's not used
|
||||
ReadMatchDistances(out len, out numDistancePairs);
|
||||
UInt32 posState = (UInt32)(_nowPos64) & _posStateMask;
|
||||
_isMatch[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].Encode(_rangeEncoder, 0);
|
||||
await _isMatch[(_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState].EncodeAsync(_rangeEncoder, 0);
|
||||
_state.UpdateChar();
|
||||
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
|
||||
_literalEncoder.GetSubCoder((UInt32)(_nowPos64), _previousByte).Encode(_rangeEncoder, curByte);
|
||||
await _literalEncoder.GetSubCoder((UInt32)(_nowPos64), _previousByte).EncodeAsync(_rangeEncoder, curByte);
|
||||
_previousByte = curByte;
|
||||
_additionalOffset--;
|
||||
_nowPos64++;
|
||||
@@ -1275,19 +1277,19 @@ namespace SharpCompress.Compressors.LZMA
|
||||
if (_processingMode && _matchFinder.IsDataStarved)
|
||||
{
|
||||
_finished = false;
|
||||
return;
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
if (_matchFinder.GetNumAvailableBytes() == 0)
|
||||
{
|
||||
Flush((UInt32)_nowPos64);
|
||||
return;
|
||||
await FlushAsync((UInt32)_nowPos64);
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
while (true)
|
||||
{
|
||||
if (_processingMode && _matchFinder.IsDataStarved)
|
||||
{
|
||||
_finished = false;
|
||||
return;
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
|
||||
UInt32 pos;
|
||||
@@ -1297,51 +1299,51 @@ namespace SharpCompress.Compressors.LZMA
|
||||
UInt32 complexState = (_state._index << Base.K_NUM_POS_STATES_BITS_MAX) + posState;
|
||||
if (len == 1 && pos == 0xFFFFFFFF)
|
||||
{
|
||||
_isMatch[complexState].Encode(_rangeEncoder, 0);
|
||||
await _isMatch[complexState].EncodeAsync(_rangeEncoder, 0);
|
||||
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
|
||||
LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)_nowPos64, _previousByte);
|
||||
if (!_state.IsCharState())
|
||||
{
|
||||
Byte matchByte =
|
||||
_matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset));
|
||||
subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte);
|
||||
await subCoder.EncodeMatchedAsync(_rangeEncoder, matchByte, curByte);
|
||||
}
|
||||
else
|
||||
{
|
||||
subCoder.Encode(_rangeEncoder, curByte);
|
||||
await subCoder.EncodeAsync(_rangeEncoder, curByte);
|
||||
}
|
||||
_previousByte = curByte;
|
||||
_state.UpdateChar();
|
||||
}
|
||||
else
|
||||
{
|
||||
_isMatch[complexState].Encode(_rangeEncoder, 1);
|
||||
await _isMatch[complexState].EncodeAsync(_rangeEncoder, 1);
|
||||
if (pos < Base.K_NUM_REP_DISTANCES)
|
||||
{
|
||||
_isRep[_state._index].Encode(_rangeEncoder, 1);
|
||||
await _isRep[_state._index].EncodeAsync(_rangeEncoder, 1);
|
||||
if (pos == 0)
|
||||
{
|
||||
_isRepG0[_state._index].Encode(_rangeEncoder, 0);
|
||||
await _isRepG0[_state._index].EncodeAsync(_rangeEncoder, 0);
|
||||
if (len == 1)
|
||||
{
|
||||
_isRep0Long[complexState].Encode(_rangeEncoder, 0);
|
||||
await _isRep0Long[complexState].EncodeAsync(_rangeEncoder, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
_isRep0Long[complexState].Encode(_rangeEncoder, 1);
|
||||
await _isRep0Long[complexState].EncodeAsync(_rangeEncoder, 1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_isRepG0[_state._index].Encode(_rangeEncoder, 1);
|
||||
await _isRepG0[_state._index].EncodeAsync(_rangeEncoder, 1);
|
||||
if (pos == 1)
|
||||
{
|
||||
_isRepG1[_state._index].Encode(_rangeEncoder, 0);
|
||||
await _isRepG1[_state._index].EncodeAsync(_rangeEncoder, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
_isRepG1[_state._index].Encode(_rangeEncoder, 1);
|
||||
_isRepG2[_state._index].Encode(_rangeEncoder, pos - 2);
|
||||
await _isRepG1[_state._index].EncodeAsync(_rangeEncoder, 1);
|
||||
await _isRepG2[_state._index].EncodeAsync(_rangeEncoder, pos - 2);
|
||||
}
|
||||
}
|
||||
if (len == 1)
|
||||
@@ -1350,7 +1352,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
else
|
||||
{
|
||||
_repMatchLenEncoder.Encode(_rangeEncoder, len - Base.K_MATCH_MIN_LEN, posState);
|
||||
await _repMatchLenEncoder.EncodeAsync(_rangeEncoder, len - Base.K_MATCH_MIN_LEN, posState);
|
||||
_state.UpdateRep();
|
||||
}
|
||||
UInt32 distance = _repDistances[pos];
|
||||
@@ -1365,13 +1367,13 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
else
|
||||
{
|
||||
_isRep[_state._index].Encode(_rangeEncoder, 0);
|
||||
await _isRep[_state._index].EncodeAsync(_rangeEncoder, 0);
|
||||
_state.UpdateMatch();
|
||||
_lenEncoder.Encode(_rangeEncoder, len - Base.K_MATCH_MIN_LEN, posState);
|
||||
await _lenEncoder.EncodeAsync(_rangeEncoder, len - Base.K_MATCH_MIN_LEN, posState);
|
||||
pos -= Base.K_NUM_REP_DISTANCES;
|
||||
UInt32 posSlot = GetPosSlot(pos);
|
||||
UInt32 lenToPosState = Base.GetLenToPosState(len);
|
||||
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
|
||||
await _posSlotEncoder[lenToPosState].EncodeAsync(_rangeEncoder, posSlot);
|
||||
|
||||
if (posSlot >= Base.K_START_POS_MODEL_INDEX)
|
||||
{
|
||||
@@ -1381,15 +1383,15 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
if (posSlot < Base.K_END_POS_MODEL_INDEX)
|
||||
{
|
||||
BitTreeEncoder.ReverseEncode(_posEncoders,
|
||||
baseVal - posSlot - 1, _rangeEncoder, footerBits,
|
||||
posReduced);
|
||||
await BitTreeEncoder.ReverseEncodeAsync(_posEncoders,
|
||||
baseVal - posSlot - 1, _rangeEncoder, footerBits,
|
||||
posReduced);
|
||||
}
|
||||
else
|
||||
{
|
||||
_rangeEncoder.EncodeDirectBits(posReduced >> Base.K_NUM_ALIGN_BITS,
|
||||
await _rangeEncoder.EncodeDirectBits(posReduced >> Base.K_NUM_ALIGN_BITS,
|
||||
footerBits - Base.K_NUM_ALIGN_BITS);
|
||||
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.K_ALIGN_MASK);
|
||||
await _posAlignEncoder.ReverseEncodeAsync(_rangeEncoder, posReduced & Base.K_ALIGN_MASK);
|
||||
_alignPriceCount++;
|
||||
}
|
||||
}
|
||||
@@ -1421,19 +1423,19 @@ namespace SharpCompress.Compressors.LZMA
|
||||
if (_processingMode && _matchFinder.IsDataStarved)
|
||||
{
|
||||
_finished = false;
|
||||
return;
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
if (_matchFinder.GetNumAvailableBytes() == 0)
|
||||
{
|
||||
Flush((UInt32)_nowPos64);
|
||||
return;
|
||||
await FlushAsync((UInt32)_nowPos64);
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
|
||||
if (_nowPos64 - progressPosValuePrev >= (1 << 12))
|
||||
{
|
||||
_finished = false;
|
||||
finished = false;
|
||||
return;
|
||||
return (inSize, outSize, finished);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1488,8 +1490,8 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_nowPos64 = 0;
|
||||
}
|
||||
|
||||
public void Code(Stream inStream, Stream outStream,
|
||||
Int64 inSize, Int64 outSize, ICodeProgress progress)
|
||||
public async ValueTask CodeAsync(Stream inStream, Stream outStream,
|
||||
Int64 inSize, Int64 outSize, ICodeProgress progress, CancellationToken cancellationToken)
|
||||
{
|
||||
_needReleaseMfStream = false;
|
||||
_processingMode = false;
|
||||
@@ -1498,10 +1500,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
SetStreams(inStream, outStream, inSize, outSize);
|
||||
while (true)
|
||||
{
|
||||
Int64 processedInSize;
|
||||
Int64 processedOutSize;
|
||||
bool finished;
|
||||
CodeOneBlock(out processedInSize, out processedOutSize, out finished);
|
||||
var (processedInSize, processedOutSize, finished) = await CodeOneBlockAsync();
|
||||
if (finished)
|
||||
{
|
||||
return;
|
||||
@@ -1518,7 +1517,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
}
|
||||
}
|
||||
|
||||
public long Code(Stream inStream, bool final)
|
||||
public async ValueTask<long> CodeAsync(Stream inStream, bool final)
|
||||
{
|
||||
_matchFinder.SetStream(inStream);
|
||||
_processingMode = !final;
|
||||
@@ -1526,10 +1525,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Int64 processedInSize;
|
||||
Int64 processedOutSize;
|
||||
bool finished;
|
||||
CodeOneBlock(out processedInSize, out processedOutSize, out finished);
|
||||
var (processedInSize, processedOutSize, finished) = await CodeOneBlockAsync();
|
||||
if (finished)
|
||||
{
|
||||
return processedInSize;
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors.LZMA.LZ;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
public class LzmaStream : Stream
|
||||
public class LzmaStream : AsyncStream
|
||||
{
|
||||
private readonly Stream _inputStream;
|
||||
private readonly long _inputSize;
|
||||
private readonly long _outputSize;
|
||||
private Stream _inputStream;
|
||||
private long _inputSize;
|
||||
private long _outputSize;
|
||||
|
||||
private readonly int _dictionarySize;
|
||||
private readonly OutWindow _outWindow = new OutWindow();
|
||||
private readonly RangeCoder.Decoder _rangeDecoder = new RangeCoder.Decoder();
|
||||
private int _dictionarySize;
|
||||
private OutWindow _outWindow = new OutWindow();
|
||||
private RangeCoder.Decoder _rangeDecoder = new RangeCoder.Decoder();
|
||||
private Decoder _decoder;
|
||||
|
||||
private long _position;
|
||||
@@ -25,70 +29,60 @@ namespace SharpCompress.Compressors.LZMA
|
||||
private long _inputPosition;
|
||||
|
||||
// LZMA2
|
||||
private readonly bool _isLzma2;
|
||||
private bool _isLzma2;
|
||||
private bool _uncompressedChunk;
|
||||
private bool _needDictReset = true;
|
||||
private bool _needProps = true;
|
||||
|
||||
private readonly Encoder _encoder;
|
||||
private bool _isDisposed;
|
||||
|
||||
private LzmaStream() {}
|
||||
|
||||
public LzmaStream(byte[] properties, Stream inputStream)
|
||||
: this(properties, inputStream, -1, -1, null, properties.Length < 5)
|
||||
public static async ValueTask<LzmaStream> CreateAsync(byte[] properties, Stream inputStream, long inputSize = -1, long outputSize = -1,
|
||||
Stream presetDictionary = null, bool? isLzma2 = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
}
|
||||
var ls = new LzmaStream();
|
||||
ls._inputStream = inputStream;
|
||||
ls._inputSize = inputSize;
|
||||
ls._outputSize = outputSize;
|
||||
ls._isLzma2 = isLzma2 ?? properties.Length < 5;
|
||||
|
||||
public LzmaStream(byte[] properties, Stream inputStream, long inputSize)
|
||||
: this(properties, inputStream, inputSize, -1, null, properties.Length < 5)
|
||||
{
|
||||
}
|
||||
|
||||
public LzmaStream(byte[] properties, Stream inputStream, long inputSize, long outputSize)
|
||||
: this(properties, inputStream, inputSize, outputSize, null, properties.Length < 5)
|
||||
{
|
||||
}
|
||||
|
||||
public LzmaStream(byte[] properties, Stream inputStream, long inputSize, long outputSize,
|
||||
Stream presetDictionary, bool isLzma2)
|
||||
{
|
||||
_inputStream = inputStream;
|
||||
_inputSize = inputSize;
|
||||
_outputSize = outputSize;
|
||||
_isLzma2 = isLzma2;
|
||||
|
||||
if (!isLzma2)
|
||||
if (!ls._isLzma2)
|
||||
{
|
||||
_dictionarySize = BinaryPrimitives.ReadInt32LittleEndian(properties.AsSpan(1));
|
||||
_outWindow.Create(_dictionarySize);
|
||||
ls._dictionarySize = BinaryPrimitives.ReadInt32LittleEndian(properties.AsSpan(1));
|
||||
ls._outWindow.Create(ls._dictionarySize);
|
||||
if (presetDictionary != null)
|
||||
{
|
||||
_outWindow.Train(presetDictionary);
|
||||
ls._outWindow.Train(presetDictionary);
|
||||
}
|
||||
|
||||
_rangeDecoder.Init(inputStream);
|
||||
await ls._rangeDecoder.InitAsync(inputStream, cancellationToken);
|
||||
|
||||
_decoder = new Decoder();
|
||||
_decoder.SetDecoderProperties(properties);
|
||||
Properties = properties;
|
||||
ls._decoder = new Decoder();
|
||||
ls._decoder.SetDecoderProperties(properties);
|
||||
ls.Properties = properties;
|
||||
|
||||
_availableBytes = outputSize < 0 ? long.MaxValue : outputSize;
|
||||
_rangeDecoderLimit = inputSize;
|
||||
ls._availableBytes = outputSize < 0 ? long.MaxValue : outputSize;
|
||||
ls._rangeDecoderLimit = inputSize;
|
||||
}
|
||||
else
|
||||
{
|
||||
_dictionarySize = 2 | (properties[0] & 1);
|
||||
_dictionarySize <<= (properties[0] >> 1) + 11;
|
||||
ls. _dictionarySize = 2 | (properties[0] & 1);
|
||||
ls. _dictionarySize <<= (properties[0] >> 1) + 11;
|
||||
|
||||
_outWindow.Create(_dictionarySize);
|
||||
ls._outWindow.Create(ls._dictionarySize);
|
||||
if (presetDictionary != null)
|
||||
{
|
||||
_outWindow.Train(presetDictionary);
|
||||
_needDictReset = false;
|
||||
ls._outWindow.Train(presetDictionary);
|
||||
ls._needDictReset = false;
|
||||
}
|
||||
|
||||
Properties = new byte[1];
|
||||
_availableBytes = 0;
|
||||
ls. Properties = new byte[1];
|
||||
ls._availableBytes = 0;
|
||||
}
|
||||
|
||||
return ls;
|
||||
}
|
||||
|
||||
public LzmaStream(LzmaEncoderProperties properties, bool isLzma2, Stream outputStream)
|
||||
@@ -126,33 +120,25 @@ namespace SharpCompress.Compressors.LZMA
|
||||
|
||||
public override bool CanWrite => _encoder != null;
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_isDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_isDisposed = true;
|
||||
if (disposing)
|
||||
if (_encoder != null)
|
||||
{
|
||||
if (_encoder != null)
|
||||
{
|
||||
_position = _encoder.Code(null, true);
|
||||
}
|
||||
_inputStream?.Dispose();
|
||||
_position = await _encoder.CodeAsync(null, true);
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
_inputStream?.DisposeAsync();
|
||||
}
|
||||
|
||||
public override long Length => _position + _availableBytes;
|
||||
|
||||
public override long Position { get => _position; set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_endReached)
|
||||
{
|
||||
@@ -166,7 +152,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
if (_isLzma2)
|
||||
{
|
||||
DecodeChunkHeader();
|
||||
await DecodeChunkHeader(cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -189,7 +175,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
_inputPosition += _outWindow.CopyStream(_inputStream, toProcess);
|
||||
}
|
||||
else if (_decoder.Code(_dictionarySize, _outWindow, _rangeDecoder)
|
||||
else if (await _decoder.CodeAsync(_dictionarySize, _outWindow, _rangeDecoder, cancellationToken)
|
||||
&& _outputSize < 0)
|
||||
{
|
||||
_availableBytes = _outWindow.AvailableBytes;
|
||||
@@ -231,7 +217,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
return total;
|
||||
}
|
||||
|
||||
private void DecodeChunkHeader()
|
||||
private async ValueTask DecodeChunkHeader(CancellationToken cancellationToken)
|
||||
{
|
||||
int control = _inputStream.ReadByte();
|
||||
_inputPosition++;
|
||||
@@ -283,7 +269,7 @@ namespace SharpCompress.Compressors.LZMA
|
||||
_decoder.SetDecoderProperties(Properties);
|
||||
}
|
||||
|
||||
_rangeDecoder.Init(_inputStream);
|
||||
await _rangeDecoder.InitAsync(_inputStream, cancellationToken);
|
||||
}
|
||||
else if (control > 0x02)
|
||||
{
|
||||
@@ -307,14 +293,25 @@ namespace SharpCompress.Compressors.LZMA
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_encoder != null)
|
||||
{
|
||||
_position = _encoder.Code(new MemoryStream(buffer, offset, count), false);
|
||||
_position = await _encoder.CodeAsync(new MemoryStream(buffer, offset, count), false);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] Properties { get; } = new byte[5];
|
||||
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
if (_encoder != null)
|
||||
{
|
||||
var m = ArrayPool<byte>.Shared.Rent(buffer.Length);
|
||||
buffer.CopyTo(m.AsMemory().Slice(0, buffer.Length));
|
||||
_position = await _encoder.CodeAsync(new MemoryStream(m, 0, buffer.Length), false);
|
||||
ArrayPool<byte>.Shared.Return(m);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] Properties { get; private set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
{
|
||||
internal class Encoder
|
||||
internal class Encoder : IAsyncDisposable
|
||||
{
|
||||
public const uint K_TOP_VALUE = (1 << 24);
|
||||
|
||||
@@ -38,43 +41,46 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_cache = 0;
|
||||
}
|
||||
|
||||
public void FlushData()
|
||||
public async ValueTask FlushData()
|
||||
{
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
ShiftLow();
|
||||
await ShiftLowAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public void FlushStream()
|
||||
public Task FlushAsync()
|
||||
{
|
||||
_stream.Flush();
|
||||
return _stream.FlushAsync();
|
||||
}
|
||||
|
||||
public void CloseStream()
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
_stream.Dispose();
|
||||
return _stream.DisposeAsync();
|
||||
}
|
||||
|
||||
public void Encode(uint start, uint size, uint total)
|
||||
public async ValueTask EncodeAsync(uint start, uint size, uint total)
|
||||
{
|
||||
_low += start * (_range /= total);
|
||||
_range *= size;
|
||||
while (_range < K_TOP_VALUE)
|
||||
{
|
||||
_range <<= 8;
|
||||
ShiftLow();
|
||||
await ShiftLowAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public void ShiftLow()
|
||||
public async ValueTask ShiftLowAsync()
|
||||
{
|
||||
if ((uint)_low < 0xFF000000 || (uint)(_low >> 32) == 1)
|
||||
{
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(1);
|
||||
var b = buffer.Memory.Slice(0,1);
|
||||
byte temp = _cache;
|
||||
do
|
||||
{
|
||||
_stream.WriteByte((byte)(temp + (_low >> 32)));
|
||||
b.Span[0] = (byte)(temp + (_low >> 32));
|
||||
await _stream.WriteAsync(b);
|
||||
temp = 0xFF;
|
||||
}
|
||||
while (--_cacheSize != 0);
|
||||
@@ -84,7 +90,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_low = ((uint)_low) << 8;
|
||||
}
|
||||
|
||||
public void EncodeDirectBits(uint v, int numTotalBits)
|
||||
public async ValueTask EncodeDirectBits(uint v, int numTotalBits)
|
||||
{
|
||||
for (int i = numTotalBits - 1; i >= 0; i--)
|
||||
{
|
||||
@@ -96,12 +102,12 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
if (_range < K_TOP_VALUE)
|
||||
{
|
||||
_range <<= 8;
|
||||
ShiftLow();
|
||||
await ShiftLowAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void EncodeBit(uint size0, int numTotalBits, uint symbol)
|
||||
public async ValueTask EncodeBitAsync(uint size0, int numTotalBits, uint symbol)
|
||||
{
|
||||
uint newBound = (_range >> numTotalBits) * size0;
|
||||
if (symbol == 0)
|
||||
@@ -116,7 +122,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
while (_range < K_TOP_VALUE)
|
||||
{
|
||||
_range <<= 8;
|
||||
ShiftLow();
|
||||
await ShiftLowAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +135,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
}
|
||||
}
|
||||
|
||||
internal class Decoder
|
||||
internal class Decoder: IAsyncDisposable
|
||||
{
|
||||
public const uint K_TOP_VALUE = (1 << 24);
|
||||
public uint _range;
|
||||
@@ -139,7 +145,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
public Stream _stream;
|
||||
public long _total;
|
||||
|
||||
public void Init(Stream stream)
|
||||
public async ValueTask InitAsync(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
// Stream.Init(stream);
|
||||
_stream = stream;
|
||||
@@ -148,7 +154,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_range = 0xFFFFFFFF;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
_code = (_code << 8) | (byte)_stream.ReadByte();
|
||||
_code = (_code << 8) | await _stream.ReadByteAsync(cancellationToken);
|
||||
}
|
||||
_total = 5;
|
||||
}
|
||||
@@ -159,44 +165,34 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_stream = null;
|
||||
}
|
||||
|
||||
public void CloseStream()
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
_stream.Dispose();
|
||||
return _stream.DisposeAsync();
|
||||
}
|
||||
|
||||
public void Normalize()
|
||||
public async ValueTask NormalizeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (_range < K_TOP_VALUE)
|
||||
{
|
||||
_code = (_code << 8) | (byte)_stream.ReadByte();
|
||||
_code = (_code << 8) | await _stream.ReadByteAsync(cancellationToken);
|
||||
_range <<= 8;
|
||||
_total++;
|
||||
}
|
||||
}
|
||||
|
||||
public void Normalize2()
|
||||
{
|
||||
if (_range < K_TOP_VALUE)
|
||||
{
|
||||
_code = (_code << 8) | (byte)_stream.ReadByte();
|
||||
_range <<= 8;
|
||||
_total++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public uint GetThreshold(uint total)
|
||||
{
|
||||
return _code / (_range /= total);
|
||||
}
|
||||
|
||||
public void Decode(uint start, uint size)
|
||||
public async ValueTask DecodeAsync(uint start, uint size, CancellationToken cancellationToken)
|
||||
{
|
||||
_code -= start * _range;
|
||||
_range *= size;
|
||||
Normalize();
|
||||
await NormalizeAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public uint DecodeDirectBits(int numTotalBits)
|
||||
public async ValueTask<uint> DecodeDirectBitsAsync(int numTotalBits, CancellationToken cancellationToken)
|
||||
{
|
||||
uint range = _range;
|
||||
uint code = _code;
|
||||
@@ -218,7 +214,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
|
||||
if (range < K_TOP_VALUE)
|
||||
{
|
||||
code = (code << 8) | (byte)_stream.ReadByte();
|
||||
code = (code << 8) | await _stream.ReadByteAsync(cancellationToken);
|
||||
range <<= 8;
|
||||
_total++;
|
||||
}
|
||||
@@ -228,7 +224,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
return result;
|
||||
}
|
||||
|
||||
public uint DecodeBit(uint size0, int numTotalBits)
|
||||
public async ValueTask<uint> DecodeBitAsync(uint size0, int numTotalBits, CancellationToken cancellationToken)
|
||||
{
|
||||
uint newBound = (_range >> numTotalBits) * size0;
|
||||
uint symbol;
|
||||
@@ -243,7 +239,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_code -= newBound;
|
||||
_range -= newBound;
|
||||
}
|
||||
Normalize();
|
||||
await NormalizeAsync(cancellationToken);
|
||||
return symbol;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
{
|
||||
@@ -29,7 +32,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
}
|
||||
}
|
||||
|
||||
public void Encode(Encoder encoder, uint symbol)
|
||||
public async ValueTask EncodeAsync(Encoder encoder, uint symbol)
|
||||
{
|
||||
// encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol);
|
||||
// UpdateModel(symbol);
|
||||
@@ -48,7 +51,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
if (encoder._range < Encoder.K_TOP_VALUE)
|
||||
{
|
||||
encoder._range <<= 8;
|
||||
encoder.ShiftLow();
|
||||
await encoder.ShiftLowAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +113,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_prob = K_BIT_MODEL_TOTAL >> 1;
|
||||
}
|
||||
|
||||
public uint Decode(Decoder rangeDecoder)
|
||||
public async ValueTask<uint> DecodeAsync(Decoder rangeDecoder, CancellationToken cancellationToken)
|
||||
{
|
||||
uint newBound = (rangeDecoder._range >> K_NUM_BIT_MODEL_TOTAL_BITS) * _prob;
|
||||
if (rangeDecoder._code < newBound)
|
||||
@@ -119,7 +122,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_prob += (K_BIT_MODEL_TOTAL - _prob) >> K_NUM_MOVE_BITS;
|
||||
if (rangeDecoder._range < Decoder.K_TOP_VALUE)
|
||||
{
|
||||
rangeDecoder._code = (rangeDecoder._code << 8) | (byte)rangeDecoder._stream.ReadByte();
|
||||
rangeDecoder._code = (rangeDecoder._code << 8) | await rangeDecoder._stream.ReadByteAsync(cancellationToken);
|
||||
rangeDecoder._range <<= 8;
|
||||
rangeDecoder._total++;
|
||||
}
|
||||
@@ -130,7 +133,7 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
_prob -= (_prob) >> K_NUM_MOVE_BITS;
|
||||
if (rangeDecoder._range < Decoder.K_TOP_VALUE)
|
||||
{
|
||||
rangeDecoder._code = (rangeDecoder._code << 8) | (byte)rangeDecoder._stream.ReadByte();
|
||||
rangeDecoder._code = (rangeDecoder._code << 8) | await rangeDecoder._stream.ReadByteAsync(cancellationToken);
|
||||
rangeDecoder._range <<= 8;
|
||||
rangeDecoder._total++;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
{
|
||||
@@ -21,25 +23,25 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
}
|
||||
}
|
||||
|
||||
public void Encode(Encoder rangeEncoder, UInt32 symbol)
|
||||
public async ValueTask EncodeAsync(Encoder rangeEncoder, UInt32 symbol)
|
||||
{
|
||||
UInt32 m = 1;
|
||||
for (int bitIndex = _numBitLevels; bitIndex > 0;)
|
||||
{
|
||||
bitIndex--;
|
||||
UInt32 bit = (symbol >> bitIndex) & 1;
|
||||
_models[m].Encode(rangeEncoder, bit);
|
||||
await _models[m].EncodeAsync(rangeEncoder, bit);
|
||||
m = (m << 1) | bit;
|
||||
}
|
||||
}
|
||||
|
||||
public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol)
|
||||
public async ValueTask ReverseEncodeAsync(Encoder rangeEncoder, UInt32 symbol)
|
||||
{
|
||||
UInt32 m = 1;
|
||||
for (UInt32 i = 0; i < _numBitLevels; i++)
|
||||
{
|
||||
UInt32 bit = symbol & 1;
|
||||
_models[m].Encode(rangeEncoder, bit);
|
||||
await _models[m].EncodeAsync(rangeEncoder, bit);
|
||||
m = (m << 1) | bit;
|
||||
symbol >>= 1;
|
||||
}
|
||||
@@ -88,14 +90,14 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
return price;
|
||||
}
|
||||
|
||||
public static void ReverseEncode(BitEncoder[] models, UInt32 startIndex,
|
||||
public static async ValueTask ReverseEncodeAsync(BitEncoder[] models, UInt32 startIndex,
|
||||
Encoder rangeEncoder, int numBitLevels, UInt32 symbol)
|
||||
{
|
||||
UInt32 m = 1;
|
||||
for (int i = 0; i < numBitLevels; i++)
|
||||
{
|
||||
UInt32 bit = symbol & 1;
|
||||
models[startIndex + m].Encode(rangeEncoder, bit);
|
||||
await models[startIndex + m].EncodeAsync(rangeEncoder, bit);
|
||||
m = (m << 1) | bit;
|
||||
symbol >>= 1;
|
||||
}
|
||||
@@ -121,23 +123,23 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
}
|
||||
}
|
||||
|
||||
public uint Decode(Decoder rangeDecoder)
|
||||
public async ValueTask<uint> DecodeAsync(Decoder rangeDecoder, CancellationToken cancellationToken)
|
||||
{
|
||||
uint m = 1;
|
||||
for (int bitIndex = _numBitLevels; bitIndex > 0; bitIndex--)
|
||||
{
|
||||
m = (m << 1) + _models[m].Decode(rangeDecoder);
|
||||
m = (m << 1) + await _models[m].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
}
|
||||
return m - ((uint)1 << _numBitLevels);
|
||||
}
|
||||
|
||||
public uint ReverseDecode(Decoder rangeDecoder)
|
||||
public async ValueTask<uint> ReverseDecode(Decoder rangeDecoder, CancellationToken cancellationToken)
|
||||
{
|
||||
uint m = 1;
|
||||
uint symbol = 0;
|
||||
for (int bitIndex = 0; bitIndex < _numBitLevels; bitIndex++)
|
||||
{
|
||||
uint bit = _models[m].Decode(rangeDecoder);
|
||||
uint bit = await _models[m].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
m <<= 1;
|
||||
m += bit;
|
||||
symbol |= (bit << bitIndex);
|
||||
@@ -145,14 +147,14 @@ namespace SharpCompress.Compressors.LZMA.RangeCoder
|
||||
return symbol;
|
||||
}
|
||||
|
||||
public static uint ReverseDecode(BitDecoder[] models, UInt32 startIndex,
|
||||
Decoder rangeDecoder, int numBitLevels)
|
||||
public static async ValueTask<uint> ReverseDecode(BitDecoder[] models, UInt32 startIndex,
|
||||
Decoder rangeDecoder, int numBitLevels, CancellationToken cancellationToken)
|
||||
{
|
||||
uint m = 1;
|
||||
uint symbol = 0;
|
||||
for (int bitIndex = 0; bitIndex < numBitLevels; bitIndex++)
|
||||
{
|
||||
uint bit = models[startIndex + m].Decode(rangeDecoder);
|
||||
uint bit = await models[startIndex + m].DecodeAsync(rangeDecoder, cancellationToken);
|
||||
m <<= 1;
|
||||
m += bit;
|
||||
symbol |= (bit << bitIndex);
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common.SevenZip;
|
||||
using SharpCompress.Compressors.BZip2;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
using SharpCompress.Compressors.Filters;
|
||||
using SharpCompress.Compressors.LZMA.Utilites;
|
||||
using SharpCompress.Compressors.PPMd;
|
||||
//using SharpCompress.Compressors.PPMd;
|
||||
|
||||
namespace SharpCompress.Compressors.LZMA
|
||||
{
|
||||
@@ -22,9 +24,10 @@ namespace SharpCompress.Compressors.LZMA
|
||||
private const uint K_DEFLATE = 0x040108;
|
||||
private const uint K_B_ZIP2 = 0x040202;
|
||||
|
||||
internal static Stream CreateDecoderStream(CMethodId id, Stream[] inStreams, byte[] info, IPasswordProvider pass,
|
||||
long limit)
|
||||
internal static async ValueTask<Stream> CreateDecoderStream(CMethodId id, Stream[] inStreams, byte[] info, IPasswordProvider pass,
|
||||
long limit, CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
switch (id._id)
|
||||
{
|
||||
case K_COPY:
|
||||
@@ -35,17 +38,17 @@ namespace SharpCompress.Compressors.LZMA
|
||||
return inStreams.Single();
|
||||
case K_LZMA:
|
||||
case K_LZMA2:
|
||||
return new LzmaStream(info, inStreams.Single(), -1, limit);
|
||||
return await LzmaStream.CreateAsync(info, inStreams.Single(), -1, limit, cancellationToken: cancellationToken);
|
||||
case CMethodId.K_AES_ID:
|
||||
return new AesDecoderStream(inStreams.Single(), info, pass, limit);
|
||||
case K_BCJ:
|
||||
return new BCJFilter(false, inStreams.Single());
|
||||
case K_BCJ2:
|
||||
return new Bcj2DecoderStream(inStreams, info, limit);
|
||||
case K_B_ZIP2:
|
||||
return new BZip2Stream(inStreams.Single(), CompressionMode.Decompress, true);
|
||||
case K_PPMD:
|
||||
return new PpmdStream(new PpmdProperties(info), inStreams.Single(), false);
|
||||
/* case K_B_ZIP2:
|
||||
return await BZip2Stream.CreateAsync(inStreams.Single(), CompressionMode.Decompress, true, cancellationToken);
|
||||
case K_PPMD:
|
||||
return new PpmdStream(new PpmdProperties(info), inStreams.Single(), false);*/
|
||||
case K_DEFLATE:
|
||||
return new DeflateStream(inStreams.Single(), CompressionMode.Decompress);
|
||||
default:
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Rar;
|
||||
|
||||
@@ -13,7 +15,7 @@ namespace SharpCompress.Compressors.Rar
|
||||
private long currentPosition;
|
||||
private long maxPosition;
|
||||
|
||||
private IEnumerator<RarFilePart> filePartEnumerator;
|
||||
private IAsyncEnumerator<RarFilePart> filePartEnumerator;
|
||||
private Stream currentStream;
|
||||
|
||||
private readonly IExtractionListener streamListener;
|
||||
@@ -21,34 +23,33 @@ namespace SharpCompress.Compressors.Rar
|
||||
private long currentPartTotalReadBytes;
|
||||
private long currentEntryTotalReadBytes;
|
||||
|
||||
internal MultiVolumeReadOnlyStream(IEnumerable<RarFilePart> parts, IExtractionListener streamListener)
|
||||
internal MultiVolumeReadOnlyStream(IExtractionListener streamListener)
|
||||
{
|
||||
this.streamListener = streamListener;
|
||||
|
||||
filePartEnumerator = parts.GetEnumerator();
|
||||
filePartEnumerator.MoveNext();
|
||||
InitializeNextFilePart();
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
internal async ValueTask Initialize(IAsyncEnumerable<RarFilePart> parts, CancellationToken cancellationToken)
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
if (disposing)
|
||||
{
|
||||
if (filePartEnumerator != null)
|
||||
{
|
||||
filePartEnumerator.Dispose();
|
||||
filePartEnumerator = null;
|
||||
}
|
||||
currentStream = null;
|
||||
}
|
||||
filePartEnumerator = parts.GetAsyncEnumerator(cancellationToken);
|
||||
await filePartEnumerator.MoveNextAsync(cancellationToken);
|
||||
await InitializeNextFilePartAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private void InitializeNextFilePart()
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (filePartEnumerator != null)
|
||||
{
|
||||
await filePartEnumerator.DisposeAsync();
|
||||
filePartEnumerator = null;
|
||||
}
|
||||
currentStream = null;
|
||||
}
|
||||
|
||||
private async ValueTask InitializeNextFilePartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
maxPosition = filePartEnumerator.Current.FileHeader.CompressedSize;
|
||||
currentPosition = 0;
|
||||
currentStream = filePartEnumerator.Current.GetCompressedStream();
|
||||
currentStream = await filePartEnumerator.Current.GetCompressedStreamAsync(cancellationToken);
|
||||
|
||||
currentPartTotalReadBytes = 0;
|
||||
|
||||
@@ -60,10 +61,15 @@ namespace SharpCompress.Compressors.Rar
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
|
||||
{
|
||||
int totalRead = 0;
|
||||
int currentOffset = offset;
|
||||
int currentCount = count;
|
||||
int currentOffset = 0;
|
||||
int currentCount = buffer.Length;
|
||||
while (currentCount > 0)
|
||||
{
|
||||
int readSize = currentCount;
|
||||
@@ -72,7 +78,7 @@ namespace SharpCompress.Compressors.Rar
|
||||
readSize = (int)(maxPosition - currentPosition);
|
||||
}
|
||||
|
||||
int read = currentStream.Read(buffer, currentOffset, readSize);
|
||||
int read = await currentStream.ReadAsync(buffer.Slice(currentOffset, readSize), cancellationToken);
|
||||
if (read < 0)
|
||||
{
|
||||
throw new EndOfStreamException();
|
||||
@@ -90,12 +96,12 @@ namespace SharpCompress.Compressors.Rar
|
||||
throw new InvalidFormatException("Sharpcompress currently does not support multi-volume decryption.");
|
||||
}
|
||||
string fileName = filePartEnumerator.Current.FileHeader.FileName;
|
||||
if (!filePartEnumerator.MoveNext())
|
||||
if (!await filePartEnumerator.MoveNextAsync(cancellationToken))
|
||||
{
|
||||
throw new InvalidFormatException(
|
||||
"Multi-part rar file is incomplete. Entry expects a new volume: " + fileName);
|
||||
}
|
||||
InitializeNextFilePart();
|
||||
await InitializeNextFilePartAsync(cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz
|
||||
{
|
||||
@@ -16,20 +19,21 @@ namespace SharpCompress.Compressors.Xz
|
||||
{
|
||||
return unchecked((uint)ReadLittleEndianInt32(reader));
|
||||
}
|
||||
public static int ReadLittleEndianInt32(this Stream stream)
|
||||
public static async ValueTask<int> ReadLittleEndianInt32(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[4];
|
||||
var read = stream.ReadFully(bytes);
|
||||
if (!read)
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(4);
|
||||
var slice = buffer.Memory.Slice(0, 4);
|
||||
var read = await stream.ReadAsync(slice, cancellationToken);
|
||||
if (read != 4)
|
||||
{
|
||||
throw new EndOfStreamException();
|
||||
}
|
||||
return BinaryPrimitives.ReadInt32LittleEndian(bytes);
|
||||
return BinaryPrimitives.ReadInt32LittleEndian(slice.Span);
|
||||
}
|
||||
|
||||
internal static uint ReadLittleEndianUInt32(this Stream stream)
|
||||
internal static async ValueTask<uint> ReadLittleEndianUInt32(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return unchecked((uint)ReadLittleEndianInt32(stream));
|
||||
return unchecked((uint)await ReadLittleEndianInt32(stream, cancellationToken));
|
||||
}
|
||||
|
||||
internal static byte[] ToBigEndianBytes(this uint uint32)
|
||||
|
||||
@@ -11,19 +11,19 @@ namespace SharpCompress.Compressors.Xz
|
||||
|
||||
private static UInt32[] defaultTable;
|
||||
|
||||
public static UInt32 Compute(byte[] buffer)
|
||||
public static UInt32 Compute(ReadOnlyMemory<byte> buffer)
|
||||
{
|
||||
return Compute(DefaultSeed, buffer);
|
||||
}
|
||||
|
||||
public static UInt32 Compute(UInt32 seed, byte[] buffer)
|
||||
public static UInt32 Compute(UInt32 seed, ReadOnlyMemory<byte> buffer)
|
||||
{
|
||||
return Compute(DefaultPolynomial, seed, buffer);
|
||||
}
|
||||
|
||||
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
|
||||
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, ReadOnlyMemory<byte> buffer)
|
||||
{
|
||||
return ~CalculateHash(InitializeTable(polynomial), seed, buffer);
|
||||
return ~CalculateHash(InitializeTable(polynomial), seed, buffer.Span);
|
||||
}
|
||||
|
||||
private static UInt32[] InitializeTable(UInt32 polynomial)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz.Filters
|
||||
{
|
||||
@@ -52,6 +53,6 @@ namespace SharpCompress.Compressors.Xz.Filters
|
||||
return filter;
|
||||
}
|
||||
|
||||
public abstract void SetBaseStream(Stream stream);
|
||||
public abstract ValueTask SetBaseStreamAsync(Stream stream);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors.LZMA;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz.Filters
|
||||
@@ -49,19 +51,14 @@ namespace SharpCompress.Compressors.Xz.Filters
|
||||
{
|
||||
}
|
||||
|
||||
public override void SetBaseStream(Stream stream)
|
||||
public override async ValueTask SetBaseStreamAsync(Stream stream)
|
||||
{
|
||||
BaseStream = new LzmaStream(new[] { _dictionarySize }, stream);
|
||||
BaseStream = await LzmaStream.CreateAsync(new[] { _dictionarySize }, stream);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return BaseStream.Read(buffer, offset, count);
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
{
|
||||
return BaseStream.ReadByte();
|
||||
return BaseStream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz
|
||||
{
|
||||
public abstract class ReadOnlyStream : Stream
|
||||
public abstract class ReadOnlyStream : AsyncStream
|
||||
{
|
||||
public Stream BaseStream { get; protected set; }
|
||||
|
||||
@@ -23,11 +26,6 @@ namespace SharpCompress.Compressors.Xz
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
@@ -38,7 +36,12 @@ namespace SharpCompress.Compressors.Xz
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override ValueTask DisposeAsync()
|
||||
{
|
||||
return new();
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors.Xz.Filters;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz
|
||||
@@ -19,7 +21,7 @@ namespace SharpCompress.Compressors.Xz
|
||||
private bool _streamConnected;
|
||||
private int _numFilters;
|
||||
private byte _blockHeaderSizeByte;
|
||||
private Stream _decomStream;
|
||||
private Stream? _decomStream;
|
||||
private bool _endOfStream;
|
||||
private bool _paddingSkipped;
|
||||
private bool _crcChecked;
|
||||
@@ -32,25 +34,25 @@ namespace SharpCompress.Compressors.Xz
|
||||
_checkSize = checkSize;
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
int bytesRead = 0;
|
||||
if (!HeaderIsLoaded)
|
||||
{
|
||||
LoadHeader();
|
||||
await LoadHeader(cancellationToken);
|
||||
}
|
||||
|
||||
if (!_streamConnected)
|
||||
{
|
||||
ConnectStream();
|
||||
await ConnectStreamAsync();
|
||||
}
|
||||
|
||||
if (!_endOfStream)
|
||||
if (!_endOfStream && _decomStream is not null)
|
||||
{
|
||||
bytesRead = _decomStream.Read(buffer, offset, count);
|
||||
bytesRead = await _decomStream.ReadAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
if (bytesRead != count)
|
||||
if (bytesRead != buffer.Length)
|
||||
{
|
||||
_endOfStream = true;
|
||||
}
|
||||
@@ -93,24 +95,27 @@ namespace SharpCompress.Compressors.Xz
|
||||
_crcChecked = true;
|
||||
}
|
||||
|
||||
private void ConnectStream()
|
||||
private async ValueTask ConnectStreamAsync()
|
||||
{
|
||||
_decomStream = BaseStream;
|
||||
while (Filters.Any())
|
||||
{
|
||||
BlockFilter filter = Filters.Pop();
|
||||
filter.SetBaseStream(_decomStream);
|
||||
await filter.SetBaseStreamAsync(_decomStream);
|
||||
_decomStream = filter;
|
||||
}
|
||||
_streamConnected = true;
|
||||
}
|
||||
|
||||
private void LoadHeader()
|
||||
private async ValueTask LoadHeader(CancellationToken cancellationToken)
|
||||
{
|
||||
ReadHeaderSize();
|
||||
byte[] headerCache = CacheHeader();
|
||||
await ReadHeaderSize(cancellationToken);
|
||||
using var blockHeaderWithoutCrc = MemoryPool<byte>.Shared.Rent(BlockHeaderSize - 4);
|
||||
var headerCache = blockHeaderWithoutCrc.Memory.Slice(0, BlockHeaderSize - 4);
|
||||
await CacheHeader(headerCache, cancellationToken);
|
||||
|
||||
using (var cache = new MemoryStream(headerCache))
|
||||
//TODO: memory-size this
|
||||
await using (var cache = new MemoryStream(headerCache.ToArray()))
|
||||
using (var cachedReader = new BinaryReader(cache))
|
||||
{
|
||||
cachedReader.BaseStream.Position = 1; // skip the header size byte
|
||||
@@ -120,33 +125,30 @@ namespace SharpCompress.Compressors.Xz
|
||||
HeaderIsLoaded = true;
|
||||
}
|
||||
|
||||
private void ReadHeaderSize()
|
||||
private async ValueTask ReadHeaderSize(CancellationToken cancellationToken)
|
||||
{
|
||||
_blockHeaderSizeByte = (byte)BaseStream.ReadByte();
|
||||
_blockHeaderSizeByte = await BaseStream.ReadByteAsync(cancellationToken);
|
||||
if (_blockHeaderSizeByte == 0)
|
||||
{
|
||||
throw new XZIndexMarkerReachedException();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] CacheHeader()
|
||||
private async ValueTask CacheHeader(Memory<byte> blockHeaderWithoutCrc, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] blockHeaderWithoutCrc = new byte[BlockHeaderSize - 4];
|
||||
blockHeaderWithoutCrc[0] = _blockHeaderSizeByte;
|
||||
var read = BaseStream.Read(blockHeaderWithoutCrc, 1, BlockHeaderSize - 5);
|
||||
blockHeaderWithoutCrc.Span[0] = _blockHeaderSizeByte;
|
||||
var read = await BaseStream.ReadAsync(blockHeaderWithoutCrc.Slice( 1, BlockHeaderSize - 5), cancellationToken);
|
||||
if (read != BlockHeaderSize - 5)
|
||||
{
|
||||
throw new EndOfStreamException("Reached end of stream unexectedly");
|
||||
throw new EndOfStreamException("Reached end of stream unexpectedly");
|
||||
}
|
||||
|
||||
uint crc = BaseStream.ReadLittleEndianUInt32();
|
||||
uint crc = await BaseStream.ReadLittleEndianUInt32(cancellationToken);
|
||||
uint calcCrc = Crc32.Compute(blockHeaderWithoutCrc);
|
||||
if (crc != calcCrc)
|
||||
{
|
||||
throw new InvalidDataException("Block header corrupt");
|
||||
}
|
||||
|
||||
return blockHeaderWithoutCrc;
|
||||
}
|
||||
|
||||
private void ReadBlockFlags(BinaryReader reader)
|
||||
|
||||
@@ -1,58 +1,65 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz
|
||||
{
|
||||
public class XZHeader
|
||||
{
|
||||
private readonly BinaryReader _reader;
|
||||
private readonly byte[] MagicHeader = { 0xFD, 0x37, 0x7A, 0x58, 0x5a, 0x00 };
|
||||
private readonly Stream _stream;
|
||||
private static readonly ReadOnlyMemory<byte> MagicHeader = new(new byte[]{ 0xFD, 0x37, 0x7A, 0x58, 0x5a, 0x00 });
|
||||
|
||||
public CheckType BlockCheckType { get; private set; }
|
||||
public int BlockCheckSize => ((((int)BlockCheckType) + 2) / 3) * 4;
|
||||
|
||||
public XZHeader(BinaryReader reader)
|
||||
public XZHeader(Stream reader)
|
||||
{
|
||||
_reader = reader;
|
||||
_stream = reader;
|
||||
}
|
||||
|
||||
public static XZHeader FromStream(Stream stream)
|
||||
public static async ValueTask<XZHeader> FromStream(Stream stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var header = new XZHeader(new BinaryReader(new NonDisposingStream(stream), Encoding.UTF8));
|
||||
header.Process();
|
||||
var header = new XZHeader(new NonDisposingStream(stream));
|
||||
await header.Process(cancellationToken);
|
||||
return header;
|
||||
}
|
||||
|
||||
public void Process()
|
||||
public async ValueTask Process(CancellationToken cancellationToken = default)
|
||||
{
|
||||
CheckMagicBytes(_reader.ReadBytes(6));
|
||||
ProcessStreamFlags();
|
||||
using var header = MemoryPool<byte>.Shared.Rent(6);
|
||||
await _stream.ReadAsync(header.Memory.Slice(0, 6), cancellationToken);
|
||||
CheckMagicBytes(header.Memory.Slice(0, 6));
|
||||
await ProcessStreamFlags(cancellationToken);
|
||||
}
|
||||
|
||||
private void ProcessStreamFlags()
|
||||
private async ValueTask ProcessStreamFlags(CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] streamFlags = _reader.ReadBytes(2);
|
||||
UInt32 crc = _reader.ReadLittleEndianUInt32();
|
||||
UInt32 calcCrc = Crc32.Compute(streamFlags);
|
||||
using var header = MemoryPool<byte>.Shared.Rent(6);
|
||||
await _stream.ReadAsync(header.Memory.Slice(0, 2), cancellationToken);
|
||||
|
||||
BlockCheckType = (CheckType)(header.Memory.Span[1] & 0x0F);
|
||||
byte futureUse = (byte)(header.Memory.Span[1] & 0xF0);
|
||||
if (futureUse != 0 || header.Memory.Span[0] != 0)
|
||||
{
|
||||
throw new InvalidDataException("Unknown XZ Stream Version");
|
||||
}
|
||||
|
||||
UInt32 crc = await _stream.ReadLittleEndianUInt32(cancellationToken);
|
||||
UInt32 calcCrc = Crc32.Compute(header.Memory.Slice(0, 2));
|
||||
if (crc != calcCrc)
|
||||
{
|
||||
throw new InvalidDataException("Stream header corrupt");
|
||||
}
|
||||
|
||||
BlockCheckType = (CheckType)(streamFlags[1] & 0x0F);
|
||||
byte futureUse = (byte)(streamFlags[1] & 0xF0);
|
||||
if (futureUse != 0 || streamFlags[0] != 0)
|
||||
{
|
||||
throw new InvalidDataException("Unknown XZ Stream Version");
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckMagicBytes(byte[] header)
|
||||
private void CheckMagicBytes(ReadOnlyMemory<byte> header)
|
||||
{
|
||||
if (!header.SequenceEqual(MagicHeader))
|
||||
if (!header.Equals(MagicHeader))
|
||||
{
|
||||
throw new InvalidDataException("Invalid XZ Stream");
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Compressors.Xz
|
||||
{
|
||||
[CLSCompliant(false)]
|
||||
public sealed class XZStream : XZReadOnlyStream
|
||||
{
|
||||
public static bool IsXZStream(Stream stream)
|
||||
public static async ValueTask<bool> IsXZStreamAsync(Stream stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return null != XZHeader.FromStream(stream);
|
||||
return null != await XZHeader.FromStream(stream, cancellationToken);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
@@ -22,7 +22,7 @@ namespace SharpCompress.Compressors.Xz
|
||||
|
||||
private void AssertBlockCheckTypeIsSupported()
|
||||
{
|
||||
switch (Header.BlockCheckType)
|
||||
switch (Header?.BlockCheckType)
|
||||
{
|
||||
case CheckType.NONE:
|
||||
break;
|
||||
@@ -36,11 +36,11 @@ namespace SharpCompress.Compressors.Xz
|
||||
throw new NotSupportedException("Check Type unknown to this version of decoder.");
|
||||
}
|
||||
}
|
||||
public XZHeader Header { get; private set; }
|
||||
public XZIndex Index { get; private set; }
|
||||
public XZFooter Footer { get; private set; }
|
||||
public XZHeader? Header { get; private set; }
|
||||
public XZIndex? Index { get; private set; }
|
||||
public XZFooter? Footer { get; private set; }
|
||||
public bool HeaderIsRead { get; private set; }
|
||||
private XZBlock _currentBlock;
|
||||
private XZBlock? _currentBlock;
|
||||
|
||||
private bool _endOfStream;
|
||||
|
||||
@@ -48,7 +48,12 @@ namespace SharpCompress.Compressors.Xz
|
||||
{
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return await ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken);
|
||||
}
|
||||
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
int bytesRead = 0;
|
||||
if (_endOfStream)
|
||||
@@ -58,11 +63,11 @@ namespace SharpCompress.Compressors.Xz
|
||||
|
||||
if (!HeaderIsRead)
|
||||
{
|
||||
ReadHeader();
|
||||
await ReadHeader();
|
||||
}
|
||||
|
||||
bytesRead = ReadBlocks(buffer, offset, count);
|
||||
if (bytesRead < count)
|
||||
bytesRead = await ReadBlocks(buffer, cancellationToken);
|
||||
if (bytesRead < buffer.Length)
|
||||
{
|
||||
_endOfStream = true;
|
||||
ReadIndex();
|
||||
@@ -71,9 +76,9 @@ namespace SharpCompress.Compressors.Xz
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
private void ReadHeader()
|
||||
private async ValueTask ReadHeader()
|
||||
{
|
||||
Header = XZHeader.FromStream(BaseStream);
|
||||
Header = await XZHeader.FromStream(BaseStream);
|
||||
AssertBlockCheckTypeIsSupported();
|
||||
HeaderIsRead = true;
|
||||
}
|
||||
@@ -90,29 +95,29 @@ namespace SharpCompress.Compressors.Xz
|
||||
// TODO verify footer
|
||||
}
|
||||
|
||||
private int ReadBlocks(byte[] buffer, int offset, int count)
|
||||
private async ValueTask<int> ReadBlocks(Memory<byte> buffer, CancellationToken cancellationToken)
|
||||
{
|
||||
int bytesRead = 0;
|
||||
if (_currentBlock is null)
|
||||
{
|
||||
NextBlock();
|
||||
_currentBlock = NextBlock();
|
||||
}
|
||||
|
||||
for (; ; )
|
||||
{
|
||||
try
|
||||
{
|
||||
if (bytesRead >= count)
|
||||
if (bytesRead >= buffer.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
int remaining = count - bytesRead;
|
||||
int newOffset = offset + bytesRead;
|
||||
int justRead = _currentBlock.Read(buffer, newOffset, remaining);
|
||||
int remaining = buffer.Length - bytesRead;
|
||||
int newOffset = bytesRead;
|
||||
int justRead = await _currentBlock.ReadAsync(buffer.Slice(newOffset, remaining), cancellationToken);
|
||||
if (justRead < remaining)
|
||||
{
|
||||
NextBlock();
|
||||
_currentBlock = NextBlock();
|
||||
}
|
||||
|
||||
bytesRead += justRead;
|
||||
@@ -125,9 +130,9 @@ namespace SharpCompress.Compressors.Xz
|
||||
return bytesRead;
|
||||
}
|
||||
|
||||
private void NextBlock()
|
||||
private XZBlock NextBlock()
|
||||
{
|
||||
_currentBlock = new XZBlock(BaseStream, Header.BlockCheckType, Header.BlockCheckSize);
|
||||
return new XZBlock(BaseStream, Header!.BlockCheckType, Header!.BlockCheckSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Crypto
|
||||
{
|
||||
@@ -52,16 +54,20 @@ namespace SharpCompress.Crypto
|
||||
}
|
||||
#endif
|
||||
|
||||
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
await stream.WriteAsync(buffer, cancellationToken);
|
||||
hash = CalculateCrc(table, hash, buffer.Span);
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
stream.Write(buffer, offset, count);
|
||||
hash = CalculateCrc(table, hash, buffer.AsSpan(offset, count));
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
stream.WriteByte(value);
|
||||
hash = CalculateCrc(table, hash, value);
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override bool CanRead => stream.CanRead;
|
||||
|
||||
76
src/SharpCompress/IO/AsyncStream.cs
Normal file
76
src/SharpCompress/IO/AsyncStream.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.IO
|
||||
{
|
||||
public abstract class AsyncStream : Stream
|
||||
{
|
||||
protected sealed override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed override void Flush()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public abstract override ValueTask DisposeAsync();
|
||||
|
||||
public sealed override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public sealed override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public sealed override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public sealed override int EndRead(IAsyncResult asyncResult)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public sealed override int ReadByte()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public sealed override void WriteByte(byte b)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return await ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken);
|
||||
}
|
||||
|
||||
public abstract override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
|
||||
|
||||
#if !NET461 && !NETSTANDARD2_0
|
||||
|
||||
public sealed override int Read(Span<byte> buffer)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public sealed override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.IO
|
||||
{
|
||||
@@ -25,16 +27,11 @@ namespace SharpCompress.IO
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Length => BytesLeftToRead;
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (count > BytesLeftToRead)
|
||||
{
|
||||
@@ -47,7 +44,7 @@ namespace SharpCompress.IO
|
||||
{
|
||||
cacheOffset = 0;
|
||||
Stream.Position = position;
|
||||
cacheLength = Stream.Read(cache, 0, cache.Length);
|
||||
cacheLength = await Stream.ReadAsync(cache, 0, cache.Length, cancellationToken);
|
||||
position += cacheLength;
|
||||
}
|
||||
|
||||
@@ -74,10 +71,5 @@ namespace SharpCompress.IO
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.IO
|
||||
{
|
||||
@@ -17,20 +19,15 @@ namespace SharpCompress.IO
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Stream.Flush();
|
||||
return Stream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
@@ -41,16 +38,16 @@ namespace SharpCompress.IO
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
Stream.Write(buffer, offset, count);
|
||||
await Stream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
Count += (uint)count;
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Stream.WriteByte(value);
|
||||
++Count;
|
||||
await Stream.WriteAsync(buffer, cancellationToken);
|
||||
Count += (uint)buffer.Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.IO
|
||||
{
|
||||
public class NonDisposingStream : Stream
|
||||
public class NonDisposingStream : AsyncStream
|
||||
{
|
||||
public NonDisposingStream(Stream stream, bool throwOnDispose = false)
|
||||
{
|
||||
@@ -13,12 +15,14 @@ namespace SharpCompress.IO
|
||||
|
||||
public bool ThrowOnDispose { get; set; }
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override ValueTask DisposeAsync()
|
||||
{
|
||||
if (ThrowOnDispose)
|
||||
{
|
||||
throw new InvalidOperationException($"Attempt to dispose of a {nameof(NonDisposingStream)} when {nameof(ThrowOnDispose)} is {ThrowOnDispose}");
|
||||
}
|
||||
|
||||
return new ValueTask();
|
||||
}
|
||||
|
||||
protected Stream Stream { get; }
|
||||
@@ -29,18 +33,23 @@ namespace SharpCompress.IO
|
||||
|
||||
public override bool CanWrite => Stream.CanWrite;
|
||||
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Stream.Flush();
|
||||
return Stream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override long Length => Stream.Length;
|
||||
|
||||
public override long Position { get => Stream.Position; set => Stream.Position = value; }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
|
||||
{
|
||||
return Stream.Read(buffer, offset, count);
|
||||
return Stream.ReadAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
return Stream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
@@ -53,23 +62,14 @@ namespace SharpCompress.IO
|
||||
Stream.SetLength(value);
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
Stream.Write(buffer, offset, count);
|
||||
return Stream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
}
|
||||
|
||||
#if !NET461 && !NETSTANDARD2_0
|
||||
|
||||
public override int Read(Span<byte> buffer)
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = new CancellationToken())
|
||||
{
|
||||
return Stream.Read(buffer);
|
||||
return Stream.WriteAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
Stream.Write(buffer);
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.IO
|
||||
{
|
||||
@@ -28,41 +30,47 @@ namespace SharpCompress.IO
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var count = buffer.Length;
|
||||
if (BytesLeftToRead < count)
|
||||
{
|
||||
count = (int)BytesLeftToRead;
|
||||
}
|
||||
int read = Stream.Read(buffer, offset, count);
|
||||
|
||||
if (count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
int read = await Stream.ReadAsync(buffer.Slice(0, count), cancellationToken);
|
||||
if (read > 0)
|
||||
{
|
||||
BytesLeftToRead -= read;
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
public override int ReadByte()
|
||||
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (BytesLeftToRead <= 0)
|
||||
if (BytesLeftToRead < count)
|
||||
{
|
||||
return -1;
|
||||
count = (int)BytesLeftToRead;
|
||||
}
|
||||
int value = Stream.ReadByte();
|
||||
if (value != -1)
|
||||
|
||||
if (count == 0)
|
||||
{
|
||||
--BytesLeftToRead;
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
int read = await Stream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
if (read > 0)
|
||||
{
|
||||
BytesLeftToRead -= read;
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
@@ -74,10 +82,5 @@ namespace SharpCompress.IO
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.IO
|
||||
{
|
||||
internal class RewindableStream : Stream
|
||||
{
|
||||
private readonly Stream stream;
|
||||
private MemoryStream bufferStream = new MemoryStream();
|
||||
private MemoryStream bufferStream = new();
|
||||
private bool isRewound;
|
||||
private bool isDisposed;
|
||||
|
||||
@@ -109,6 +111,11 @@ namespace SharpCompress.IO
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
//don't actually read if we don't really want to read anything
|
||||
//currently a network stream bug on Windows for .NET Core
|
||||
@@ -119,13 +126,13 @@ namespace SharpCompress.IO
|
||||
int read;
|
||||
if (isRewound && bufferStream.Position != bufferStream.Length)
|
||||
{
|
||||
read = bufferStream.Read(buffer, offset, count);
|
||||
read = await bufferStream.ReadAsync(buffer, offset, count, cancellationToken);
|
||||
if (read < count)
|
||||
{
|
||||
int tempRead = stream.Read(buffer, offset + read, count - read);
|
||||
int tempRead = await stream.ReadAsync(buffer, read, count - read, cancellationToken);
|
||||
if (IsRecording)
|
||||
{
|
||||
bufferStream.Write(buffer, offset + read, tempRead);
|
||||
await bufferStream.WriteAsync(buffer, read, tempRead, cancellationToken);
|
||||
}
|
||||
read += tempRead;
|
||||
}
|
||||
@@ -137,10 +144,48 @@ namespace SharpCompress.IO
|
||||
return read;
|
||||
}
|
||||
|
||||
read = stream.Read(buffer, offset, count);
|
||||
read = await stream.ReadAsync(buffer, cancellationToken);
|
||||
if (IsRecording)
|
||||
{
|
||||
bufferStream.Write(buffer, offset, read);
|
||||
await bufferStream.WriteAsync(buffer, cancellationToken);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var count = buffer.Length;
|
||||
//don't actually read if we don't really want to read anything
|
||||
//currently a network stream bug on Windows for .NET Core
|
||||
if (count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
int read;
|
||||
if (isRewound && bufferStream.Position != bufferStream.Length)
|
||||
{
|
||||
read = await bufferStream.ReadAsync(buffer, cancellationToken);
|
||||
if (read < count)
|
||||
{
|
||||
int tempRead = await stream.ReadAsync(buffer.Slice(read, count - read), cancellationToken);
|
||||
if (IsRecording)
|
||||
{
|
||||
await bufferStream.WriteAsync(buffer.Slice(read, tempRead), cancellationToken);
|
||||
}
|
||||
read += tempRead;
|
||||
}
|
||||
if (bufferStream.Position == bufferStream.Length && !IsRecording)
|
||||
{
|
||||
isRewound = false;
|
||||
bufferStream.SetLength(0);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
read = await stream.ReadAsync(buffer, cancellationToken);
|
||||
if (IsRecording)
|
||||
{
|
||||
await bufferStream.WriteAsync(buffer, cancellationToken);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,31 @@
|
||||
#nullable disable
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress
|
||||
{
|
||||
internal sealed class LazyReadOnlyCollection<T> : ICollection<T>
|
||||
internal sealed class LazyReadOnlyCollection<T> : IAsyncEnumerable<T>
|
||||
{
|
||||
private readonly List<T> backing = new List<T>();
|
||||
private readonly IEnumerator<T> source;
|
||||
private readonly List<T> backing = new();
|
||||
private IAsyncEnumerator<T>? enumerator;
|
||||
private readonly IAsyncEnumerable<T> enumerable;
|
||||
private bool fullyLoaded;
|
||||
|
||||
public LazyReadOnlyCollection(IEnumerable<T> source)
|
||||
public LazyReadOnlyCollection(IAsyncEnumerable<T> source)
|
||||
{
|
||||
this.source = source.GetEnumerator();
|
||||
enumerable = source;
|
||||
}
|
||||
|
||||
private class LazyLoader : IEnumerator<T>
|
||||
private IAsyncEnumerator<T> GetEnumerator()
|
||||
{
|
||||
if (enumerator is null)
|
||||
{
|
||||
enumerator = enumerable.GetAsyncEnumerator();
|
||||
}
|
||||
return enumerator;
|
||||
}
|
||||
|
||||
private class LazyLoader : IAsyncEnumerator<T>
|
||||
{
|
||||
private readonly LazyReadOnlyCollection<T> lazyReadOnlyCollection;
|
||||
private bool disposed;
|
||||
@@ -28,58 +36,43 @@ namespace SharpCompress
|
||||
this.lazyReadOnlyCollection = lazyReadOnlyCollection;
|
||||
}
|
||||
|
||||
#region IEnumerator<T> Members
|
||||
|
||||
public T Current => lazyReadOnlyCollection.backing[index];
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
public void Dispose()
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (!disposed)
|
||||
{
|
||||
disposed = true;
|
||||
}
|
||||
return new ValueTask(Task.CompletedTask);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IEnumerator Members
|
||||
|
||||
object IEnumerator.Current => Current;
|
||||
|
||||
public bool MoveNext()
|
||||
public async ValueTask<bool> MoveNextAsync()
|
||||
{
|
||||
if (index + 1 < lazyReadOnlyCollection.backing.Count)
|
||||
{
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
if (!lazyReadOnlyCollection.fullyLoaded && lazyReadOnlyCollection.source.MoveNext())
|
||||
if (!lazyReadOnlyCollection.fullyLoaded && await lazyReadOnlyCollection.GetEnumerator().MoveNextAsync())
|
||||
{
|
||||
lazyReadOnlyCollection.backing.Add(lazyReadOnlyCollection.source.Current);
|
||||
lazyReadOnlyCollection.backing.Add(lazyReadOnlyCollection.GetEnumerator().Current);
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
lazyReadOnlyCollection.fullyLoaded = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
internal void EnsureFullyLoaded()
|
||||
internal async ValueTask EnsureFullyLoaded()
|
||||
{
|
||||
if (!fullyLoaded)
|
||||
{
|
||||
this.ForEach(x => { });
|
||||
await foreach (var x in this)
|
||||
{
|
||||
}
|
||||
fullyLoaded = true;
|
||||
}
|
||||
}
|
||||
@@ -89,65 +82,14 @@ namespace SharpCompress
|
||||
return backing;
|
||||
}
|
||||
|
||||
#region ICollection<T> Members
|
||||
|
||||
public void Add(T item)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public bool Contains(T item)
|
||||
{
|
||||
EnsureFullyLoaded();
|
||||
return backing.Contains(item);
|
||||
}
|
||||
|
||||
public void CopyTo(T[] array, int arrayIndex)
|
||||
{
|
||||
EnsureFullyLoaded();
|
||||
backing.CopyTo(array, arrayIndex);
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureFullyLoaded();
|
||||
return backing.Count;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsReadOnly => true;
|
||||
|
||||
public bool Remove(T item)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IEnumerable<T> Members
|
||||
|
||||
//TODO check for concurrent access
|
||||
public IEnumerator<T> GetEnumerator()
|
||||
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken)
|
||||
{
|
||||
return new LazyLoader(this);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IEnumerable Members
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetEnumerator();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Readers
|
||||
@@ -14,7 +16,7 @@ namespace SharpCompress.Readers
|
||||
where TVolume : Volume
|
||||
{
|
||||
private bool completed;
|
||||
private IEnumerator<TEntry>? entriesForCurrentReadStream;
|
||||
private IAsyncEnumerator<TEntry>? entriesForCurrentReadStream;
|
||||
private bool wroteCurrentEntry;
|
||||
|
||||
public event EventHandler<ReaderExtractionEventArgs<IEntry>>? EntryExtractionProgress;
|
||||
@@ -40,14 +42,14 @@ namespace SharpCompress.Readers
|
||||
/// <summary>
|
||||
/// Current file entry
|
||||
/// </summary>
|
||||
public TEntry Entry => entriesForCurrentReadStream!.Current;
|
||||
public TEntry? Entry => entriesForCurrentReadStream?.Current ?? default;
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
public void Dispose()
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
entriesForCurrentReadStream?.Dispose();
|
||||
Volume?.Dispose();
|
||||
await (entriesForCurrentReadStream?.DisposeAsync() ?? new ValueTask());
|
||||
await Volume.DisposeAsync();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -67,7 +69,7 @@ namespace SharpCompress.Readers
|
||||
}
|
||||
}
|
||||
|
||||
public bool MoveToNextEntry()
|
||||
public async ValueTask<bool> MoveToNextEntryAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (completed)
|
||||
{
|
||||
@@ -79,14 +81,21 @@ namespace SharpCompress.Readers
|
||||
}
|
||||
if (entriesForCurrentReadStream is null)
|
||||
{
|
||||
return LoadStreamForReading(RequestInitialStream());
|
||||
}
|
||||
if (!wroteCurrentEntry)
|
||||
var stream = await RequestInitialStream(cancellationToken);
|
||||
if (stream is null || !stream.CanRead)
|
||||
{
|
||||
throw new MultipartStreamRequiredException("File is split into multiple archives: '"
|
||||
+ (Entry?.Key ?? "unknown") +
|
||||
"'. A new readable stream is required. Use Cancel if it was intended.");
|
||||
}
|
||||
entriesForCurrentReadStream = GetEntries(stream, cancellationToken).GetAsyncEnumerator(cancellationToken);
|
||||
}
|
||||
else if (!wroteCurrentEntry)
|
||||
{
|
||||
SkipEntry();
|
||||
await SkipEntry(cancellationToken);
|
||||
}
|
||||
wroteCurrentEntry = false;
|
||||
if (NextEntryForCurrentStream())
|
||||
if (await entriesForCurrentReadStream.MoveNextAsync())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -94,43 +103,29 @@ namespace SharpCompress.Readers
|
||||
return false;
|
||||
}
|
||||
|
||||
protected bool LoadStreamForReading(Stream stream)
|
||||
protected virtual ValueTask<Stream> RequestInitialStream(CancellationToken cancellationToken)
|
||||
{
|
||||
entriesForCurrentReadStream?.Dispose();
|
||||
if ((stream is null) || (!stream.CanRead))
|
||||
{
|
||||
throw new MultipartStreamRequiredException("File is split into multiple archives: '"
|
||||
+ Entry.Key +
|
||||
"'. A new readable stream is required. Use Cancel if it was intended.");
|
||||
}
|
||||
entriesForCurrentReadStream = GetEntries(stream).GetEnumerator();
|
||||
return entriesForCurrentReadStream.MoveNext();
|
||||
return new(Volume.Stream);
|
||||
}
|
||||
|
||||
protected virtual Stream RequestInitialStream()
|
||||
{
|
||||
return Volume.Stream;
|
||||
}
|
||||
|
||||
internal virtual bool NextEntryForCurrentStream()
|
||||
{
|
||||
return entriesForCurrentReadStream!.MoveNext();
|
||||
}
|
||||
|
||||
protected abstract IEnumerable<TEntry> GetEntries(Stream stream);
|
||||
protected abstract IAsyncEnumerable<TEntry> GetEntries(Stream stream, CancellationToken cancellationToken);
|
||||
|
||||
#region Entry Skip/Write
|
||||
|
||||
private void SkipEntry()
|
||||
private async ValueTask SkipEntry(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Entry.IsDirectory)
|
||||
if (Entry?.IsDirectory != true)
|
||||
{
|
||||
Skip();
|
||||
await SkipAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private void Skip()
|
||||
private async ValueTask SkipAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Entry is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (ArchiveType != ArchiveType.Rar
|
||||
&& !Entry.IsSolid
|
||||
&& Entry.CompressedSize > 0)
|
||||
@@ -142,19 +137,17 @@ namespace SharpCompress.Readers
|
||||
if (rawStream != null)
|
||||
{
|
||||
var bytesToAdvance = Entry.CompressedSize;
|
||||
rawStream.Skip(bytesToAdvance);
|
||||
await rawStream.SkipAsync(bytesToAdvance, cancellationToken: cancellationToken);
|
||||
part.Skipped = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
//don't know the size so we have to try to decompress to skip
|
||||
using (var s = OpenEntryStream())
|
||||
{
|
||||
s.Skip();
|
||||
}
|
||||
await using var s = await OpenEntryStreamAsync(cancellationToken);
|
||||
await s.SkipAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public void WriteEntryTo(Stream writableStream)
|
||||
public async ValueTask WriteEntryToAsync(Stream writableStream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (wroteCurrentEntry)
|
||||
{
|
||||
@@ -165,26 +158,28 @@ namespace SharpCompress.Readers
|
||||
throw new ArgumentNullException("A writable Stream was required. Use Cancel if that was intended.");
|
||||
}
|
||||
|
||||
Write(writableStream);
|
||||
await WriteAsync(writableStream, cancellationToken);
|
||||
wroteCurrentEntry = true;
|
||||
}
|
||||
|
||||
internal void Write(Stream writeStream)
|
||||
private async ValueTask WriteAsync(Stream writeStream, CancellationToken cancellationToken)
|
||||
{
|
||||
var streamListener = this as IReaderExtractionListener;
|
||||
using (Stream s = OpenEntryStream())
|
||||
if (Entry is null)
|
||||
{
|
||||
s.TransferTo(writeStream, Entry, streamListener);
|
||||
throw new ArgumentException("Entry is null");
|
||||
}
|
||||
var streamListener = this as IReaderExtractionListener;
|
||||
await using Stream s = await OpenEntryStreamAsync(cancellationToken);
|
||||
await s.TransferToAsync(writeStream, Entry, streamListener, cancellationToken);
|
||||
}
|
||||
|
||||
public EntryStream OpenEntryStream()
|
||||
public async ValueTask<EntryStream> OpenEntryStreamAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (wroteCurrentEntry)
|
||||
{
|
||||
throw new ArgumentException("WriteEntryTo or OpenEntryStream can only be called once.");
|
||||
}
|
||||
var stream = GetEntryStream();
|
||||
var stream = await GetEntryStreamAsync(cancellationToken);
|
||||
wroteCurrentEntry = true;
|
||||
return stream;
|
||||
}
|
||||
@@ -194,17 +189,21 @@ namespace SharpCompress.Readers
|
||||
/// </summary>
|
||||
protected EntryStream CreateEntryStream(Stream decompressed)
|
||||
{
|
||||
return new EntryStream(this, decompressed);
|
||||
return new(this, decompressed);
|
||||
}
|
||||
|
||||
protected virtual EntryStream GetEntryStream()
|
||||
protected async ValueTask<EntryStream> GetEntryStreamAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return CreateEntryStream(Entry.Parts.First().GetCompressedStream());
|
||||
if (Entry is null)
|
||||
{
|
||||
throw new ArgumentException("Entry is null");
|
||||
}
|
||||
return CreateEntryStream(await Entry.Parts.First().GetCompressedStreamAsync(cancellationToken));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
IEntry IReader.Entry => Entry;
|
||||
IEntry? IReader.Entry => Entry;
|
||||
|
||||
void IExtractionListener.FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.GZip;
|
||||
|
||||
@@ -31,9 +32,9 @@ namespace SharpCompress.Readers.GZip
|
||||
|
||||
#endregion Open
|
||||
|
||||
protected override IEnumerable<GZipEntry> GetEntries(Stream stream)
|
||||
protected override IAsyncEnumerable<GZipEntry> GetEntries(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return GZipEntry.GetEntries(stream, Options);
|
||||
return GZipEntry.GetEntries(stream, Options, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Readers
|
||||
{
|
||||
public interface IReader : IDisposable
|
||||
public interface IReader : IAsyncDisposable
|
||||
{
|
||||
event EventHandler<ReaderExtractionEventArgs<IEntry>> EntryExtractionProgress;
|
||||
|
||||
@@ -13,13 +15,13 @@ namespace SharpCompress.Readers
|
||||
|
||||
ArchiveType ArchiveType { get; }
|
||||
|
||||
IEntry Entry { get; }
|
||||
IEntry? Entry { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Decompresses the current entry to the stream. This cannot be called twice for the current entry.
|
||||
/// </summary>
|
||||
/// <param name="writableStream"></param>
|
||||
void WriteEntryTo(Stream writableStream);
|
||||
ValueTask WriteEntryToAsync(Stream writableStream, CancellationToken cancellationToken = default);
|
||||
|
||||
bool Cancelled { get; }
|
||||
void Cancel();
|
||||
@@ -28,12 +30,12 @@ namespace SharpCompress.Readers
|
||||
/// Moves to the next entry by reading more data from the underlying stream. This skips if data has not been read.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
bool MoveToNextEntry();
|
||||
ValueTask<bool> MoveToNextEntryAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the current entry as a stream that will decompress as it is read.
|
||||
/// Read the entire stream or use SkipEntry on EntryStream.
|
||||
/// </summary>
|
||||
EntryStream OpenEntryStream();
|
||||
ValueTask<EntryStream> OpenEntryStreamAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +1,73 @@
|
||||
using System.IO;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Readers
|
||||
{
|
||||
public static class IReaderExtensions
|
||||
{
|
||||
public static void WriteEntryTo(this IReader reader, string filePath)
|
||||
public static async ValueTask WriteEntryToAsync(this IReader reader, string filePath)
|
||||
{
|
||||
using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
reader.WriteEntryTo(stream);
|
||||
}
|
||||
await using Stream stream = File.Open(filePath, FileMode.Create, FileAccess.Write);
|
||||
await reader.WriteEntryToAsync(stream);
|
||||
}
|
||||
|
||||
public static void WriteEntryTo(this IReader reader, FileInfo filePath)
|
||||
public static async ValueTask WriteEntryToAsync(this IReader reader, FileInfo filePath)
|
||||
{
|
||||
using (Stream stream = filePath.Open(FileMode.Create))
|
||||
{
|
||||
reader.WriteEntryTo(stream);
|
||||
}
|
||||
await using Stream stream = filePath.Open(FileMode.Create);
|
||||
await reader.WriteEntryToAsync(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract all remaining unread entries to specific directory, retaining filename
|
||||
/// </summary>
|
||||
public static void WriteAllToDirectory(this IReader reader, string destinationDirectory,
|
||||
public static async ValueTask WriteAllToDirectoryAsync(this IReader reader, string destinationDirectory,
|
||||
ExtractionOptions? options = null)
|
||||
{
|
||||
while (reader.MoveToNextEntry())
|
||||
while (await reader.MoveToNextEntryAsync())
|
||||
{
|
||||
reader.WriteEntryToDirectory(destinationDirectory, options);
|
||||
await reader.WriteEntryToDirectoryAsync(destinationDirectory, options);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract to specific directory, retaining filename
|
||||
/// </summary>
|
||||
public static void WriteEntryToDirectory(this IReader reader, string destinationDirectory,
|
||||
ExtractionOptions? options = null)
|
||||
public static ValueTask WriteEntryToDirectoryAsync(this IReader reader, string destinationDirectory,
|
||||
ExtractionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ExtractionMethods.WriteEntryToDirectory(reader.Entry, destinationDirectory, options,
|
||||
reader.WriteEntryToFile);
|
||||
if (reader.Entry is null)
|
||||
{
|
||||
throw new ArgumentException("Entry is null");
|
||||
}
|
||||
return ExtractionMethods.WriteEntryToDirectoryAsync(reader.Entry, destinationDirectory, options,
|
||||
async (x, o, ct) =>
|
||||
{
|
||||
await reader.WriteEntryToFileAsync(x, o, ct);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract to specific file
|
||||
/// </summary>
|
||||
public static void WriteEntryToFile(this IReader reader,
|
||||
public static async ValueTask WriteEntryToFileAsync(this IReader reader,
|
||||
string destinationFileName,
|
||||
ExtractionOptions? options = null)
|
||||
ExtractionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ExtractionMethods.WriteEntryToFile(reader.Entry, destinationFileName, options,
|
||||
(x, fm) =>
|
||||
if (reader.Entry is null)
|
||||
{
|
||||
throw new ArgumentException("Entry is null");
|
||||
}
|
||||
await ExtractionMethods.WriteEntryToFileAsync(reader.Entry, destinationFileName, options,
|
||||
async (x, fm, ct) =>
|
||||
{
|
||||
using (FileStream fs = File.Open(destinationFileName, fm))
|
||||
{
|
||||
reader.WriteEntryTo(fs);
|
||||
}
|
||||
});
|
||||
await using FileStream fs = File.Open(x, fm);
|
||||
await reader.WriteEntryToAsync(fs, ct);
|
||||
}, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Archives.GZip;
|
||||
using SharpCompress.Archives.Rar;
|
||||
//using SharpCompress.Archives.Rar;
|
||||
using SharpCompress.Archives.Tar;
|
||||
using SharpCompress.Archives.Zip;
|
||||
using SharpCompress.Common;
|
||||
@@ -10,7 +12,7 @@ using SharpCompress.Compressors.BZip2;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
using SharpCompress.IO;
|
||||
using SharpCompress.Readers.GZip;
|
||||
using SharpCompress.Readers.Rar;
|
||||
//using SharpCompress.Readers.Rar;
|
||||
using SharpCompress.Readers.Tar;
|
||||
using SharpCompress.Readers.Zip;
|
||||
using SharpCompress.Compressors.LZMA;
|
||||
@@ -26,80 +28,80 @@ namespace SharpCompress.Readers
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
public static IReader Open(Stream stream, ReaderOptions? options = null)
|
||||
public static async ValueTask<IReader> OpenAsync(Stream stream, ReaderOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
stream.CheckNotNull(nameof(stream));
|
||||
options = options ?? new ReaderOptions()
|
||||
{
|
||||
LeaveStreamOpen = false
|
||||
};
|
||||
RewindableStream rewindableStream = new RewindableStream(stream);
|
||||
options ??= new ReaderOptions()
|
||||
{
|
||||
LeaveStreamOpen = false
|
||||
};
|
||||
RewindableStream rewindableStream = new(stream);
|
||||
rewindableStream.StartRecording();
|
||||
if (ZipArchive.IsZipFile(rewindableStream, options.Password))
|
||||
if (await ZipArchive.IsZipFileAsync(rewindableStream, options.Password, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return ZipReader.Open(rewindableStream, options);
|
||||
}
|
||||
rewindableStream.Rewind(false);
|
||||
if (GZipArchive.IsGZipFile(rewindableStream))
|
||||
if (await GZipArchive.IsGZipFileAsync(rewindableStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(false);
|
||||
GZipStream testStream = new GZipStream(rewindableStream, CompressionMode.Decompress);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
GZipStream testStream = new(rewindableStream, CompressionMode.Decompress);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.GZip);
|
||||
}
|
||||
}
|
||||
rewindableStream.Rewind(true);
|
||||
return GZipReader.Open(rewindableStream, options);
|
||||
}
|
||||
|
||||
rewindableStream.Rewind(false);
|
||||
if (BZip2Stream.IsBZip2(rewindableStream))
|
||||
if (await BZip2Stream.IsBZip2Async(rewindableStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(false);
|
||||
BZip2Stream testStream = new BZip2Stream(new NonDisposingStream(rewindableStream), CompressionMode.Decompress, false);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
var testStream = await BZip2Stream.CreateAsync(new NonDisposingStream(rewindableStream), CompressionMode.Decompress, false, cancellationToken);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.BZip2);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
rewindableStream.Rewind(false);
|
||||
if (LZipStream.IsLZipFile(rewindableStream))
|
||||
if (await LZipStream.IsLZipFileAsync(rewindableStream))
|
||||
{
|
||||
rewindableStream.Rewind(false);
|
||||
LZipStream testStream = new LZipStream(new NonDisposingStream(rewindableStream), CompressionMode.Decompress);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.LZip);
|
||||
}
|
||||
var testStream = await LZipStream.CreateAsync(new NonDisposingStream(rewindableStream), CompressionMode.Decompress);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.LZip);
|
||||
}
|
||||
}
|
||||
rewindableStream.Rewind(false);
|
||||
/* rewindableStream.Rewind(false);
|
||||
if (RarArchive.IsRarFile(rewindableStream, options))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return RarReader.Open(rewindableStream, options);
|
||||
}
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return RarReader.Open(rewindableStream, options);
|
||||
} */
|
||||
|
||||
rewindableStream.Rewind(false);
|
||||
if (TarArchive.IsTarFile(rewindableStream))
|
||||
if (await TarArchive.IsTarFileAsync(rewindableStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return TarReader.Open(rewindableStream, options);
|
||||
}
|
||||
return await TarReader.OpenAsync(rewindableStream, options, cancellationToken);
|
||||
}
|
||||
rewindableStream.Rewind(false);
|
||||
if (XZStream.IsXZStream(rewindableStream))
|
||||
if (await XZStream.IsXZStreamAsync(rewindableStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
XZStream testStream = new XZStream(rewindableStream);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
XZStream testStream = new(rewindableStream);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.Xz);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new InvalidOperationException("Cannot determine compressed stream type. Supported Reader Formats: Zip, GZip, BZip2, Tar, Rar, LZip, XZ");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Archives.GZip;
|
||||
using SharpCompress.Archives.Tar;
|
||||
using SharpCompress.Common;
|
||||
@@ -27,22 +29,22 @@ namespace SharpCompress.Readers.Tar
|
||||
|
||||
public override TarVolume Volume { get; }
|
||||
|
||||
protected override Stream RequestInitialStream()
|
||||
protected override async ValueTask<Stream> RequestInitialStream(CancellationToken cancellationToken)
|
||||
{
|
||||
var stream = base.RequestInitialStream();
|
||||
var stream = await base.RequestInitialStream(cancellationToken);
|
||||
switch (compressionType)
|
||||
{
|
||||
case CompressionType.BZip2:
|
||||
/* case CompressionType.BZip2:
|
||||
{
|
||||
return new BZip2Stream(stream, CompressionMode.Decompress, false);
|
||||
}
|
||||
return await BZip2Stream.CreateAsync(stream, CompressionMode.Decompress, false, cancellationToken);
|
||||
} */
|
||||
case CompressionType.GZip:
|
||||
{
|
||||
return new GZipStream(stream, CompressionMode.Decompress);
|
||||
}
|
||||
case CompressionType.LZip:
|
||||
{
|
||||
return new LZipStream(stream, CompressionMode.Decompress);
|
||||
return await LZipStream.CreateAsync(stream, CompressionMode.Decompress);
|
||||
}
|
||||
case CompressionType.Xz:
|
||||
{
|
||||
@@ -67,17 +69,17 @@ namespace SharpCompress.Readers.Tar
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
public static TarReader Open(Stream stream, ReaderOptions? options = null)
|
||||
public static async ValueTask<TarReader> OpenAsync(Stream stream, ReaderOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
stream.CheckNotNull(nameof(stream));
|
||||
options = options ?? new ReaderOptions();
|
||||
RewindableStream rewindableStream = new RewindableStream(stream);
|
||||
options ??= new ReaderOptions();
|
||||
RewindableStream rewindableStream = new(stream);
|
||||
rewindableStream.StartRecording();
|
||||
if (GZipArchive.IsGZipFile(rewindableStream))
|
||||
if (await GZipArchive.IsGZipFileAsync(rewindableStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(false);
|
||||
GZipStream testStream = new GZipStream(rewindableStream, CompressionMode.Decompress);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
GZipStream testStream = new(rewindableStream, CompressionMode.Decompress);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.GZip);
|
||||
@@ -85,25 +87,25 @@ namespace SharpCompress.Readers.Tar
|
||||
throw new InvalidFormatException("Not a tar file.");
|
||||
}
|
||||
|
||||
rewindableStream.Rewind(false);
|
||||
if (BZip2Stream.IsBZip2(rewindableStream))
|
||||
/*rewindableStream.Rewind(false);
|
||||
if (await BZip2Stream.IsBZip2Async(rewindableStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(false);
|
||||
BZip2Stream testStream = new BZip2Stream(rewindableStream, CompressionMode.Decompress, false);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
var testStream = await BZip2Stream.CreateAsync(rewindableStream, CompressionMode.Decompress, false, cancellationToken);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.BZip2);
|
||||
}
|
||||
throw new InvalidFormatException("Not a tar file.");
|
||||
}
|
||||
} */
|
||||
|
||||
rewindableStream.Rewind(false);
|
||||
if (LZipStream.IsLZipFile(rewindableStream))
|
||||
if (await LZipStream.IsLZipFileAsync(rewindableStream))
|
||||
{
|
||||
rewindableStream.Rewind(false);
|
||||
LZipStream testStream = new LZipStream(rewindableStream, CompressionMode.Decompress);
|
||||
if (TarArchive.IsTarFile(testStream))
|
||||
var testStream = await LZipStream.CreateAsync(rewindableStream, CompressionMode.Decompress);
|
||||
if (await TarArchive.IsTarFileAsync(testStream, cancellationToken))
|
||||
{
|
||||
rewindableStream.Rewind(true);
|
||||
return new TarReader(rewindableStream, options, CompressionType.LZip);
|
||||
@@ -116,9 +118,9 @@ namespace SharpCompress.Readers.Tar
|
||||
|
||||
#endregion Open
|
||||
|
||||
protected override IEnumerable<TarEntry> GetEntries(Stream stream)
|
||||
protected override IAsyncEnumerable<TarEntry> GetEntries(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return TarEntry.GetEntries(StreamingMode.Streaming, stream, compressionType, Options.ArchiveEncoding);
|
||||
return TarEntry.GetEntries(StreamingMode.Streaming, stream, compressionType, Options.ArchiveEncoding, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Zip;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Readers.Zip
|
||||
{
|
||||
@@ -35,9 +39,18 @@ namespace SharpCompress.Readers.Zip
|
||||
|
||||
#endregion Open
|
||||
|
||||
protected override IEnumerable<ZipEntry> GetEntries(Stream stream)
|
||||
protected override async IAsyncEnumerable<ZipEntry> GetEntries(Stream stream, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (ZipHeader h in _headerFactory.ReadStreamHeader(stream))
|
||||
RewindableStream rewindableStream;
|
||||
if (stream is RewindableStream rs)
|
||||
{
|
||||
rewindableStream = rs;
|
||||
}
|
||||
else
|
||||
{
|
||||
rewindableStream = new RewindableStream(stream);
|
||||
}
|
||||
await foreach (ZipHeader h in _headerFactory.ReadStreamHeader(rewindableStream, cancellationToken).WithCancellation(cancellationToken))
|
||||
{
|
||||
if (h != null)
|
||||
{
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
<AssemblyVersion>0.28.0</AssemblyVersion>
|
||||
<FileVersion>0.28.0</FileVersion>
|
||||
<Authors>Adam Hathcock</Authors>
|
||||
<TargetFrameworks>netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0</TargetFrameworks>
|
||||
<TargetFrameworks>netstandard2.1;netcoreapp3.1;net5.0</TargetFrameworks>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<WarningsAsErrors>true</WarningsAsErrors>
|
||||
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
|
||||
<AssemblyName>SharpCompress</AssemblyName>
|
||||
<AssemblyOriginatorKeyFile>../../SharpCompress.snk</AssemblyOriginatorKeyFile>
|
||||
@@ -29,13 +30,39 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
|
||||
<PackageReference Include="System.Linq.Async" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.1' ">
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0" />
|
||||
<PackageReference Include="System.Memory" Version="4.5.4" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="Archives\SevenZip\**" />
|
||||
<Compile Remove="Archives\Rar\**" />
|
||||
<Compile Remove="Readers\Rar\**" />
|
||||
<Compile Remove="Common\Rar\**" />
|
||||
<Compile Remove="Common\SevenZip\ArchiveDatabase.cs" />
|
||||
<Compile Remove="Common\SevenZip\ArchiveReader.cs" />
|
||||
<Compile Remove="Common\SevenZip\CStreamSwitch.cs" />
|
||||
<Compile Remove="Common\SevenZip\SevenZipEntry.cs" />
|
||||
<Compile Remove="Common\SevenZip\SevenZipFilePart.cs" />
|
||||
<Compile Remove="Common\SevenZip\SevenZipVolume.cs" />
|
||||
<Compile Remove="Compressors\Rar\**" />
|
||||
<Compile Remove="Compressors\PPMd\**" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Remove="Archives\SevenZip\**" />
|
||||
<EmbeddedResource Remove="Readers\Rar\**" />
|
||||
<EmbeddedResource Remove="Common\Rar\**" />
|
||||
<EmbeddedResource Remove="Compressors\Rar\**" />
|
||||
<EmbeddedResource Remove="Compressors\PPMd\**" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Remove="Archives\SevenZip\**" />
|
||||
<None Remove="Archives\Rar\**" />
|
||||
<None Remove="Readers\Rar\**" />
|
||||
<None Remove="Common\Rar\**" />
|
||||
<None Remove="Compressors\Rar\**" />
|
||||
<None Remove="Compressors\PPMd\**" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,18 +1,108 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Readers;
|
||||
|
||||
namespace SharpCompress
|
||||
{
|
||||
internal static class Utility
|
||||
{
|
||||
public static ReadOnlyCollection<T> ToReadOnly<T>(this ICollection<T> items)
|
||||
public static async ValueTask ForEachAsync<T>(this IEnumerable<T> collection, Func<T, Task> action)
|
||||
{
|
||||
return new ReadOnlyCollection<T>(items);
|
||||
foreach (T item in collection)
|
||||
{
|
||||
await action(item);
|
||||
}
|
||||
}
|
||||
|
||||
private static async ValueTask WritePrimitive<T>(this Stream stream, Action<Memory<byte>> func, CancellationToken cancellationToken)
|
||||
where T : struct
|
||||
{
|
||||
var bytes = Marshal.SizeOf<T>();
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(bytes);
|
||||
var memory = buffer.Memory.Slice(0, bytes);
|
||||
func(memory);
|
||||
await stream.WriteAsync(memory, cancellationToken);
|
||||
}
|
||||
|
||||
public static ValueTask WriteByteAsync(this Stream stream, byte val, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return stream.WritePrimitive<byte>( x => x.Span[0] = val, cancellationToken);
|
||||
}
|
||||
|
||||
public static async ValueTask WriteBytes(this Stream stream, params byte[] val)
|
||||
{
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(val.Length);
|
||||
var memory = buffer.Memory.Slice(0, val.Length);
|
||||
val.CopyTo(memory);
|
||||
await stream.WriteAsync(memory);
|
||||
}
|
||||
|
||||
public static ValueTask WriteUInt16(this Stream stream, ushort val, CancellationToken cancellationToken =default)
|
||||
{
|
||||
return stream.WritePrimitive<ushort>( x => BinaryPrimitives.WriteUInt16LittleEndian(x.Span, val), cancellationToken);
|
||||
}
|
||||
public static ValueTask WriteUInt32(this Stream stream, uint val, CancellationToken cancellationToken= default)
|
||||
{
|
||||
return stream.WritePrimitive<uint>( x => BinaryPrimitives.WriteUInt32LittleEndian(x.Span, val), cancellationToken);
|
||||
}
|
||||
public static ValueTask WriteUInt64(this Stream stream, ulong val, CancellationToken cancellationToken= default)
|
||||
{
|
||||
return stream.WritePrimitive<ulong>( x => BinaryPrimitives.WriteUInt64LittleEndian(x.Span, val), cancellationToken);
|
||||
}
|
||||
|
||||
private static async ValueTask<T?> ReadPrimitive<T>(this Stream stream, Func<ReadOnlyMemory<byte>, T> func, CancellationToken cancellationToken)
|
||||
where T : struct
|
||||
{
|
||||
var bytes = Marshal.SizeOf<T>();
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(bytes);
|
||||
var memory = buffer.Memory.Slice(0, bytes);
|
||||
var n = await stream.ReadAsync(memory, cancellationToken);
|
||||
if (n != memory.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return func(memory);
|
||||
}
|
||||
|
||||
public static async ValueTask<byte> ReadByteAsync(this Stream stream, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await stream.ReadPrimitive(x => x.Span[0], cancellationToken) ?? default;
|
||||
}
|
||||
public static async ValueTask<ushort> ReadUInt16(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return await stream.ReadPrimitive( x => BinaryPrimitives.ReadUInt16LittleEndian(x.Span), cancellationToken)?? default;
|
||||
}
|
||||
public static async ValueTask<uint> ReadUInt32(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return await stream.ReadPrimitive( x => BinaryPrimitives.ReadUInt32LittleEndian(x.Span), cancellationToken)?? default;
|
||||
}
|
||||
public static ValueTask<uint?> ReadUInt32OrNull(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return stream.ReadPrimitive(x => BinaryPrimitives.ReadUInt32LittleEndian(x.Span), cancellationToken);
|
||||
}
|
||||
public static async ValueTask<int> ReadInt32(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return await stream.ReadPrimitive( x => BinaryPrimitives.ReadInt32LittleEndian(x.Span), cancellationToken)?? default;
|
||||
}
|
||||
|
||||
public static async ValueTask<ulong> ReadUInt64(this Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
return await stream.ReadPrimitive( x => BinaryPrimitives.ReadUInt64LittleEndian(x.Span), cancellationToken)?? default;
|
||||
}
|
||||
|
||||
public static async ValueTask<byte[]> ReadBytes(this Stream stream, int bytes, CancellationToken cancellationToken)
|
||||
{
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(bytes);
|
||||
await stream.ReadAsync(buffer.Memory.Slice(0, bytes), cancellationToken);
|
||||
return buffer.Memory.Slice(0, bytes).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs an unsigned bitwise right shift with the specified number
|
||||
/// </summary>
|
||||
@@ -92,13 +182,21 @@ namespace SharpCompress
|
||||
{
|
||||
yield return item;
|
||||
}
|
||||
public static async IAsyncEnumerable<T> AsAsyncEnumerable<T>(this T item)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
yield return item;
|
||||
}
|
||||
|
||||
public static void CheckNotNull(this object obj, string name)
|
||||
public static T CheckNotNull<T>(this T? obj, string name)
|
||||
where T : class
|
||||
{
|
||||
if (obj is null)
|
||||
{
|
||||
throw new ArgumentNullException(name);
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
public static void CheckNotNullOrEmpty(this string obj, string name)
|
||||
@@ -109,6 +207,36 @@ namespace SharpCompress
|
||||
throw new ArgumentException("String is empty.", name);
|
||||
}
|
||||
}
|
||||
|
||||
public static async ValueTask SkipAsync(this Stream source, long advanceAmount, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (source.CanSeek)
|
||||
{
|
||||
source.Position += advanceAmount;
|
||||
return;
|
||||
}
|
||||
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(81920);
|
||||
do
|
||||
{
|
||||
var readCount = 81920;
|
||||
if (readCount > advanceAmount)
|
||||
{
|
||||
readCount = (int)advanceAmount;
|
||||
}
|
||||
int read = await source.ReadAsync(buffer.Memory.Slice(0, readCount), cancellationToken);
|
||||
if (read <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
advanceAmount -= read;
|
||||
if (advanceAmount == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (true);
|
||||
}
|
||||
|
||||
public static void Skip(this Stream source, long advanceAmount)
|
||||
{
|
||||
@@ -164,6 +292,15 @@ namespace SharpCompress
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public static async ValueTask SkipAsync(this Stream source, CancellationToken cancellationToken)
|
||||
{
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(81920);
|
||||
do
|
||||
{
|
||||
}
|
||||
while (await source.ReadAsync(buffer.Memory.Slice(0, 81920), cancellationToken) > 0);
|
||||
}
|
||||
|
||||
public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime)
|
||||
{
|
||||
@@ -229,6 +366,24 @@ namespace SharpCompress
|
||||
DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
return sTime.AddSeconds(unixtime);
|
||||
}
|
||||
|
||||
public static async Task<long> TransferToAsync(this Stream source, Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(81920);
|
||||
long total = 0;
|
||||
while (true)
|
||||
{
|
||||
int bytesRead = await source.ReadAsync(buffer.Memory.Slice(0, 81920), cancellationToken);
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
total += bytesRead;
|
||||
await destination.WriteAsync(buffer.Memory.Slice(0, bytesRead), cancellationToken);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
public static long TransferTo(this Stream source, Stream destination)
|
||||
{
|
||||
@@ -236,7 +391,8 @@ namespace SharpCompress
|
||||
try
|
||||
{
|
||||
long total = 0;
|
||||
while (ReadTransferBlock(source, array, out int count))
|
||||
var count = 0;
|
||||
while ((count = source.Read(array, 0, array.Length)) != 0)
|
||||
{
|
||||
total += count;
|
||||
destination.Write(array, 0, count);
|
||||
@@ -249,31 +405,21 @@ namespace SharpCompress
|
||||
}
|
||||
}
|
||||
|
||||
public static long TransferTo(this Stream source, Stream destination, Common.Entry entry, IReaderExtractionListener readerExtractionListener)
|
||||
public static async ValueTask<long> TransferToAsync(this Stream source, Stream destination, Common.Entry entry, IReaderExtractionListener readerExtractionListener, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] array = GetTransferByteArray();
|
||||
try
|
||||
using var buffer = MemoryPool<byte>.Shared.Rent(81920);
|
||||
var iterations = 0;
|
||||
long total = 0;
|
||||
var count = 0;
|
||||
var slice = buffer.Memory.Slice(0, 81920);
|
||||
while ((count = await source.ReadAsync(slice, cancellationToken)) != 0)
|
||||
{
|
||||
var iterations = 0;
|
||||
long total = 0;
|
||||
while (ReadTransferBlock(source, array, out int count))
|
||||
{
|
||||
total += count;
|
||||
destination.Write(array, 0, count);
|
||||
iterations++;
|
||||
readerExtractionListener.FireEntryExtractionProgress(entry, total, iterations);
|
||||
}
|
||||
return total;
|
||||
total += count;
|
||||
await destination.WriteAsync(slice.Slice(0, count), cancellationToken);
|
||||
iterations++;
|
||||
readerExtractionListener.FireEntryExtractionProgress(entry, total, iterations);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(array);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ReadTransferBlock(Stream source, byte[] array, out int count)
|
||||
{
|
||||
return (count = source.Read(array, 0, array.Length)) != 0;
|
||||
return total;
|
||||
}
|
||||
|
||||
private static byte[] GetTransferByteArray()
|
||||
|
||||
@@ -2,21 +2,21 @@
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Writers
|
||||
{
|
||||
public abstract class AbstractWriter : IWriter
|
||||
{
|
||||
private bool _isDisposed;
|
||||
|
||||
protected AbstractWriter(ArchiveType type, WriterOptions writerOptions)
|
||||
{
|
||||
WriterType = type;
|
||||
WriterOptions = writerOptions;
|
||||
}
|
||||
|
||||
protected void InitalizeStream(Stream stream)
|
||||
protected void InitializeStream(Stream stream)
|
||||
{
|
||||
OutputStream = stream;
|
||||
}
|
||||
@@ -27,33 +27,18 @@ namespace SharpCompress.Writers
|
||||
|
||||
protected WriterOptions WriterOptions { get; }
|
||||
|
||||
public abstract void Write(string filename, Stream source, DateTime? modificationTime);
|
||||
public abstract ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken);
|
||||
|
||||
protected virtual void Dispose(bool isDisposing)
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (isDisposing)
|
||||
{
|
||||
OutputStream.Dispose();
|
||||
}
|
||||
await DisposeAsyncCore();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
protected virtual ValueTask DisposeAsyncCore()
|
||||
{
|
||||
if (!_isDisposed)
|
||||
{
|
||||
GC.SuppressFinalize(this);
|
||||
Dispose(true);
|
||||
_isDisposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
~AbstractWriter()
|
||||
{
|
||||
if (!_isDisposed)
|
||||
{
|
||||
Dispose(false);
|
||||
_isDisposed = true;
|
||||
}
|
||||
return OutputStream.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Compressors;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
@@ -18,22 +20,18 @@ namespace SharpCompress.Writers.GZip
|
||||
{
|
||||
destination = new NonDisposingStream(destination);
|
||||
}
|
||||
InitalizeStream(new GZipStream(destination, CompressionMode.Compress,
|
||||
InitializeStream(new GZipStream(destination, CompressionMode.Compress,
|
||||
options?.CompressionLevel ?? CompressionLevel.Default,
|
||||
WriterOptions.ArchiveEncoding.GetEncoding()));
|
||||
}
|
||||
|
||||
protected override void Dispose(bool isDisposing)
|
||||
protected override ValueTask DisposeAsyncCore()
|
||||
{
|
||||
if (isDisposing)
|
||||
{
|
||||
//dispose here to finish the GZip, GZip won't close the underlying stream
|
||||
OutputStream.Dispose();
|
||||
}
|
||||
base.Dispose(isDisposing);
|
||||
//dispose here to finish the GZip, GZip won't close the underlying stream
|
||||
return OutputStream.DisposeAsync();
|
||||
}
|
||||
|
||||
public override void Write(string filename, Stream source, DateTime? modificationTime)
|
||||
public override async ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_wroteToStream)
|
||||
{
|
||||
@@ -42,7 +40,7 @@ namespace SharpCompress.Writers.GZip
|
||||
GZipStream stream = (GZipStream)OutputStream;
|
||||
stream.FileName = filename;
|
||||
stream.LastModified = modificationTime;
|
||||
source.TransferTo(stream);
|
||||
await source.TransferToAsync(stream, cancellationToken);
|
||||
_wroteToStream = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
|
||||
namespace SharpCompress.Writers
|
||||
{
|
||||
public interface IWriter : IDisposable
|
||||
public interface IWriter : IAsyncDisposable
|
||||
{
|
||||
ArchiveType WriterType { get; }
|
||||
void Write(string filename, Stream source, DateTime? modificationTime);
|
||||
ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -2,43 +2,46 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharpCompress.Writers
|
||||
{
|
||||
public static class IWriterExtensions
|
||||
{
|
||||
public static void Write(this IWriter writer, string entryPath, Stream source)
|
||||
public static ValueTask WriteAsync(this IWriter writer, string entryPath, Stream source, CancellationToken cancellationToken = default)
|
||||
{
|
||||
writer.Write(entryPath, source, null);
|
||||
return writer.WriteAsync(entryPath, source, null, cancellationToken);
|
||||
}
|
||||
|
||||
public static void Write(this IWriter writer, string entryPath, FileInfo source)
|
||||
public static async ValueTask WriteAsync(this IWriter writer, string entryPath, FileInfo source, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!source.Exists)
|
||||
{
|
||||
throw new ArgumentException("Source does not exist: " + source.FullName);
|
||||
}
|
||||
using (var stream = source.OpenRead())
|
||||
|
||||
await using (var stream = source.OpenRead())
|
||||
{
|
||||
writer.Write(entryPath, stream, source.LastWriteTime);
|
||||
await writer.WriteAsync(entryPath, stream, source.LastWriteTime, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Write(this IWriter writer, string entryPath, string source)
|
||||
public static ValueTask WriteAsync(this IWriter writer, string entryPath, string source, CancellationToken cancellationToken = default)
|
||||
{
|
||||
writer.Write(entryPath, new FileInfo(source));
|
||||
return writer.WriteAsync(entryPath, new FileInfo(source), cancellationToken);
|
||||
}
|
||||
|
||||
public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly)
|
||||
public static ValueTask WriteAllAsync(this IWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default)
|
||||
{
|
||||
writer.WriteAll(directory, searchPattern, null, option);
|
||||
return writer.WriteAllAsync(directory, searchPattern, null, option, cancellationToken);
|
||||
}
|
||||
|
||||
public static void WriteAll(this IWriter writer,
|
||||
string directory,
|
||||
string searchPattern = "*",
|
||||
Expression<Func<string, bool>>? fileSearchFunc = null,
|
||||
SearchOption option = SearchOption.TopDirectoryOnly)
|
||||
public static async ValueTask WriteAllAsync(this IWriter writer,
|
||||
string directory,
|
||||
string searchPattern = "*",
|
||||
Expression<Func<string, bool>>? fileSearchFunc = null,
|
||||
SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!Directory.Exists(directory))
|
||||
{
|
||||
@@ -51,7 +54,7 @@ namespace SharpCompress.Writers
|
||||
}
|
||||
foreach (var file in Directory.EnumerateFiles(directory, searchPattern, option).Where(fileSearchFunc.Compile()))
|
||||
{
|
||||
writer.Write(file.Substring(directory.Length), file);
|
||||
await writer.WriteAsync(file.Substring(directory.Length), file, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Tar.Headers;
|
||||
using SharpCompress.Compressors;
|
||||
@@ -12,18 +15,24 @@ namespace SharpCompress.Writers.Tar
|
||||
{
|
||||
public class TarWriter : AbstractWriter
|
||||
{
|
||||
private readonly bool finalizeArchiveOnClose;
|
||||
private bool finalizeArchiveOnClose;
|
||||
|
||||
public TarWriter(Stream destination, TarWriterOptions options)
|
||||
private TarWriter(TarWriterOptions options)
|
||||
: base(ArchiveType.Tar, options)
|
||||
{
|
||||
finalizeArchiveOnClose = options.FinalizeArchiveOnClose;
|
||||
}
|
||||
|
||||
public static async ValueTask<TarWriter> CreateAsync(Stream destination, TarWriterOptions options, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
var tw = new TarWriter(options);
|
||||
tw.finalizeArchiveOnClose = options.FinalizeArchiveOnClose;
|
||||
|
||||
if (!destination.CanWrite)
|
||||
{
|
||||
throw new ArgumentException("Tars require writable streams.");
|
||||
}
|
||||
if (WriterOptions.LeaveStreamOpen)
|
||||
if (tw.WriterOptions.LeaveStreamOpen)
|
||||
{
|
||||
destination = new NonDisposingStream(destination);
|
||||
}
|
||||
@@ -31,11 +40,11 @@ namespace SharpCompress.Writers.Tar
|
||||
{
|
||||
case CompressionType.None:
|
||||
break;
|
||||
case CompressionType.BZip2:
|
||||
case CompressionType.BZip2:
|
||||
{
|
||||
destination = new BZip2Stream(destination, CompressionMode.Compress, false);
|
||||
destination = await BZip2Stream.CreateAsync(destination, CompressionMode.Compress, false, cancellationToken);
|
||||
}
|
||||
break;
|
||||
break;
|
||||
case CompressionType.GZip:
|
||||
{
|
||||
destination = new GZipStream(destination, CompressionMode.Compress);
|
||||
@@ -43,7 +52,7 @@ namespace SharpCompress.Writers.Tar
|
||||
break;
|
||||
case CompressionType.LZip:
|
||||
{
|
||||
destination = new LZipStream(destination, CompressionMode.Compress);
|
||||
destination = await LZipStream.CreateAsync(destination, CompressionMode.Compress);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
@@ -51,12 +60,32 @@ namespace SharpCompress.Writers.Tar
|
||||
throw new InvalidFormatException("Tar does not support compression: " + options.CompressionType);
|
||||
}
|
||||
}
|
||||
InitalizeStream(destination);
|
||||
tw.InitializeStream(destination);
|
||||
return tw;
|
||||
}
|
||||
|
||||
public override void Write(string filename, Stream source, DateTime? modificationTime)
|
||||
public override ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Write(filename, source, modificationTime, null);
|
||||
return WriteAsync(filename, source, modificationTime, null, cancellationToken);
|
||||
}
|
||||
|
||||
public async ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, long? size, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!source.CanSeek && size == null)
|
||||
{
|
||||
throw new ArgumentException("Seekable stream is required if no size is given.");
|
||||
}
|
||||
|
||||
long realSize = size ?? source.Length;
|
||||
|
||||
TarHeader header = new(WriterOptions.ArchiveEncoding);
|
||||
|
||||
header.LastModifiedTime = modificationTime ?? TarHeader.EPOCH;
|
||||
header.Name = NormalizeFilename(filename);
|
||||
header.Size = realSize;
|
||||
await header.WriteAsync(OutputStream);
|
||||
size = await source.TransferToAsync(OutputStream, cancellationToken);
|
||||
await PadTo512Async(size.Value, false);
|
||||
}
|
||||
|
||||
private string NormalizeFilename(string filename)
|
||||
@@ -72,26 +101,7 @@ namespace SharpCompress.Writers.Tar
|
||||
return filename.Trim('/');
|
||||
}
|
||||
|
||||
public void Write(string filename, Stream source, DateTime? modificationTime, long? size)
|
||||
{
|
||||
if (!source.CanSeek && size is null)
|
||||
{
|
||||
throw new ArgumentException("Seekable stream is required if no size is given.");
|
||||
}
|
||||
|
||||
long realSize = size ?? source.Length;
|
||||
|
||||
TarHeader header = new TarHeader(WriterOptions.ArchiveEncoding);
|
||||
|
||||
header.LastModifiedTime = modificationTime ?? TarHeader.EPOCH;
|
||||
header.Name = NormalizeFilename(filename);
|
||||
header.Size = realSize;
|
||||
header.Write(OutputStream);
|
||||
size = source.TransferTo(OutputStream);
|
||||
PadTo512(size.Value, false);
|
||||
}
|
||||
|
||||
private void PadTo512(long size, bool forceZeros)
|
||||
private async Task PadTo512Async(long size, bool forceZeros)
|
||||
{
|
||||
int zeros = (int)size % 512;
|
||||
if (zeros == 0 && !forceZeros)
|
||||
@@ -99,33 +109,31 @@ namespace SharpCompress.Writers.Tar
|
||||
return;
|
||||
}
|
||||
zeros = 512 - zeros;
|
||||
OutputStream.Write(stackalloc byte[zeros]);
|
||||
using var zeroBuffer = MemoryPool<byte>.Shared.Rent(zeros);
|
||||
zeroBuffer.Memory.Span.Clear();
|
||||
await OutputStream.WriteAsync(zeroBuffer.Memory.Slice(0, zeros));
|
||||
}
|
||||
|
||||
protected override void Dispose(bool isDisposing)
|
||||
protected override async ValueTask DisposeAsyncCore()
|
||||
{
|
||||
if (isDisposing)
|
||||
if (finalizeArchiveOnClose)
|
||||
{
|
||||
if (finalizeArchiveOnClose)
|
||||
{
|
||||
PadTo512(0, true);
|
||||
PadTo512(0, true);
|
||||
}
|
||||
switch (OutputStream)
|
||||
{
|
||||
case BZip2Stream b:
|
||||
{
|
||||
b.Finish();
|
||||
break;
|
||||
}
|
||||
case LZipStream l:
|
||||
{
|
||||
l.Finish();
|
||||
break;
|
||||
}
|
||||
}
|
||||
await PadTo512Async(0, true);
|
||||
await PadTo512Async(0, true);
|
||||
}
|
||||
switch (OutputStream)
|
||||
{
|
||||
/* case BZip2Stream b:
|
||||
{
|
||||
await b.FinishAsync(CancellationToken.None);
|
||||
break;
|
||||
} */
|
||||
case LZipStream l:
|
||||
{
|
||||
await l.FinishAsync();
|
||||
break;
|
||||
}
|
||||
}
|
||||
base.Dispose(isDisposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Writers.GZip;
|
||||
using SharpCompress.Writers.Tar;
|
||||
@@ -9,7 +11,7 @@ namespace SharpCompress.Writers
|
||||
{
|
||||
public static class WriterFactory
|
||||
{
|
||||
public static IWriter Open(Stream stream, ArchiveType archiveType, WriterOptions writerOptions)
|
||||
public static async ValueTask<IWriter> OpenAsync(Stream stream, ArchiveType archiveType, WriterOptions writerOptions, CancellationToken cancellationToken = default)
|
||||
{
|
||||
switch (archiveType)
|
||||
{
|
||||
@@ -26,9 +28,9 @@ namespace SharpCompress.Writers
|
||||
return new ZipWriter(stream, new ZipWriterOptions(writerOptions));
|
||||
}
|
||||
case ArchiveType.Tar:
|
||||
{
|
||||
return new TarWriter(stream, new TarWriterOptions(writerOptions));
|
||||
}
|
||||
{
|
||||
return await TarWriter.CreateAsync(stream, new TarWriterOptions(writerOptions), cancellationToken);
|
||||
}
|
||||
default:
|
||||
{
|
||||
throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Zip;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
@@ -30,7 +32,7 @@ namespace SharpCompress.Writers.Zip
|
||||
internal ushort Zip64HeaderOffset { get; set; }
|
||||
internal ulong HeaderOffset { get; }
|
||||
|
||||
internal uint Write(Stream outputStream)
|
||||
internal async ValueTask<uint> WriteAsync(Stream outputStream, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] encodedFilename = archiveEncoding.Encode(fileName);
|
||||
byte[] encodedComment = archiveEncoding.Encode(Comment ?? string.Empty);
|
||||
@@ -71,63 +73,42 @@ namespace SharpCompress.Writers.Zip
|
||||
usedCompression = ZipCompressionMethod.None;
|
||||
}
|
||||
|
||||
Span<byte> intBuf = stackalloc byte[] { 80, 75, 1, 2, version, 0, version, 0 };
|
||||
byte[] intBuf = { 80, 75, 1, 2, version, 0, version, 0 };
|
||||
//constant sig, then version made by, then version to extract
|
||||
outputStream.Write(intBuf);
|
||||
await outputStream.WriteAsync(intBuf, 0, 8, cancellationToken);
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)flags);
|
||||
outputStream.Write(intBuf.Slice(0, 2));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)usedCompression);
|
||||
outputStream.Write(intBuf.Slice(0, 2)); // zipping method
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, ModificationTime.DateTimeToDosTime());
|
||||
outputStream.Write(intBuf.Slice(0, 4));
|
||||
await outputStream.WriteUInt16( (ushort)flags, cancellationToken);
|
||||
await outputStream.WriteUInt16( (ushort)usedCompression, cancellationToken);// zipping method
|
||||
await outputStream.WriteUInt32(ModificationTime.DateTimeToDosTime(), cancellationToken); // zipping date and time
|
||||
|
||||
// zipping date and time
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, Crc);
|
||||
outputStream.Write(intBuf.Slice(0, 4)); // file CRC
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, compressedvalue);
|
||||
outputStream.Write(intBuf.Slice(0, 4)); // compressed file size
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, decompressedvalue);
|
||||
outputStream.Write(intBuf.Slice(0, 4)); // uncompressed file size
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)encodedFilename.Length);
|
||||
outputStream.Write(intBuf.Slice(0, 2)); // Filename in zip
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)extralength);
|
||||
outputStream.Write(intBuf.Slice(0, 2)); // extra length
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)encodedComment.Length);
|
||||
outputStream.Write(intBuf.Slice(0, 2));
|
||||
await outputStream.WriteUInt32(Crc, cancellationToken); // file CRC
|
||||
await outputStream.WriteUInt32(compressedvalue, cancellationToken); // compressed file size
|
||||
await outputStream.WriteUInt32(decompressedvalue, cancellationToken); // uncompressed file size
|
||||
await outputStream.WriteUInt16((ushort)encodedFilename.Length, cancellationToken); // Filename in zip
|
||||
await outputStream.WriteUInt16( (ushort)extralength, cancellationToken); // extra length
|
||||
await outputStream.WriteUInt16((ushort)encodedComment.Length, cancellationToken);
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 0);
|
||||
outputStream.Write(intBuf.Slice(0, 2)); // disk=0
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)flags);
|
||||
outputStream.Write(intBuf.Slice(0, 2)); // file type: binary
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)flags);
|
||||
outputStream.Write(intBuf.Slice(0, 2)); // Internal file attributes
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 0x8100);
|
||||
outputStream.Write(intBuf.Slice(0, 2));
|
||||
await outputStream.WriteUInt16(0, cancellationToken); // disk=0
|
||||
await outputStream.WriteUInt16( (ushort)flags, cancellationToken); // file type: binary
|
||||
await outputStream.WriteUInt16( (ushort)flags, cancellationToken); // Internal file attributes
|
||||
await outputStream.WriteUInt16(0x8100, cancellationToken);
|
||||
|
||||
// External file attributes (normal/readable)
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, headeroffsetvalue);
|
||||
outputStream.Write(intBuf.Slice(0, 4)); // Offset of header
|
||||
await outputStream.WriteUInt32(headeroffsetvalue, cancellationToken); // Offset of header
|
||||
|
||||
outputStream.Write(encodedFilename, 0, encodedFilename.Length);
|
||||
await outputStream.WriteAsync(encodedFilename, 0, encodedFilename.Length, cancellationToken);
|
||||
if (zip64)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 0x0001);
|
||||
outputStream.Write(intBuf.Slice(0, 2));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)(extralength - 4));
|
||||
outputStream.Write(intBuf.Slice(0, 2));
|
||||
await outputStream.WriteUInt16(0x0001, cancellationToken);
|
||||
await outputStream.WriteUInt16((ushort)(extralength - 4), cancellationToken);
|
||||
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, Decompressed);
|
||||
outputStream.Write(intBuf);
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, Compressed);
|
||||
outputStream.Write(intBuf);
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, HeaderOffset);
|
||||
outputStream.Write(intBuf);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, 0);
|
||||
outputStream.Write(intBuf.Slice(0, 4)); // VolumeNumber = 0
|
||||
await outputStream.WriteUInt64(Decompressed, cancellationToken);
|
||||
await outputStream.WriteUInt64(Compressed, cancellationToken);
|
||||
await outputStream.WriteUInt64(HeaderOffset, cancellationToken);
|
||||
await outputStream.WriteUInt32(0, cancellationToken); // VolumeNumber = 0
|
||||
}
|
||||
|
||||
outputStream.Write(encodedComment, 0, encodedComment.Length);
|
||||
await outputStream.WriteAsync(encodedComment, 0, encodedComment.Length, cancellationToken);
|
||||
|
||||
return (uint)(8 + 2 + 2 + 4 + 4 + 4 + 4 + 2 + 2 + 2
|
||||
+ 2 + 2 + 2 + 2 + 4 + encodedFilename.Length + extralength + encodedComment.Length);
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Common;
|
||||
using SharpCompress.Common.Zip;
|
||||
using SharpCompress.Common.Zip.Headers;
|
||||
@@ -10,7 +13,7 @@ using SharpCompress.Compressors;
|
||||
using SharpCompress.Compressors.BZip2;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
using SharpCompress.Compressors.LZMA;
|
||||
using SharpCompress.Compressors.PPMd;
|
||||
//using SharpCompress.Compressors.PPMd;
|
||||
using SharpCompress.IO;
|
||||
|
||||
namespace SharpCompress.Writers.Zip
|
||||
@@ -19,10 +22,10 @@ namespace SharpCompress.Writers.Zip
|
||||
{
|
||||
private readonly CompressionType compressionType;
|
||||
private readonly CompressionLevel compressionLevel;
|
||||
private readonly List<ZipCentralDirectoryEntry> entries = new List<ZipCentralDirectoryEntry>();
|
||||
private readonly List<ZipCentralDirectoryEntry> entries = new();
|
||||
private readonly string zipComment;
|
||||
private long streamPosition;
|
||||
private PpmdProperties? ppmdProps;
|
||||
// private PpmdProperties? ppmdProps;
|
||||
private readonly bool isZip64;
|
||||
|
||||
public ZipWriter(Stream destination, ZipWriterOptions zipWriterOptions)
|
||||
@@ -42,29 +45,26 @@ namespace SharpCompress.Writers.Zip
|
||||
{
|
||||
destination = new NonDisposingStream(destination);
|
||||
}
|
||||
InitalizeStream(destination);
|
||||
InitializeStream(destination);
|
||||
}
|
||||
|
||||
private PpmdProperties PpmdProperties
|
||||
/* private PpmdProperties PpmdProperties
|
||||
{
|
||||
get
|
||||
{
|
||||
return ppmdProps ??= new PpmdProperties();
|
||||
}
|
||||
}
|
||||
} */
|
||||
|
||||
protected override void Dispose(bool isDisposing)
|
||||
protected override async ValueTask DisposeAsyncCore()
|
||||
{
|
||||
if (isDisposing)
|
||||
ulong size = 0;
|
||||
foreach (ZipCentralDirectoryEntry entry in entries)
|
||||
{
|
||||
ulong size = 0;
|
||||
foreach (ZipCentralDirectoryEntry entry in entries)
|
||||
{
|
||||
size += entry.Write(OutputStream);
|
||||
}
|
||||
WriteEndRecord(size);
|
||||
size += await entry.WriteAsync(OutputStream, CancellationToken.None);
|
||||
}
|
||||
base.Dispose(isDisposing);
|
||||
await WriteEndRecordAsync(size);
|
||||
await base.DisposeAsyncCore();
|
||||
}
|
||||
|
||||
private static ZipCompressionMethod ToZipCompressionMethod(CompressionType compressionType)
|
||||
@@ -96,23 +96,21 @@ namespace SharpCompress.Writers.Zip
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(string entryPath, Stream source, DateTime? modificationTime)
|
||||
public override ValueTask WriteAsync(string filename, Stream source, DateTime? modificationTime, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Write(entryPath, source, new ZipWriterEntryOptions()
|
||||
return WriteAsync(filename, source, new ZipWriterEntryOptions()
|
||||
{
|
||||
ModificationDateTime = modificationTime
|
||||
});
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public void Write(string entryPath, Stream source, ZipWriterEntryOptions zipWriterEntryOptions)
|
||||
public async ValueTask WriteAsync(string entryPath, Stream source, ZipWriterEntryOptions zipWriterEntryOptions, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (Stream output = WriteToStream(entryPath, zipWriterEntryOptions))
|
||||
{
|
||||
source.TransferTo(output);
|
||||
}
|
||||
await using Stream output = await WriteToStreamAsync(entryPath, zipWriterEntryOptions, cancellationToken);
|
||||
await source.CopyToAsync(output, cancellationToken);
|
||||
}
|
||||
|
||||
public Stream WriteToStream(string entryPath, ZipWriterEntryOptions options)
|
||||
public async ValueTask<Stream> WriteToStreamAsync(string entryPath, ZipWriterEntryOptions options, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var compression = ToZipCompressionMethod(options.CompressionType ?? compressionType);
|
||||
|
||||
@@ -132,10 +130,12 @@ namespace SharpCompress.Writers.Zip
|
||||
useZip64 = options.EnableZip64.Value;
|
||||
}
|
||||
|
||||
var headersize = (uint)WriteHeader(entryPath, options, entry, useZip64);
|
||||
var headersize = (uint)(await WriteHeaderAsync(entryPath, options, entry, useZip64, cancellationToken));
|
||||
streamPosition += headersize;
|
||||
return new ZipWritingStream(this, OutputStream, entry, compression,
|
||||
var s = new ZipWritingStream(this, OutputStream, entry, compression,
|
||||
options.DeflateCompressionLevel ?? compressionLevel);
|
||||
await s.InitializeAsync(cancellationToken);
|
||||
return s;
|
||||
}
|
||||
|
||||
private string NormalizeFilename(string filename)
|
||||
@@ -151,7 +151,8 @@ namespace SharpCompress.Writers.Zip
|
||||
return filename.Trim('/');
|
||||
}
|
||||
|
||||
private int WriteHeader(string filename, ZipWriterEntryOptions zipWriterEntryOptions, ZipCentralDirectoryEntry entry, bool useZip64)
|
||||
private async ValueTask<int> WriteHeaderAsync(string filename, ZipWriterEntryOptions zipWriterEntryOptions, ZipCentralDirectoryEntry entry, bool useZip64,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// We err on the side of caution until the zip specification clarifies how to support this
|
||||
if (!OutputStream.CanSeek && useZip64)
|
||||
@@ -162,23 +163,21 @@ namespace SharpCompress.Writers.Zip
|
||||
var explicitZipCompressionInfo = ToZipCompressionMethod(zipWriterEntryOptions.CompressionType ?? compressionType);
|
||||
byte[] encodedFilename = WriterOptions.ArchiveEncoding.Encode(filename);
|
||||
|
||||
Span<byte> intBuf = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, ZipHeaderFactory.ENTRY_HEADER_BYTES);
|
||||
OutputStream.Write(intBuf);
|
||||
await OutputStream.WriteUInt32(ZipHeaderFactory.ENTRY_HEADER_BYTES, cancellationToken: cancellationToken);
|
||||
if (explicitZipCompressionInfo == ZipCompressionMethod.Deflate)
|
||||
{
|
||||
if (OutputStream.CanSeek && useZip64)
|
||||
{
|
||||
OutputStream.Write(stackalloc byte[] { 45, 0 }); //smallest allowed version for zip64
|
||||
await OutputStream.WriteBytes(45, 0 ); //smallest allowed version for zip64
|
||||
}
|
||||
else
|
||||
{
|
||||
OutputStream.Write(stackalloc byte[] { 20, 0 }); //older version which is more compatible
|
||||
await OutputStream.WriteBytes(20, 0 ); //older version which is more compatible
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
OutputStream.Write(stackalloc byte[] { 63, 0 }); //version says we used PPMd or LZMA
|
||||
await OutputStream.WriteBytes(63, 0); //version says we used PPMd or LZMA
|
||||
}
|
||||
HeaderFlags flags = Equals(WriterOptions.ArchiveEncoding.GetEncoding(), Encoding.UTF8) ? HeaderFlags.Efs : 0;
|
||||
if (!OutputStream.CanSeek)
|
||||
@@ -191,19 +190,13 @@ namespace SharpCompress.Writers.Zip
|
||||
}
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)flags);
|
||||
OutputStream.Write(intBuf.Slice(0, 2));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)explicitZipCompressionInfo);
|
||||
OutputStream.Write(intBuf.Slice(0, 2)); // zipping method
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, zipWriterEntryOptions.ModificationDateTime.DateTimeToDosTime());
|
||||
OutputStream.Write(intBuf);
|
||||
|
||||
// zipping date and time
|
||||
OutputStream.Write(stackalloc byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
|
||||
await OutputStream.WriteUInt16((ushort)flags, cancellationToken: cancellationToken);
|
||||
await OutputStream.WriteUInt16((ushort)explicitZipCompressionInfo, cancellationToken: cancellationToken); // zipping method
|
||||
await OutputStream.WriteUInt32(zipWriterEntryOptions.ModificationDateTime.DateTimeToDosTime(), cancellationToken: cancellationToken); // zipping date and time
|
||||
// unused CRC, un/compressed size, updated later
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)encodedFilename.Length);
|
||||
OutputStream.Write(intBuf.Slice(0, 2)); // filename length
|
||||
await OutputStream.WriteBytes(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
|
||||
await OutputStream.WriteUInt16((ushort)encodedFilename.Length, cancellationToken: cancellationToken);// filename length
|
||||
|
||||
var extralength = 0;
|
||||
if (OutputStream.CanSeek && useZip64)
|
||||
@@ -211,31 +204,26 @@ namespace SharpCompress.Writers.Zip
|
||||
extralength = 2 + 2 + 8 + 8;
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)extralength);
|
||||
OutputStream.Write(intBuf.Slice(0, 2)); // extra length
|
||||
OutputStream.Write(encodedFilename, 0, encodedFilename.Length);
|
||||
await OutputStream.WriteUInt16( (ushort)extralength, cancellationToken: cancellationToken); // extra length
|
||||
await OutputStream.WriteAsync(encodedFilename, 0, encodedFilename.Length, cancellationToken);
|
||||
|
||||
if (extralength != 0)
|
||||
{
|
||||
OutputStream.Write(new byte[extralength], 0, extralength); // reserve space for zip64 data
|
||||
await OutputStream.WriteAsync(new byte[extralength], 0, extralength, cancellationToken); // reserve space for zip64 data
|
||||
entry.Zip64HeaderOffset = (ushort)(6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length);
|
||||
}
|
||||
|
||||
return 6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length + extralength;
|
||||
}
|
||||
|
||||
private void WriteFooter(uint crc, uint compressed, uint uncompressed)
|
||||
private async ValueTask WriteFooterAsync(uint crc, uint compressed, uint uncompressed)
|
||||
{
|
||||
Span<byte> intBuf = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, crc);
|
||||
OutputStream.Write(intBuf);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, compressed);
|
||||
OutputStream.Write(intBuf);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, uncompressed);
|
||||
OutputStream.Write(intBuf);
|
||||
await OutputStream.WriteUInt32(crc);
|
||||
await OutputStream.WriteUInt32(compressed);
|
||||
await OutputStream.WriteUInt32(uncompressed);
|
||||
}
|
||||
|
||||
private void WriteEndRecord(ulong size)
|
||||
private async ValueTask WriteEndRecordAsync(ulong size)
|
||||
{
|
||||
|
||||
var zip64 = isZip64 || entries.Count > ushort.MaxValue || streamPosition >= uint.MaxValue || size >= uint.MaxValue;
|
||||
@@ -243,71 +231,58 @@ namespace SharpCompress.Writers.Zip
|
||||
var sizevalue = size >= uint.MaxValue ? uint.MaxValue : (uint)size;
|
||||
var streampositionvalue = streamPosition >= uint.MaxValue ? uint.MaxValue : (uint)streamPosition;
|
||||
|
||||
Span<byte> intBuf = stackalloc byte[8];
|
||||
if (zip64)
|
||||
{
|
||||
var recordlen = 2 + 2 + 4 + 4 + 8 + 8 + 8 + 8;
|
||||
|
||||
// Write zip64 end of central directory record
|
||||
OutputStream.Write(stackalloc byte[] { 80, 75, 6, 6 });
|
||||
await OutputStream.WriteBytes(80, 75, 6, 6);
|
||||
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, (ulong)recordlen);
|
||||
OutputStream.Write(intBuf); // Size of zip64 end of central directory record
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 45);
|
||||
OutputStream.Write(intBuf.Slice(0, 2)); // Made by
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 45);
|
||||
OutputStream.Write(intBuf.Slice(0, 2)); // Version needed
|
||||
await OutputStream.WriteUInt64((ulong)recordlen); // Size of zip64 end of central directory record
|
||||
await OutputStream.WriteUInt16(45); // Made by
|
||||
await OutputStream.WriteUInt16(45); // Version needed
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, 0);
|
||||
OutputStream.Write(intBuf.Slice(0, 4)); // Disk number
|
||||
OutputStream.Write(intBuf.Slice(0, 4)); // Central dir disk
|
||||
await OutputStream.WriteUInt32(0); // Disk number
|
||||
await OutputStream.WriteUInt32(0); // Central dir disk
|
||||
|
||||
// TODO: entries.Count is int, so max 2^31 files
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, (ulong)entries.Count);
|
||||
OutputStream.Write(intBuf); // Entries in this disk
|
||||
OutputStream.Write(intBuf); // Total entries
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, size);
|
||||
OutputStream.Write(intBuf); // Central Directory size
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, (ulong)streamPosition);
|
||||
OutputStream.Write(intBuf); // Disk offset
|
||||
await OutputStream.WriteUInt64((ulong)entries.Count); // Entries in this disk
|
||||
await OutputStream.WriteUInt64((ulong)entries.Count); // Total entries
|
||||
await OutputStream.WriteUInt64(size); // Central Directory size
|
||||
await OutputStream.WriteUInt64((ulong)streamPosition); // Disk offset
|
||||
|
||||
// Write zip64 end of central directory locator
|
||||
OutputStream.Write(stackalloc byte[] { 80, 75, 6, 7 });
|
||||
await OutputStream.WriteBytes( 80, 75, 6, 7);
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, 0);
|
||||
OutputStream.Write(intBuf.Slice(0, 4)); // Entry disk
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, (ulong)streamPosition + size);
|
||||
OutputStream.Write(intBuf); // Offset to the zip64 central directory
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, 1);
|
||||
OutputStream.Write(intBuf.Slice(0, 4)); // Number of disks
|
||||
await OutputStream.WriteUInt32(0);// Entry disk
|
||||
await OutputStream.WriteUInt64((ulong)streamPosition + size); // Offset to the zip64 central directory
|
||||
await OutputStream.WriteUInt32( 1); // Number of disks
|
||||
|
||||
streamPosition += recordlen + (4 + 4 + 8 + 4);
|
||||
streampositionvalue = streamPosition >= uint.MaxValue ? uint.MaxValue : (uint)streampositionvalue;
|
||||
}
|
||||
|
||||
// Write normal end of central directory record
|
||||
OutputStream.Write(stackalloc byte[] { 80, 75, 5, 6, 0, 0, 0, 0 });
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)entries.Count);
|
||||
OutputStream.Write(intBuf.Slice(0, 2));
|
||||
OutputStream.Write(intBuf.Slice(0, 2));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, sizevalue);
|
||||
OutputStream.Write(intBuf.Slice(0, 4));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, streampositionvalue);
|
||||
OutputStream.Write(intBuf.Slice(0, 4));
|
||||
await OutputStream.WriteBytes(80, 75, 5, 6, 0, 0, 0, 0);
|
||||
await OutputStream.WriteUInt16((ushort)entries.Count);
|
||||
await OutputStream.WriteUInt16((ushort)entries.Count);
|
||||
await OutputStream.WriteUInt32(sizevalue);
|
||||
await OutputStream.WriteUInt32( streampositionvalue);
|
||||
byte[] encodedComment = WriterOptions.ArchiveEncoding.Encode(zipComment);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)encodedComment.Length);
|
||||
OutputStream.Write(intBuf.Slice(0, 2));
|
||||
OutputStream.Write(encodedComment, 0, encodedComment.Length);
|
||||
await OutputStream.WriteUInt16((ushort)encodedComment.Length);
|
||||
await OutputStream.WriteAsync(encodedComment, 0, encodedComment.Length);
|
||||
}
|
||||
|
||||
#region Nested type: ZipWritingStream
|
||||
|
||||
internal class ZipWritingStream : Stream
|
||||
private class ZipWritingStream : AsyncStream
|
||||
{
|
||||
private readonly CRC32 crc = new CRC32();
|
||||
private readonly ZipCentralDirectoryEntry entry;
|
||||
private readonly Stream originalStream;
|
||||
private readonly Stream writeStream;
|
||||
#nullable disable
|
||||
private Stream writeStream;
|
||||
#nullable enable
|
||||
private readonly ZipWriter writer;
|
||||
private readonly ZipCompressionMethod zipCompressionMethod;
|
||||
private readonly CompressionLevel compressionLevel;
|
||||
@@ -327,7 +302,11 @@ namespace SharpCompress.Writers.Zip
|
||||
this.entry = entry;
|
||||
this.zipCompressionMethod = zipCompressionMethod;
|
||||
this.compressionLevel = compressionLevel;
|
||||
writeStream = GetWriteStream(originalStream);
|
||||
}
|
||||
|
||||
public async ValueTask InitializeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
writeStream = await GetWriteStream(originalStream, cancellationToken);
|
||||
}
|
||||
|
||||
public override bool CanRead => false;
|
||||
@@ -340,7 +319,7 @@ namespace SharpCompress.Writers.Zip
|
||||
|
||||
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
|
||||
private Stream GetWriteStream(Stream writeStream)
|
||||
private async ValueTask<Stream> GetWriteStream(Stream writeStream, CancellationToken cancellationToken)
|
||||
{
|
||||
counting = new CountingWritableSubStream(writeStream);
|
||||
Stream output = counting;
|
||||
@@ -356,25 +335,22 @@ namespace SharpCompress.Writers.Zip
|
||||
}
|
||||
case ZipCompressionMethod.BZip2:
|
||||
{
|
||||
return new BZip2Stream(counting, CompressionMode.Compress, false);
|
||||
}
|
||||
return await BZip2Stream.CreateAsync(counting, CompressionMode.Compress, false, cancellationToken);
|
||||
}
|
||||
case ZipCompressionMethod.LZMA:
|
||||
{
|
||||
counting.WriteByte(9);
|
||||
counting.WriteByte(20);
|
||||
counting.WriteByte(5);
|
||||
counting.WriteByte(0);
|
||||
await counting.WriteBytes(9, 20, 5, 0);
|
||||
|
||||
LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek),
|
||||
false, counting);
|
||||
counting.Write(lzmaStream.Properties, 0, lzmaStream.Properties.Length);
|
||||
await counting.WriteAsync(lzmaStream.Properties, 0, lzmaStream.Properties.Length, cancellationToken);
|
||||
return lzmaStream;
|
||||
}
|
||||
case ZipCompressionMethod.PPMd:
|
||||
/* case ZipCompressionMethod.PPMd:
|
||||
{
|
||||
counting.Write(writer.PpmdProperties.Properties, 0, 2);
|
||||
return new PpmdStream(writer.PpmdProperties, counting, true);
|
||||
}
|
||||
} */
|
||||
default:
|
||||
{
|
||||
throw new NotSupportedException("CompressionMethod: " + zipCompressionMethod);
|
||||
@@ -382,7 +358,7 @@ namespace SharpCompress.Writers.Zip
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
if (isDisposed)
|
||||
{
|
||||
@@ -391,17 +367,14 @@ namespace SharpCompress.Writers.Zip
|
||||
|
||||
isDisposed = true;
|
||||
|
||||
base.Dispose(disposing);
|
||||
if (disposing)
|
||||
{
|
||||
writeStream.Dispose();
|
||||
await writeStream.DisposeAsync();
|
||||
|
||||
if (limitsExceeded)
|
||||
{
|
||||
// We have written invalid data into the archive,
|
||||
// so we destroy it now, instead of allowing the user to continue
|
||||
// with a defunct archive
|
||||
originalStream.Dispose();
|
||||
await originalStream.DisposeAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -416,19 +389,19 @@ namespace SharpCompress.Writers.Zip
|
||||
if (originalStream.CanSeek)
|
||||
{
|
||||
originalStream.Position = (long)(entry.HeaderOffset + 6);
|
||||
originalStream.WriteByte(0);
|
||||
await originalStream.WriteByteAsync(0);
|
||||
|
||||
if (counting.Count == 0 && entry.Decompressed == 0)
|
||||
{
|
||||
// set compression to STORED for zero byte files (no compression data)
|
||||
originalStream.Position = (long)(entry.HeaderOffset + 8);
|
||||
originalStream.WriteByte(0);
|
||||
originalStream.WriteByte(0);
|
||||
await originalStream.WriteByteAsync(0);
|
||||
await originalStream.WriteByteAsync(0);
|
||||
}
|
||||
|
||||
originalStream.Position = (long)(entry.HeaderOffset + 14);
|
||||
|
||||
writer.WriteFooter(entry.Crc, compressedvalue, decompressedvalue);
|
||||
await writer.WriteFooterAsync(entry.Crc, compressedvalue, decompressedvalue);
|
||||
|
||||
// Ideally, we should not throw from Dispose()
|
||||
// We should not get here as the Write call checks the limits
|
||||
@@ -442,16 +415,11 @@ namespace SharpCompress.Writers.Zip
|
||||
if (entry.Zip64HeaderOffset != 0)
|
||||
{
|
||||
originalStream.Position = (long)(entry.HeaderOffset + entry.Zip64HeaderOffset);
|
||||
Span<byte> intBuf = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 0x0001);
|
||||
originalStream.Write(intBuf.Slice(0, 2));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(intBuf, 8 + 8);
|
||||
originalStream.Write(intBuf.Slice(0, 2));
|
||||
await originalStream.WriteUInt16(0x0001);
|
||||
await originalStream.WriteUInt16(8 + 8);
|
||||
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, entry.Decompressed);
|
||||
originalStream.Write(intBuf);
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(intBuf, entry.Compressed);
|
||||
originalStream.Write(intBuf);
|
||||
await originalStream.WriteUInt64(entry.Decompressed);
|
||||
await originalStream.WriteUInt64(entry.Compressed);
|
||||
}
|
||||
|
||||
originalStream.Position = writer.streamPosition + (long)entry.Compressed;
|
||||
@@ -470,28 +438,19 @@ namespace SharpCompress.Writers.Zip
|
||||
throw new NotSupportedException("Streams larger than 4GiB are not supported for non-seekable streams");
|
||||
}
|
||||
|
||||
Span<byte> intBuf = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(intBuf, ZipHeaderFactory.POST_DATA_DESCRIPTOR);
|
||||
originalStream.Write(intBuf);
|
||||
writer.WriteFooter(entry.Crc,
|
||||
await originalStream.WriteUInt32(ZipHeaderFactory.POST_DATA_DESCRIPTOR);
|
||||
await writer.WriteFooterAsync(entry.Crc,
|
||||
compressedvalue,
|
||||
decompressedvalue);
|
||||
writer.streamPosition += (long)entry.Compressed + 16;
|
||||
}
|
||||
writer.entries.Add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
public override Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
writeStream.Flush();
|
||||
return writeStream.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
@@ -502,7 +461,7 @@ namespace SharpCompress.Writers.Zip
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
// We check the limits first, because we can keep the archive consistent
|
||||
// if we can prevent the writes from happening
|
||||
@@ -517,7 +476,7 @@ namespace SharpCompress.Writers.Zip
|
||||
|
||||
decompressed += (uint)count;
|
||||
crc.SlurpBlock(buffer, offset, count);
|
||||
writeStream.Write(buffer, offset, count);
|
||||
await writeStream.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
|
||||
if (entry.Zip64HeaderOffset == 0)
|
||||
{
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using SharpCompress.Compressors;
|
||||
using SharpCompress.Compressors.ADC;
|
||||
using SharpCompress.Compressors.Deflate;
|
||||
@@ -128,16 +129,16 @@ namespace SharpCompress.Test
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestCrc32Stream()
|
||||
public async Task TestCrc32Stream()
|
||||
{
|
||||
using (FileStream decFs = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar")))
|
||||
await using (FileStream decFs = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar")))
|
||||
{
|
||||
var crc32 = new CRC32().GetCrc32(decFs);
|
||||
decFs.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
var memory = new MemoryStream();
|
||||
var crcStream = new Crc32Stream(memory, 0xEDB88320, 0xFFFFFFFF);
|
||||
decFs.CopyTo(crcStream);
|
||||
await decFs.CopyToAsync(crcStream);
|
||||
|
||||
decFs.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user