-
Notifications
You must be signed in to change notification settings - Fork 55
/
utils.go
128 lines (117 loc) · 2.34 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
// Package zutil daily development helper functions
package zutil
import (
"fmt"
"os"
"runtime"
"strings"
"time"
)
type (
// Stack uintptr array
Stack []uintptr
// Nocmp is an uncomparable struct
Nocmp [0]func()
namedArgs struct {
arg interface{}
name string
}
)
// Named creates a named argument
func Named(name string, arg interface{}) interface{} {
return namedArgs{
name: name,
arg: arg,
}
}
const (
maxStackDepth = 1 << 5
)
// WithRunContext function execution time and memory
func WithRunContext(handler func()) (time.Duration, uint64) {
start, mem := time.Now(), runtime.MemStats{}
runtime.ReadMemStats(&mem)
curMem := mem.TotalAlloc
handler()
runtime.ReadMemStats(&mem)
return time.Since(start), mem.TotalAlloc - curMem
}
// IfVal Simulate ternary calculations, pay attention to handling no variables or indexing problems
func IfVal(condition bool, trueVal, falseVal interface{}) interface{} {
if condition {
return trueVal
}
return falseVal
}
// TryCatch exception capture
func TryCatch(fn func() error) (err error) {
defer func() {
if recoverErr := recover(); recoverErr != nil {
if e, ok := recoverErr.(error); ok {
err = e
} else {
err = fmt.Errorf("%v", recoverErr)
}
}
}()
err = fn()
return
}
// Deprecated: please use zerror.TryCatch
// Try exception capture
func Try(fn func(), catch func(e interface{}), finally ...func()) {
if len(finally) > 0 {
defer func() {
finally[0]()
}()
}
defer func() {
if err := recover(); err != nil {
if catch != nil {
catch(err)
} else {
panic(err)
}
}
}()
fn()
}
// Deprecated: please use zerror.Panic
// CheckErr Check Err
func CheckErr(err error, exit ...bool) {
if err != nil {
if len(exit) > 0 && exit[0] {
fmt.Println(err)
os.Exit(1)
return
}
panic(err)
}
}
func Callers(skip ...int) Stack {
var (
pcs [maxStackDepth]uintptr
n = 0
)
if len(skip) > 0 {
n += skip[0]
}
return pcs[:runtime.Callers(n, pcs[:])]
}
func (s Stack) Format(f func(fn *runtime.Func, file string, line int) bool) {
if s == nil {
return
}
for _, p := range s {
if fn := runtime.FuncForPC(p - 1); fn != nil {
file, line := fn.FileLine(p - 1)
name := fn.Name()
if !strings.HasSuffix(file, "_test.go") && strings.Contains(name, "github.com/sohaha") {
continue
}
if !f(fn, file, line) {
break
}
}
}
}