github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/id_test.go (about)

     1  package tlog
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"math/rand"
     8  	"sync"
     9  	"testing"
    10  
    11  	"github.com/nikandfor/assert"
    12  )
    13  
    14  func testRandID(seed int64) func() ID {
    15  	var mu sync.Mutex
    16  	rnd := rand.New(rand.NewSource(seed)) //nolint:gosec
    17  
    18  	return func() (id ID) {
    19  		defer mu.Unlock()
    20  		mu.Lock()
    21  
    22  		for id == (ID{}) {
    23  			_, _ = rnd.Read(id[:])
    24  		}
    25  
    26  		return
    27  	}
    28  }
    29  
    30  func TestIDJSON(t *testing.T) {
    31  	id := testRandID(1)()
    32  
    33  	data, err := json.Marshal(id)
    34  	assert.NoError(t, err)
    35  
    36  	t.Logf("json encoded id: %s", data)
    37  
    38  	var back ID
    39  	err = json.Unmarshal(data, &back)
    40  	assert.NoError(t, err)
    41  
    42  	assert.Equal(t, id, back)
    43  }
    44  
    45  func BenchmarkIDFormat(b *testing.B) {
    46  	b.ReportAllocs()
    47  
    48  	id := ID{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}
    49  
    50  	for i := 0; i < b.N; i++ {
    51  		fmt.Fprintf(ioutil.Discard, "%+x", id)
    52  	}
    53  }
    54  
    55  func BenchmarkIDFormatTo(b *testing.B) {
    56  	b.ReportAllocs()
    57  
    58  	var buf [40]byte
    59  	id := ID{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}
    60  
    61  	for i := 0; i < b.N; i++ {
    62  		if i&0xf == 0 {
    63  			ID{}.FormatTo(buf[:], 'v')
    64  		} else {
    65  			id.FormatTo(buf[:], 'v')
    66  		}
    67  	}
    68  }