1
0
mirror of https://github.com/ppy/osu.git synced 2024-11-16 16:38:22 +08:00
osu-lazer/osu.Game/IO/Archives/ZipArchiveReader.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

95 lines
2.9 KiB
C#
Raw Normal View History

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
2018-04-13 17:19:50 +08:00
2022-06-17 15:37:17 +08:00
#nullable disable
using System.Buffers;
using System.Collections.Generic;
using System.IO;
2016-10-05 05:08:43 +08:00
using System.Linq;
using Microsoft.Toolkit.HighPerformance;
using osu.Framework.IO.Stores;
using SharpCompress.Archives.Zip;
using SixLabors.ImageSharp.Memory;
2018-04-13 17:19:50 +08:00
namespace osu.Game.IO.Archives
{
public sealed class ZipArchiveReader : ArchiveReader
{
private readonly Stream archiveStream;
private readonly ZipArchive archive;
2018-04-13 17:19:50 +08:00
public ZipArchiveReader(Stream archiveStream, string name = null)
2018-02-15 09:20:23 +08:00
: base(name)
{
this.archiveStream = archiveStream;
archive = ZipArchive.Open(archiveStream);
}
2018-04-13 17:19:50 +08:00
2016-11-05 19:00:14 +08:00
public override Stream GetStream(string name)
{
ZipArchiveEntry entry = archive.Entries.SingleOrDefault(e => e.Key == name);
if (entry == null)
return null;
2018-04-13 17:19:50 +08:00
var owner = MemoryAllocator.Default.Allocate<byte>((int)entry.Size);
2018-04-13 17:19:50 +08:00
using (Stream s = entry.OpenEntryStream())
2024-03-06 10:42:20 +08:00
s.ReadExactly(owner.Memory.Span);
2018-04-13 17:19:50 +08:00
return new MemoryOwnerMemoryStream(owner);
}
2018-04-13 17:19:50 +08:00
2016-10-19 01:35:01 +08:00
public override void Dispose()
{
archive.Dispose();
archiveStream.Dispose();
}
2018-04-13 17:19:50 +08:00
public override IEnumerable<string> Filenames => archive.Entries.Select(e => e.Key).ExcludeSystemFileNames();
private class MemoryOwnerMemoryStream : Stream
{
private readonly IMemoryOwner<byte> owner;
private readonly Stream stream;
public MemoryOwnerMemoryStream(IMemoryOwner<byte> owner)
{
this.owner = owner;
stream = owner.Memory.AsStream();
}
protected override void Dispose(bool disposing)
{
owner?.Dispose();
base.Dispose(disposing);
}
public override void Flush() => stream.Flush();
public override int Read(byte[] buffer, int offset, int count) => stream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => stream.Seek(offset, origin);
public override void SetLength(long value) => stream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => stream.Write(buffer, offset, count);
public override bool CanRead => stream.CanRead;
public override bool CanSeek => stream.CanSeek;
public override bool CanWrite => stream.CanWrite;
public override long Length => stream.Length;
public override long Position
{
get => stream.Position;
set => stream.Position = value;
}
}
}
}