tlog.app/go/tlog@v0.23.1/id_test.go (about) 1 package tlog 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 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 TestIDFromString(tb *testing.T) { 31 id, err := IDFromString("e6a5d996-99b1-493e-ad74-47382220d1a9") 32 assert.NoError(tb, err) 33 assert.Equal(tb, ID{0xe6, 0xa5, 0xd9, 0x96, 0x99, 0xb1, 0x49, 0x3e, 0xad, 0x74, 0x47, 0x38, 0x22, 0x20, 0xd1, 0xa9}, id) 34 35 _, err = IDFromString("e6a5d996-99b1-493e-ad74-47382220d1a") 36 assert.ErrorIs(tb, err, ShortIDError{Bytes: 15}) 37 } 38 39 func TestIDJSON(t *testing.T) { 40 id := testRandID(1)() 41 42 data, err := json.Marshal(id) 43 assert.NoError(t, err) 44 45 t.Logf("json encoded id: %s (% x)", data, []byte(id[:])) 46 47 var back ID 48 err = json.Unmarshal(data, &back) 49 assert.NoError(t, err) 50 51 assert.Equal(t, id, back) 52 } 53 54 func BenchmarkIDStringUUID(b *testing.B) { 55 b.ReportAllocs() 56 57 id := ID{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf} 58 59 for i := 0; i < b.N; i++ { 60 _ = id.StringUUID() 61 } 62 } 63 64 func BenchmarkIDFormat(b *testing.B) { 65 b.ReportAllocs() 66 67 id := ID{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf} 68 69 for i := 0; i < b.N; i++ { 70 fmt.Fprintf(io.Discard, "%+x", id) 71 } 72 } 73 74 func BenchmarkIDFormatTo(b *testing.B) { 75 b.ReportAllocs() 76 77 var buf [40]byte 78 id := ID{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf} 79 80 for i := 0; i < b.N; i++ { 81 if i&0xf == 0 { 82 ID{}.FormatTo(buf[:], 0, 'v') 83 } else { 84 id.FormatTo(buf[:], 0, 'v') 85 } 86 } 87 }