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

     1  package expgolomb
     2  
     3  import (
     4  	"bytes"
     5  	"math/rand"
     6  	"testing"
     7  
     8  	"github.com/egonelbre/exp/bit"
     9  )
    10  
    11  func TestIntRandomSmall(t *testing.T) { testInt(t, 5) }
    12  func TestIntRandomLarge(t *testing.T) { testInt(t, 1251) }
    13  
    14  func testInt(t *testing.T, n int) {
    15  	values := make([]int, n)
    16  	for i := range values {
    17  		if i%2 == 0 {
    18  			values[i] = rand.Int()
    19  		} else {
    20  			values[i] = -rand.Int()
    21  		}
    22  	}
    23  
    24  	var buf bytes.Buffer
    25  	w := bit.NewWriter(&buf)
    26  	for _, v := range values {
    27  		WriteInt(w, v)
    28  	}
    29  
    30  	err := w.Close()
    31  	if err != nil {
    32  		t.Errorf("w.Close: %v", err)
    33  		return
    34  	}
    35  
    36  	r := bit.NewReader(&buf)
    37  	for i, exp := range values {
    38  		got, err := ReadInt(r), r.Error()
    39  		if err != nil {
    40  			t.Errorf("ReadInt: %v", err)
    41  			return
    42  		}
    43  		if got != exp {
    44  			t.Errorf("%v: %d got %v expected %v", values, i, got, exp)
    45  			return
    46  		}
    47  	}
    48  }
    49  
    50  func TestUintRandomSmall(t *testing.T) { testUint(t, 5) }
    51  func TestUintRandomLarge(t *testing.T) { testUint(t, 1251) }
    52  
    53  func testUint(t *testing.T, n int) {
    54  	values := make([]uint, n)
    55  	for i := range values {
    56  		values[i] = uint(rand.Int())
    57  	}
    58  
    59  	var buf bytes.Buffer
    60  	w := bit.NewWriter(&buf)
    61  	for _, v := range values {
    62  		WriteUint(w, v)
    63  	}
    64  
    65  	err := w.Close()
    66  	if err != nil {
    67  		t.Errorf("w.Close: %v", err)
    68  		return
    69  	}
    70  
    71  	r := bit.NewReader(&buf)
    72  	for i, exp := range values {
    73  		got, err := ReadUint(r), r.Error()
    74  		if err != nil {
    75  			t.Errorf("ReadUint: %v", err)
    76  			return
    77  		}
    78  		if got != exp {
    79  			t.Errorf("%v: %d got %v expected %v", values, i, got, exp)
    80  			return
    81  		}
    82  	}
    83  }