github.com/iDigitalFlame/xmt@v0.5.4/util/rand_fast.go (about) 1 //go:build !stdrand 2 // +build !stdrand 3 4 // Copyright (C) 2020 - 2023 iDigitalFlame 5 // 6 // This program is free software: you can redistribute it and/or modify 7 // it under the terms of the GNU General Public License as published by 8 // the Free Software Foundation, either version 3 of the License, or 9 // any later version. 10 // 11 // This program is distributed in the hope that it will be useful, 12 // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 // GNU General Public License for more details. 15 // 16 // You should have received a copy of the GNU General Public License 17 // along with this program. If not, see <https://www.gnu.org/licenses/>. 18 // 19 20 package util 21 22 type random struct{} 23 24 func (r random) Int() int { 25 return int(abs64(r.Uint64())) 26 } 27 func abs32(v uint32) uint32 { 28 return v &^ (1 << 31) 29 } 30 func abs64(v uint64) uint64 { 31 return v &^ (1 << 63) 32 } 33 func (random) Int31() int32 { 34 return int32(abs32(FastRand())) 35 } 36 func (r random) Int63() int64 { 37 return int64(abs64(r.Uint64())) 38 } 39 func (random) Uint32() uint32 { 40 return FastRand() 41 } 42 func (random) Uint64() uint64 { 43 return uint64(FastRand())<<32 | uint64(FastRand()) 44 } 45 func (r random) Intn(n int) int { 46 return int(abs64(r.Uint64())) % n 47 } 48 func (random) Int31n(n int32) int32 { 49 return int32(abs32(FastRand())) & n 50 } 51 func (r random) Int63n(n int64) int64 { 52 return int64(abs64(r.Uint64())) % n 53 } 54 func (random) Read(p []byte) (int, error) { 55 for i := range p { 56 p[i] = byte(FastRandN(256)) 57 } 58 return len(p), nil 59 }