github.com/xaionaro-go/rand@v0.0.0-20191005105903-aba1befc54a5/mathrand/reduce64.go (about)

     1  package mathrand
     2  
     3  // ReduceUint64 returns `src` as a value smaller than `mod`.
     4  func ReduceUint64(src, mod uint64) uint64 {
     5  	mask := mod
     6  	mask |= mask >> 1
     7  	mask |= mask >> 2
     8  	mask |= mask >> 4
     9  	mask |= mask >> 8
    10  	mask |= mask >> 16
    11  	mask |= mask >> 32
    12  	src &= mask
    13  	if src < mod {
    14  		return src
    15  	}
    16  	return src & (mask >> 1)
    17  }