1
0
mirror of synced 2024-12-04 20:08:00 +01:00
Switch-Toolbox/Switch_Toolbox_Library/Compression/Formats/LZMA.cs

98 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using Toolbox.Library.IO;
2019-09-22 20:46:57 +02:00
using Toolbox.Library.Forms;
namespace Toolbox.Library
{
public class LZMA : ICompressionFormat
{
public string[] Description { get; set; } = new string[] { "LZMA Compressed" };
public string[] Extension { get; set; } = new string[] { "*.lzma", };
public override string ToString() { return "LZMA"; }
public bool Identify(Stream stream, string fileName)
{
using (var reader = new FileReader(stream, true))
{
return reader.CheckSignature(4,"LZMA", 1);
}
}
public bool CanCompress { get; } = true;
2019-09-22 20:35:38 +02:00
private bool UseLZMAMagicHeader = true;
public Stream Decompress(Stream stream)
{
using (var reader = new FileReader(stream))
{
2019-09-22 20:35:38 +02:00
reader.SetByteOrder(false);
var output = new System.IO.MemoryStream();
if (reader.CheckSignature(4, "LZMA", 1))
{
2019-09-22 20:35:38 +02:00
byte unk = reader.ReadByte(); //0xFF
uint magic = reader.ReadUInt32();
2019-09-22 20:35:38 +02:00
reader.ReadByte(); //padding
UseLZMAMagicHeader = true;
}
2019-09-22 20:35:38 +02:00
byte[] properties = reader.ReadBytes(5); //Property and dictionary size
ulong decompressedSize = reader.ReadUInt64();
2019-09-22 20:35:38 +02:00
var compressedSize = stream.Length - reader.Position;
var copressedBytes = reader.ReadBytes((int)compressedSize);
SevenZip.Compression.LZMA.Decoder decode = new SevenZip.Compression.LZMA.Decoder();
decode.SetDecoderProperties(properties);
MemoryStream ms = new MemoryStream(copressedBytes);
2019-09-22 20:35:38 +02:00
decode.Code(ms, output, compressedSize, (int)decompressedSize, null);
return output;
}
}
public Stream Compress(Stream stream)
{
MemoryStream mem = new MemoryStream();
2019-09-22 20:46:57 +02:00
LzmaSettingsForm settingsDlg = new LzmaSettingsForm();
if (settingsDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
2019-09-22 20:46:57 +02:00
if (settingsDlg.WriteMagicHeader) {
using (var writer = new FileWriter(mem, true))
{
writer.SetByteOrder(false);
if (UseLZMAMagicHeader)
{
writer.Write((byte)0xFF);
writer.WriteSignature("LZMA");
writer.Write((byte)0);
}
}
2019-09-22 20:35:38 +02:00
}
2019-09-22 20:46:57 +02:00
SevenZip.Compression.LZMA.Encoder encode = new SevenZip.Compression.LZMA.Encoder();
if (settingsDlg.WriteProperties)
encode.WriteCoderProperties(mem);
if (settingsDlg.WriteDecomSize)
mem.Write(BitConverter.GetBytes(stream.Length), (int)stream.Position, 8);
encode.Code(stream, mem, -1, -1, null);
}
else
return null;
2019-09-22 20:35:38 +02:00
return mem;
}
}
}