github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/dbs/memristed/memex/rand.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 memex 15 16 import "time" 17 18 const maxRandValue = 0x3FFFFFFF 19 20 // MysqlRng is random number generator and this implementation is ported from MyALLEGROSQL. 21 // See https://github.com/einsteindb/einsteindb/pull/6117#issuecomment-562489078. 22 type MysqlRng struct { 23 seed1 uint32 24 seed2 uint32 25 } 26 27 // NewWithSeed create a rng with random seed. 28 func NewWithSeed(seed int64) *MysqlRng { 29 seed1 := uint32(seed*0x10001+55555555) % maxRandValue 30 seed2 := uint32(seed*0x10000001) % maxRandValue 31 return &MysqlRng{seed1: seed1, seed2: seed2} 32 } 33 34 // NewWithTime create a rng with time stamp. 35 func NewWithTime() *MysqlRng { 36 return NewWithSeed(time.Now().UnixNano()) 37 } 38 39 // Gen will generate random number. 40 func (rng *MysqlRng) Gen() float64 { 41 rng.seed1 = (rng.seed1*3 + rng.seed2) % maxRandValue 42 rng.seed2 = (rng.seed1 + rng.seed2 + 33) % maxRandValue 43 return float64(rng.seed1) / float64(maxRandValue) 44 }