Example #1
0
func TestRandomCodings(t *testing.T) {
	rng = rand.New(rand.NewSource(randSeed))

	for iteration := 0; iteration < iterations; iteration++ {
		codeTable := randomCodeTable()
		coding, err := huffman.NewCoding(codeTable)
		if err != nil {
			t.Errorf("valid coding #%d got: %v", iteration, err)
			continue
		}
		_ = coding
	}
}
Example #2
0
func TestLoopback(t *testing.T) {
	rng = rand.New(rand.NewSource(randSeed))

	for iteration := 0; iteration < iterations; iteration++ {
		codeTable := randomCodeTable()
		coding, err := huffman.NewCoding(codeTable)
		if err != nil {
			t.Errorf("valid coding #%d got: %v", iteration, err)
			continue
		}

		enc := huffman.NewEncoder(coding)
		dec := huffman.NewDecoder(coding)

		dataLen := rng.Intn(10)
		dataIn := make([]byte, dataLen)
		for i, _ := range dataIn {
			dataIn[i] = uint8(rng.Int())
		}
		t.Logf("input: " + showBinaryOctets(dataIn))

		var huffed []byte
		transcodeLoop(t, &huffed, dataIn, enc.Encode, enc.Flush)
		t.Logf("huffed: " + showBinaryOctets(huffed))

		var dataOut []byte
		transcodeLoop(t, &dataOut, huffed, dec.Decode, dec.Flush)
		t.Logf("looped: " + showBinaryOctets(dataOut))

		// Since this is an unterminated Huffman coding, we may decode some garbage symbols at the
		// end.  TODO: check to make sure any garbage symbols come from zero-valued decode.
		lenOk := len(dataOut) >= len(dataIn)
		if !(lenOk && bytes.Equal(dataOut[:len(dataIn)], dataIn)) {
			t.Fatalf("coding #%d failed to loop around %d -> %d -> %d bytes of data",
				iteration, dataLen, len(huffed), len(dataOut))
			continue
		}
	}
}