github.com/petermattis/pebble@v0.0.0-20190905164901-ab51a2166067/internal/randvar/uniform.go (about)

     1  // Copyright 2018 The Cockroach Authors.
     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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    12  // implied. See the License for the specific language governing
    13  // permissions and limitations under the License. See the AUTHORS file
    14  // for names of contributors.
    15  
    16  package randvar
    17  
    18  import (
    19  	"sync"
    20  
    21  	"golang.org/x/exp/rand"
    22  )
    23  
    24  // Uniform is a random number generator that generates draws from a uniform
    25  // distribution.
    26  type Uniform struct {
    27  	min uint64
    28  	mu  struct {
    29  		sync.Mutex
    30  		rng *rand.Rand
    31  		max uint64
    32  	}
    33  }
    34  
    35  // NewUniform constructs a new Uniform generator with the given
    36  // parameters. Returns an error if the parameters are outside the accepted
    37  // range.
    38  func NewUniform(rng *rand.Rand, min, max uint64) *Uniform {
    39  	g := &Uniform{min: min}
    40  	g.mu.rng = ensureRand(rng)
    41  	g.mu.max = max
    42  	return g
    43  }
    44  
    45  // IncMax increments max.
    46  func (g *Uniform) IncMax(delta int) {
    47  	g.mu.Lock()
    48  	g.mu.max += uint64(delta)
    49  	g.mu.Unlock()
    50  }
    51  
    52  // Uint64 returns a random Uint64 between min and max, drawn from a uniform
    53  // distribution.
    54  func (g *Uniform) Uint64() uint64 {
    55  	g.mu.Lock()
    56  	result := g.mu.rng.Uint64n(g.mu.max-g.min+1) + g.min
    57  	g.mu.Unlock()
    58  	return result
    59  }