github.com/zxysilent/utils@v0.3.1/rand.go (about) 1 package utils 2 3 import ( 4 "unsafe" 5 ) 6 7 // go clean -testcache // Delete all cached test results 8 9 const ( 10 randStr = "23456789abcdefghijkmnpqrstuvwxyz" //32 11 randMask = 1<<5 - 1 //11111 12 _suid = 8 //LEQ 12 13 14 uuidStr = "0123456789abcdef" //16 15 uuidMask = 1<<4 - 1 //1111 16 17 digitStr = "0123456789" 18 digitMask = 1<<4 - 1 19 variant = "89ab" 20 ) 21 22 // SUID SUID生成 23 func SUID() string { 24 buf := make([]byte, _suid) 25 for idx, cache := 0, fastRand(); idx < _suid; { 26 buf[idx] = randStr[cache&randMask] 27 cache >>= 5 28 idx++ 29 } 30 // return unsafe.String(&buf[0], len(buf)) 31 return *(*string)(unsafe.Pointer(&buf)) 32 } 33 34 // RUID 返回指定长度的随机字符串 35 // 包含数字 小写字母 36 func RUID(ln int) string { 37 buf := make([]byte, ln) 38 for idx, cache, remain := 0, fastRand(), 12; idx < ln; { 39 if remain == 0 { 40 cache, remain = fastRand(), 12 41 } 42 buf[idx] = randStr[cache&randMask] 43 cache >>= 5 44 remain-- 45 idx++ 46 } 47 return *(*string)(unsafe.Pointer(&buf)) 48 } 49 50 // DUID 返回指定长度的随机字符串 51 // 只包含数字 52 func DUID(ln int) string { 53 buf := make([]byte, ln) 54 for idx, cache, remain := 0, fastRand(), 16; idx < ln; { 55 if remain == 0 { 56 cache, remain = fastRand(), 16 57 } 58 buf[idx] = digitStr[int(cache&digitMask)%10] 59 cache >>= 4 60 remain-- 61 idx++ 62 } 63 return *(*string)(unsafe.Pointer(&buf)) 64 } 65 66 // UUID 67 // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. 68 func UUID() string { 69 buf := make([]byte, 36) 70 for idx, cache, remain := 0, fastRand(), 16; idx < 32; { 71 if remain == 0 { 72 cache, remain = fastRand(), 16 73 } 74 buf[idx] = uuidStr[cache&uuidMask] 75 cache >>= 4 76 remain-- 77 idx++ 78 } 79 buf[32] = buf[8] 80 buf[33] = buf[13] 81 buf[34] = buf[18] 82 buf[35] = buf[23] 83 buf[8] = '-' 84 buf[13] = '-' 85 buf[14] = '4' 86 buf[18] = '-' 87 buf[19] = variant[buf[19]%4] 88 buf[23] = '-' 89 return *(*string)(unsafe.Pointer(&buf)) 90 // return unsafe.String(&buf[0], len(buf)) 91 } 92 93 //go:linkname fastRand runtime.fastrand64 94 func fastRand() uint64 95 96 //go:noescape 97 //go:linkname now time.now 98 func now() (sec int64, nsec int32, mono int64) 99 100 // for runtime.walltime 101 func Now() int64 { 102 sec, nsec, _ := now() 103 return sec*1e3 + int64(nsec)/1e6 104 // return time.Now().Unix() 105 }