github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/coder/arith/encoding_test.go (about)

     1  package arith
     2  
     3  import (
     4  	"math/rand"
     5  	"testing"
     6  )
     7  
     8  type pair struct {
     9  	bit  uint
    10  	prob P
    11  }
    12  
    13  func TestRandomEncodeDecode(t *testing.T) {
    14  	bits := make([]pair, 2141)
    15  	for i := range bits {
    16  		bits[i].bit = uint(rand.Intn(2))
    17  		bits[i].prob = P(rand.Intn(MaxP))
    18  	}
    19  
    20  	enc := NewEncoder()
    21  	for _, v := range bits {
    22  		enc.Encode(v.bit, v.prob)
    23  	}
    24  	enc.Close()
    25  	data := enc.Bytes()
    26  
    27  	dec := NewDecoder(data)
    28  	for i, v := range bits {
    29  		x := dec.Decode(v.prob)
    30  		if x != v.bit {
    31  			t.Fatalf("fail %v: %v got %v exp %v", bits, i, x, v.bit)
    32  		}
    33  	}
    34  }
    35  
    36  func TestPacking(t *testing.T) {
    37  	const N = 1 << 16
    38  	enc := NewEncoder()
    39  	p := Prob(0.1)
    40  	for i := 0; i < N; i++ {
    41  		if rand.Intn(100) < 10 {
    42  			enc.Encode(1, p)
    43  		} else {
    44  			enc.Encode(0, p)
    45  		}
    46  	}
    47  	enc.Close()
    48  
    49  	if len(enc.Bytes()) > N/8 {
    50  		t.Fatalf("No packing: %v vs %v", len(enc.Bytes()), N/8)
    51  	}
    52  	enc.Bytes()
    53  }