github.com/aclisp/heapster@v0.19.2-0.20160613100040-51756f899a96/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/rand/rand.go (about)

     1  /*
     2  Copyright 2015 The Kubernetes Authors All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package rand provides utilities related to randomization.
    18  package rand
    19  
    20  import (
    21  	"math/rand"
    22  	"sync"
    23  	"time"
    24  )
    25  
    26  var letters = []rune("abcdefghijklmnopqrstuvwxyz0123456789")
    27  var numLetters = len(letters)
    28  var rng = struct {
    29  	sync.Mutex
    30  	rand *rand.Rand
    31  }{
    32  	rand: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),
    33  }
    34  
    35  // Intn generates an integer in range 0->max.
    36  // By design this should panic if input is invalid, <= 0.
    37  func Intn(max int) int {
    38  	rng.Lock()
    39  	defer rng.Unlock()
    40  	return rng.rand.Intn(max)
    41  }
    42  
    43  // Seed seeds the rng with the provided seed.
    44  func Seed(seed int64) {
    45  	rng.Lock()
    46  	defer rng.Unlock()
    47  
    48  	rng.rand = rand.New(rand.NewSource(seed))
    49  }
    50  
    51  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
    52  // from the default Source.
    53  func Perm(n int) []int {
    54  	rng.Lock()
    55  	defer rng.Unlock()
    56  	return rng.rand.Perm(n)
    57  }
    58  
    59  // String generates a random alphanumeric string n characters long.  This will
    60  // panic if n is less than zero.
    61  func String(length int) string {
    62  	b := make([]rune, length)
    63  	for i := range b {
    64  		b[i] = letters[Intn(numLetters)]
    65  	}
    66  	return string(b)
    67  }
    68  
    69  // A type that satisfies the rand.Shufflable interface can be shuffled
    70  // by Shuffle. Any sort.Interface will satisfy this interface.
    71  type Shufflable interface {
    72  	Len() int
    73  	Swap(i, j int)
    74  }
    75  
    76  func Shuffle(data Shufflable) {
    77  	rng.Lock()
    78  	defer rng.Unlock()
    79  	for i := 0; i < data.Len(); i++ {
    80  		j := rng.rand.Intn(i + 1)
    81  		data.Swap(i, j)
    82  	}
    83  }