-
Notifications
You must be signed in to change notification settings - Fork 9
/
utils.go
123 lines (112 loc) · 2.32 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
package ecs
import (
"errors"
"math/rand"
"reflect"
"runtime/debug"
"sync/atomic"
"time"
"unsafe"
)
var Empty struct{} = struct{}{}
var seq uint32
var timestamp int64
var DebugTry = true
func init() {
rand.Seed(time.Now().UnixNano())
}
func LocalUniqueID() int64 {
tNow := int64(time.Now().UnixNano()) << 32
tTemp := atomic.LoadInt64(×tamp)
if tTemp != tNow {
atomic.StoreUint32(&seq, 0)
for {
if atomic.CompareAndSwapInt64(×tamp, tTemp, tNow) {
break
} else {
tTemp = atomic.LoadInt64(×tamp)
tNow = int64(time.Now().UnixNano()) << 32
}
}
}
s := atomic.AddUint32(&seq, 1)
return tNow + int64((s<<16)&0xFFFF0000+rand.Uint32()&0x0000FFFF)
}
func Try(task func(), catch ...func(error)) {
defer (func() {
if DebugTry {
return
}
if r := recover(); r != nil {
var str string
switch r.(type) {
case error:
str = r.(error).Error()
case string:
str = r.(string)
}
err := errors.New(str + "\n" + string(debug.Stack()))
if len(catch) > 0 {
catch[0](err)
}
}
})()
task()
}
func TryAndReport(task func() error) (err error) {
defer func() {
if DebugTry {
return
}
if r := recover(); r != nil {
switch typ := r.(type) {
case error:
err = r.(error)
case string:
err = errors.New(r.(string))
default:
_ = typ
}
}
}()
err = task()
return nil
}
func IsPureValueType(typ reflect.Type) bool {
switch typ.Kind() {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
return true
case reflect.Array:
return IsPureValueType(typ.Elem())
case reflect.Struct:
for i := 0; i < typ.NumField(); i++ {
subType := typ.Field(i).Type
if !IsPureValueType(subType) {
return false
}
}
return true
default:
return false
}
}
func StrHash(str string, groupCount int) int {
total := 0
for i := 0; i < len(str); i++ {
total += int(str[i])
}
return total % groupCount
}
func memcmp(a unsafe.Pointer, b unsafe.Pointer, len uintptr) (ret bool) {
for i := uintptr(0); i < len; i++ {
if *(*byte)(unsafe.Add(a, i)) != *(*byte)(unsafe.Add(b, i)) {
ret = false
return
}
}
ret = true
Log.Infof("memory compare: %v, %v, %v, equal:%v", a, b, len, ret)
return
}