github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bit/bit_test.go (about)

     1  package bit
     2  
     3  import (
     4  	"bytes"
     5  	"math/rand"
     6  	"testing"
     7  )
     8  
     9  func TestWriteReadRandomBit(t *testing.T) {
    10  	var buf bytes.Buffer
    11  	w := NewWriter(&buf)
    12  
    13  	values := make([]int, 1251)
    14  	for i := range values {
    15  		values[i] = rand.Intn(1)
    16  		w.WriteBit(values[i])
    17  	}
    18  	w.Close()
    19  
    20  	r := NewReader(&buf)
    21  	for i, exp := range values {
    22  		got, err := r.ReadBit(), r.Error()
    23  		if err != nil {
    24  			t.Errorf("r.ReadBits: %v", err)
    25  			return
    26  		}
    27  		if got != exp {
    28  			t.Errorf("%v: %d got %v expected %v", values, i, got, exp)
    29  			return
    30  		}
    31  	}
    32  }
    33  
    34  func TestWriteReadBits(t *testing.T) {
    35  	testReadWrite(t, []pair{
    36  		{0xAC, 8},
    37  		{1, 3},
    38  		{2, 3},
    39  		{3, 3},
    40  		{4, 3},
    41  		{5, 3},
    42  		{0xEF, 8},
    43  		{0x7F, 7},
    44  		{0xCAFEBABE, 32},
    45  	})
    46  }
    47  
    48  func TestWriteReadRandomBitsSmall(t *testing.T) { testRandomBits(t, 5) }
    49  func TestWriteReadRandomBitsLarge(t *testing.T) { testRandomBits(t, 1251) }
    50  
    51  func testRandomBits(t *testing.T, N int) {
    52  	values := make([]pair, N)
    53  	for i := range values {
    54  		width := uint(rand.Intn(61) + 1)
    55  		value := uint64(rand.Intn(1<<width - 1))
    56  		values[i] = pair{value, width}
    57  	}
    58  	testReadWrite(t, values)
    59  }
    60  
    61  type pair struct {
    62  	value uint64
    63  	width uint
    64  }
    65  
    66  func testReadWrite(t *testing.T, values []pair) {
    67  	var buf bytes.Buffer
    68  	w := NewWriter(&buf)
    69  	for _, p := range values {
    70  		w.WriteBits(p.value, p.width)
    71  	}
    72  
    73  	err := w.Close()
    74  	if err != nil {
    75  		t.Errorf("w.Close: %v", err)
    76  		return
    77  	}
    78  
    79  	r := NewReader(&buf)
    80  	for i, exp := range values {
    81  		got, err := r.ReadBits(exp.width), r.Error()
    82  		if err != nil {
    83  			t.Errorf("r.ReadBit: %v", err)
    84  			return
    85  		}
    86  		if got != exp.value {
    87  			t.Errorf("%v: %d got %v expected %v", values, i, got, exp.value)
    88  			return
    89  		}
    90  	}
    91  }