...

Source file src/go.etcd.io/etcd/pkg/v3/stringutil/rand.go

Documentation: go.etcd.io/etcd/pkg/v3/stringutil

     1  // Copyright 2018 The etcd 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 implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package stringutil
    16  
    17  import (
    18  	"math/rand"
    19  	"time"
    20  )
    21  
    22  // UniqueStrings returns a slice of randomly generated unique strings.
    23  func UniqueStrings(slen uint, n int) (ss []string) {
    24  	exist := make(map[string]struct{})
    25  	ss = make([]string, 0, n)
    26  	for len(ss) < n {
    27  		s := RandString(slen)
    28  		if _, ok := exist[s]; !ok {
    29  			ss = append(ss, s)
    30  			exist[s] = struct{}{}
    31  		}
    32  	}
    33  	return ss
    34  }
    35  
    36  // RandomStrings returns a slice of randomly generated strings.
    37  func RandomStrings(slen uint, n int) (ss []string) {
    38  	ss = make([]string, 0, n)
    39  	for i := 0; i < n; i++ {
    40  		ss = append(ss, RandString(slen))
    41  	}
    42  	return ss
    43  }
    44  
    45  const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    46  
    47  func RandString(l uint) string {
    48  	rand.Seed(time.Now().UnixNano())
    49  	s := make([]byte, l)
    50  	for i := 0; i < int(l); i++ {
    51  		s[i] = chars[rand.Intn(len(chars))]
    52  	}
    53  	return string(s)
    54  }
    55  

View as plain text