-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes_test.go
77 lines (64 loc) · 1.22 KB
/
bytes_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package json
import (
"testing"
)
func BenchmarkBytes(b *testing.B) {
s := "The quick brown fox jumps over the lazy dog"
bs := []byte(s)
b.Run("safe bytes to string", func(b *testing.B) {
fn := func() string {
return string(bs)
}
for n := 0; n < b.N; n++ {
fn()
}
})
b.Run("safe string to bytes", func(b *testing.B) {
fn := func() []byte {
return []byte(s)
}
for n := 0; n < b.N; n++ {
fn()
}
})
b.Run("unsafe bytes to string", func(b *testing.B) {
for n := 0; n < b.N; n++ {
bytesToString(bs)
}
})
b.Run("unsafe string to bytes", func(b *testing.B) {
for n := 0; n < b.N; n++ {
stringToBytes(s)
}
})
}
func TestBytes(t *testing.T) {
t.Run("string to bytes", func(t *testing.T) {
s := "The quick brown fox jumps over the lazy dog"
bs := stringToBytes(s)
if len(bs) != len(s) {
t.Fail()
}
if string(bs) != s {
t.Fail()
}
bs = stringToBytes("")
if len(bs) > 0 {
t.Fail()
}
})
t.Run("bytes to string", func(t *testing.T) {
bs := []byte("The quick brown fox jumps over the lazy dog")
s := bytesToString(bs)
if len(bs) != len(s) {
t.Fail()
}
if string(bs) != s {
t.Fail()
}
s = bytesToString(nil)
if s != "" {
t.Fail()
}
})
}