private static void roundTrip(HuffmanEncoder encoder, HuffmanDecoder decoder, byte[] buf) { using(var baos = new MemoryStream()) { using(var dos = new BinaryWriter(baos)) { encoder.Encode(dos, buf); var actualBytes = decoder.Decode(baos.ToArray()); Assert.IsTrue(buf.SequenceEqual(actualBytes)); } } }
private static string DecodeWithHuffman(string dictFilename, byte[] bytes) { var serializedDict = File.ReadAllText(dictFilename); var rates = serializedDict.Split('操').Select(x => { var chr = x[0]; var rate = int.Parse(x.Substring(1, x.Length - 1)); return(new { chr, rate }); }).ToDictionary(x => x.chr, x => x.rate); var huffmanTree = new HuffmanDecoder(); huffmanTree.BuildWithRates(rates); return(huffmanTree.Decode(new BitArray(bytes))); }
public void Decode_ThreeSymbols_TwoAreRight() { //given var tree = MockHuffmanTreeBuilder.Build('c', '#', 'x', 'a'); var decoder = new HuffmanDecoder <char>(tree); var input = new MockDecoderInput(new List <int> { 0, 1, 1, 1, 0 }); var output = new MockDecoderOutput(new List <char> { 'c', 'a', 'x' }); //when decoder.Decode(input, output); //then output.AssertCorrectOutput(); }
public void Decode_FourSymbols_DeepTree() { //given var tree = MockHuffmanTreeBuilder.Build('a', '#', 'b', '#', 'c', 'd'); var decoder = new HuffmanDecoder <char>(tree); var input = new MockDecoderInput(new List <int> { 0, 1, 0, 1, 1, 0, 1, 1, 1 }); var output = new MockDecoderOutput(new List <char> { 'a', 'b', 'c', 'd' }); //when decoder.Decode(input, output); //then output.AssertCorrectOutput(); }
public override object Decode(Stream stream) { byte num = stream.CreateSuitableBinaryReader().ReadByte(); byte[] numArray; try { numArray = HuffmanDecoder.Decode(stream); } catch (Exception ex) { throw new CodecException("Unable to decode", ex); } byte[] buffer = numArray != null ? new byte[numArray.Length + 1] : throw new CodecException("Unable to decode"); buffer[0] = num; Buffer.BlockCopy(numArray, 0, buffer, 1, numArray.Length); using (MemoryStream memoryStream = new MemoryStream(buffer)) return(base.Decode(memoryStream)); }