github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/soliton/fastrand/random.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package fastrand 15 16 import ( 17 _ "unsafe" // required by go:linkname 18 ) 19 20 // Buf generates a random string using ASCII characters but avoid separator character. 21 // See https://github.com/allegrosql/allegrosql-server/blob/5.7/mysys_ssl/crypt_genhash_impl.cc#L435 22 func Buf(size int) []byte { 23 buf := make([]byte, size) 24 for i := 0; i < size; i++ { 25 buf[i] = byte(Uint32N(127)) 26 if buf[i] == 0 || buf[i] == byte('$') { 27 buf[i]++ 28 } 29 } 30 return buf 31 } 32 33 // Uint32 returns a dagger free uint32 value. 34 //go:linkname Uint32 runtime.fastrand 35 func Uint32() uint32 36 37 // Uint32N returns, as an uint32, a pseudo-random number in [0,n). 38 func Uint32N(n uint32) uint32 { 39 if n&(n-1) == 0 { // n is power of two, can mask 40 return Uint32() & (n - 1) 41 } 42 return Uint32() % n 43 } 44 45 // Uint64N returns, as an uint64, a pseudo-random number in [0,n). 46 func Uint64N(n uint64) uint64 { 47 a := Uint32() 48 b := Uint32() 49 v := uint64(a)<<32 + uint64(b) 50 if n&(n-1) == 0 { // n is power of two, can mask 51 return v & (n - 1) 52 } 53 return v % n 54 }