Skip to content

Commit

Permalink
use math/rand/v2 for go1.22+
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Feb 20, 2024
1 parent feeb95a commit b08b0cc
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 5 deletions.
20 changes: 20 additions & 0 deletions helper/rand.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright 2024 xgfone
//
// 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 helper

import "math/rand"

// IntN is the alias of the function "math/rand.Intn" or "math/rand/v2.IntN".
var IntN = rand.Intn
22 changes: 22 additions & 0 deletions helper/rand_go1.22.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright 2024 xgfone
//
// 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.

//go:build go1.22
// +build go1.22

package helper

import "math/rand/v2"

func init() { IntN = rand.IntN }
7 changes: 2 additions & 5 deletions helper/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@

package helper

import (
"math/rand"
"unsafe"
)
import "unsafe"

// Pre-define some charsets to generate the random string.
var (
Expand Down Expand Up @@ -48,7 +45,7 @@ func RandomString(n int, charset string) string {
func Random(buf []byte, charset string) {
nlen := len(charset)
for i, _len := 0, len(buf); i < _len; i++ {
buf[i] = charset[rand.Intn(nlen)]
buf[i] = charset[IntN(nlen)]
}
}

Expand Down

0 comments on commit b08b0cc

Please sign in to comment.