-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
149 lines (134 loc) · 2.47 KB
/
utils.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package slog
import (
"bytes"
"runtime"
"sync"
"time"
)
const recordBufSize = 128
var (
recordPool = sync.Pool{
New: func() interface{} {
return &Record{}
},
}
bufPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, recordBufSize))
},
}
uintBytes2 [60][]byte // 0 - 59
uintBytes4 [69][]byte // 1970 - 2038
uintBytes [999][]byte // 2 - 1000
now = time.Now
)
func uint2Bytes(x, size int) []byte {
// x and size shoule be uint32
result := make([]byte, size)
for i := 0; i < size; i++ {
r := x % 10
result[size-i-1] = byte(r) + '0'
x /= 10
}
return result
}
func uint2DynamicBytes(x int) []byte {
// x shoule be uint32
size := 0
switch {
case x < 10:
return []byte{byte(x) + '0'}
case x < 100:
size = 2
case x < 1000:
size = 3
case x < 10000:
size = 4
case x < 10000:
size = 5
case x < 10000:
size = 6
case x < 100000:
size = 7
case x < 1000000:
size = 8
case x < 10000000:
size = 9
default:
size = 10
}
result := make([]byte, size)
for i := 0; i < size; i++ {
r := x % 10
result[size-i-1] = byte(r) + '0'
x /= 10
}
return result
}
func init() {
for i := 0; i < 60; i++ { // hour / minute / second is between 0 and 59
uintBytes2[i] = uint2Bytes(i, 2)
}
for i := 0; i < 69; i++ { // year is between 1970 and 2038
uintBytes4[i] = uint2Bytes(1970+i, 4)
}
for i := 0; i < 999; i++ { // source code line number is usually between 2 and 1000
uintBytes[i] = uint2DynamicBytes(i + 2)
}
}
func uint2Bytes2(x int) []byte {
// x shoule between 0 and 59
return uintBytes2[x]
}
func uint2Bytes4(x int) []byte {
// x shoule between 1970 and 2038
return uintBytes4[x-1970]
}
func fastUint2DynamicBytes(x int) []byte {
// x shoule be uint32
size := 0
switch {
case x < 2:
return []byte{byte(x) + '0'}
case x <= 1000:
return uintBytes[x-2]
case x < 10000:
size = 4
case x < 10000:
size = 5
case x < 10000:
size = 6
case x < 100000:
size = 7
case x < 1000000:
size = 8
case x < 10000000:
size = 9
default:
size = 10
}
result := make([]byte, size)
for i := 0; i < size; i++ {
r := x % 10
result[size-i-1] = byte(r) + '0'
x /= 10
}
return result
}
func stopTimer(timer *time.Timer) {
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
}
func logError(err error) {
if internalLogger != nil {
_, file, line, _ := runtime.Caller(1)
internalLogger.Log(ErrorLevel, file, line, err.Error())
}
}
func setNowFunc(nowFunc func() time.Time) {
now = nowFunc
}