LZMA.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.IO;
  3. using SevenZip;
  4. using SevenZip.Compression.LZMA;
  5. namespace Util
  6. {
  7. internal static class LZMA
  8. {
  9. private static readonly CoderPropID[] PropIDs =
  10. {
  11. CoderPropID.DictionarySize,
  12. CoderPropID.PosStateBits,
  13. CoderPropID.LitContextBits,
  14. CoderPropID.LitPosBits,
  15. CoderPropID.Algorithm,
  16. CoderPropID.NumFastBytes,
  17. CoderPropID.MatchFinder,
  18. CoderPropID.EndMarker
  19. };
  20. private static readonly object[] Properties =
  21. {
  22. 1 << 23,
  23. 2,
  24. 3,
  25. 0,
  26. 2,
  27. 128,
  28. "bt4",
  29. false
  30. };
  31. public static byte[] Compress(MemoryStream inStream)
  32. {
  33. MemoryStream outStream = new MemoryStream();
  34. Encoder encoder = new Encoder();
  35. encoder.SetCoderProperties(PropIDs, Properties);
  36. encoder.WriteCoderProperties(outStream);
  37. Int64 fileSize = inStream.Length;
  38. for (int i = 0; i < 8; i++)
  39. {
  40. outStream.WriteByte((Byte)(fileSize >> (8 * i)));
  41. }
  42. encoder.Code(inStream, outStream, -1, -1, null);
  43. return outStream.ToArray();
  44. }
  45. public static MemoryStream Decompress(Stream inStream)
  46. {
  47. MemoryStream outStream = new MemoryStream();
  48. byte[] properties = new byte[5];
  49. if (inStream.Read(properties, 0, 5) != 5)
  50. {
  51. throw new Exception("input .lzma is too short");
  52. }
  53. Decoder decoder = new Decoder();
  54. decoder.SetDecoderProperties(properties);
  55. long outSize = 0;
  56. for (int i = 0; i < 8; i++)
  57. {
  58. int v = inStream.ReadByte();
  59. if (v < 0)
  60. {
  61. throw new Exception("Can't Read 1");
  62. }
  63. outSize |= ((long)(byte)v) << (8 * i);
  64. }
  65. long compressedSize = inStream.Length - inStream.Position;
  66. decoder.Code(inStream, outStream, compressedSize, outSize, null);
  67. return outStream;
  68. }
  69. }
  70. }