2021-04-19 13:42:47 +08:00
|
|
|
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
|
|
|
|
//
|
|
|
|
// 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.
|
|
|
|
|
2021-02-22 09:58:34 +08:00
|
|
|
package funcutil
|
|
|
|
|
|
|
|
import (
|
2021-09-09 10:06:29 +08:00
|
|
|
"fmt"
|
2021-02-22 09:58:34 +08:00
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-12-14 15:31:07 +08:00
|
|
|
var r *rand.Rand
|
2021-05-24 10:50:37 +08:00
|
|
|
|
2021-02-22 09:58:34 +08:00
|
|
|
func init() {
|
2021-10-04 23:40:01 +08:00
|
|
|
r = rand.New(rand.NewSource(time.Now().UnixNano()))
|
2021-02-22 09:58:34 +08:00
|
|
|
}
|
|
|
|
|
2021-12-16 16:35:42 +08:00
|
|
|
var letterRunes = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
2021-02-22 09:58:34 +08:00
|
|
|
|
2021-12-16 16:35:42 +08:00
|
|
|
// RandomBytes returns a batch of random string
|
|
|
|
func RandomBytes(n int) []byte {
|
|
|
|
b := make([]byte, n)
|
2021-02-22 09:58:34 +08:00
|
|
|
for i := range b {
|
2021-10-04 23:40:01 +08:00
|
|
|
b[i] = letterRunes[r.Intn(len(letterRunes))]
|
2021-02-22 09:58:34 +08:00
|
|
|
}
|
2021-12-16 16:35:42 +08:00
|
|
|
return b
|
2021-02-22 09:58:34 +08:00
|
|
|
}
|
2021-09-09 10:06:29 +08:00
|
|
|
|
2021-12-16 16:35:42 +08:00
|
|
|
// RandomString returns a batch of random string
|
|
|
|
func RandomString(n int) string {
|
|
|
|
return string(RandomBytes(n))
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenRandomBytes generates a random bytes.
|
|
|
|
func GenRandomBytes() []byte {
|
2021-09-09 10:06:29 +08:00
|
|
|
l := rand.Uint64()%10 + 1
|
|
|
|
b := make([]byte, l)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
2021-12-16 16:35:42 +08:00
|
|
|
return nil
|
2021-09-09 10:06:29 +08:00
|
|
|
}
|
2021-12-16 16:35:42 +08:00
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenRandomStr generates a random string.
|
|
|
|
func GenRandomStr() string {
|
|
|
|
return fmt.Sprintf("%X", GenRandomBytes())
|
2021-09-09 10:06:29 +08:00
|
|
|
}
|