private static void Encode(Stream input, Stream output) { using (PaddedStream paddedInput = new PaddedStream(input, 32, PaddedStreamMode.Read)) { using (XorStream xorPaddedInput = new XorStream(paddedInput)) { using (MemoryStream normalOutput = new MemoryStream()) { using (MemoryStream xorOutput = new MemoryStream()) { long initialPosition = input.Position; long inputLength = input.Length - initialPosition; // Compress using normal encoding EncodeInternal(paddedInput, normalOutput, false, inputLength); // Reset the input stream and compress using XOR encoding input.Position = initialPosition; EncodeInternal(xorPaddedInput, xorOutput, true, inputLength); long normalOutputLength = normalOutput.Length; long xorOutputLength = xorOutput.Length; using (PaddedStream paddedOutput = new PaddedStream(output, 2, PaddedStreamMode.Write)) { byte[] outputBytes = (normalOutputLength <= xorOutputLength ? normalOutput : xorOutput).ToArray(); paddedOutput.Write(outputBytes, 0, outputBytes.Length); } } } } } }
private static void Decode(Stream input, Stream output, Endianness endianness) { using (PaddedStream paddedInput = new PaddedStream(input, 2, PaddedStreamMode.Read)) { byte packetLength = NeutralEndian.Read1(paddedInput); var readBitfield = GetBitfieldReader(NeutralEndian.Read1(paddedInput)); ushort incrementingValue; ushort commonValue; InputBitStream <ushort> bitStream; Action <Stream, ushort> write2; if (endianness == Endianness.BigEndian) { incrementingValue = BigEndian.Read2(paddedInput); commonValue = BigEndian.Read2(paddedInput); bitStream = new UInt16BE_E_L_InputBitStream(paddedInput); write2 = Write2BE; } else { incrementingValue = LittleEndian.Read2(paddedInput); commonValue = LittleEndian.Read2(paddedInput); bitStream = new UInt16LE_E_L_InputBitStream(paddedInput); write2 = Write2LE; } // Loop until the end-of-data marker is found (if it is not found before the end of the stream, UInt8InputBitStream // will throw an exception) for (; ;) { if (bitStream.Get()) { int mode = bitStream.Read(2); int count = bitStream.Read(4); switch (mode) { case 0: case 1: { ushort flags = readBitfield(bitStream); ushort outv = (ushort)(bitStream.Read(packetLength) | flags); do { write2(output, outv); outv += (ushort)mode; } while (--count >= 0); } break; case 2: mode = -1; goto case 0; case 3: { // End of compressed data if (count == 0xf) { return; } do { ushort flags = readBitfield(bitStream); ushort outv = bitStream.Read(packetLength); write2(output, (ushort)(outv | flags)); } while (--count >= 0); } break; } } else { bool mode = bitStream.Get(); int count = bitStream.Read(4); if (mode) { do { write2(output, commonValue); } while (--count >= 0); } else { do { write2(output, incrementingValue++); } while (--count >= 0); } } } } }