mirror of https://github.com/etcd-io/dbtester.git
86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
// Copyright 2017 CoreOS, Inc.
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package dbtester
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
mrand "math/rand"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// sequentialKey returns '00012' when size is 5 and num is 12.
|
|
func sequentialKey(size, num int64) string {
|
|
txt := fmt.Sprintf("%d", num)
|
|
if len(txt) > int(size) {
|
|
return txt
|
|
}
|
|
delta := int(size) - len(txt)
|
|
return strings.Repeat("0", delta) + txt
|
|
}
|
|
|
|
func sameKey(size int64) string {
|
|
return strings.Repeat("a", int(size))
|
|
}
|
|
|
|
func randBytes(bytesN int64) []byte {
|
|
const (
|
|
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
letterIdxBits = 6 // 6 bits to represent a letter index
|
|
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
|
|
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
|
|
)
|
|
src := mrand.NewSource(time.Now().UnixNano())
|
|
b := make([]byte, bytesN)
|
|
for i, cache, remain := bytesN-1, src.Int63(), letterIdxMax; i >= 0; {
|
|
if remain == 0 {
|
|
cache, remain = src.Int63(), letterIdxMax
|
|
}
|
|
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
|
b[i] = letterBytes[idx]
|
|
i--
|
|
}
|
|
cache >>= letterIdxBits
|
|
remain--
|
|
}
|
|
return b
|
|
}
|
|
|
|
func mustRandBytes(n int) []byte {
|
|
rb := make([]byte, n)
|
|
_, err := rand.Read(rb)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "failed to generate value: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
return rb
|
|
}
|
|
|
|
func multiRandStrings(keyN, sliceN int64) []string {
|
|
m := make(map[string]struct{})
|
|
for int64(len(m)) != sliceN {
|
|
m[string(randBytes(keyN))] = struct{}{}
|
|
}
|
|
rs := make([]string, sliceN)
|
|
idx := 0
|
|
for k := range m {
|
|
rs[idx] = k
|
|
idx++
|
|
}
|
|
return rs
|
|
}
|