github.com/turingchain2020/turingchain@v1.1.21/common/common.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package common contains various helper functions. 6 package common 7 8 import ( 9 "errors" 10 "math/rand" 11 "sync" 12 "time" 13 ) 14 15 var random *rand.Rand 16 var globalPointerMap = make(map[int64]interface{}) 17 var globalPointerID int64 18 var gloabalMu sync.Mutex 19 20 //ErrPointerNotFound 指针没有找到 21 var ErrPointerNotFound = errors.New("ErrPointerNotFound") 22 23 func init() { 24 random = rand.New(rand.NewSource(time.Now().UnixNano())) 25 go func() { 26 for { 27 time.Sleep(60 * time.Second) 28 gloabalMu.Lock() 29 pointerLen := len(globalPointerMap) 30 gloabalMu.Unlock() 31 if pointerLen > 10 { 32 println("<==>global pointer count = ", len(globalPointerMap)) 33 } 34 } 35 }() 36 } 37 38 //StorePointer 保存指针返回int64 39 func StorePointer(p interface{}) int64 { 40 gloabalMu.Lock() 41 defer gloabalMu.Unlock() 42 globalPointerID++ 43 for globalPointerMap[globalPointerID] != nil { 44 globalPointerID++ 45 } 46 globalPointerMap[globalPointerID] = p 47 return globalPointerID 48 } 49 50 //RemovePointer 删除指针 51 func RemovePointer(id int64) { 52 gloabalMu.Lock() 53 defer gloabalMu.Unlock() 54 delete(globalPointerMap, id) 55 } 56 57 //GetPointer 删除指针 58 func GetPointer(id int64) (interface{}, error) { 59 gloabalMu.Lock() 60 defer gloabalMu.Unlock() 61 p, ok := globalPointerMap[id] 62 if !ok { 63 return nil, ErrPointerNotFound 64 } 65 return p, nil 66 } 67 68 //MinInt32 min 69 func MinInt32(left, right int32) int32 { 70 if left > right { 71 return right 72 } 73 return left 74 } 75 76 //MaxInt32 max 77 func MaxInt32(left, right int32) int32 { 78 if left > right { 79 return left 80 } 81 return right 82 } 83 84 //GetRandBytes 获取随机字节 85 func GetRandBytes(min, max int) []byte { 86 length := max 87 if min < max { 88 length = min + random.Intn(max-min) 89 } 90 result := make([]byte, length) 91 for i := 0; i < length; i++ { 92 result[i] = byte(random.Intn(256)) 93 } 94 return result 95 } 96 97 //GetRandString 获取随机字符串 98 func GetRandString(length int) string { 99 return string(GetRandBytes(length, length)) 100 } 101 102 var printString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 103 104 //GetRandPrintString 获取随机可打印字符串 105 func GetRandPrintString(min, max int) string { 106 l := max 107 if min < max { 108 l = min + random.Intn(max-min) 109 } 110 result := make([]byte, l) 111 for i := 0; i < l; i++ { 112 result[i] = printString[random.Intn(len(printString))] 113 } 114 return string(result) 115 }