Skip to content

Commit

Permalink
refactor: 更新至 v3
Browse files Browse the repository at this point in the history
math/rand 更新至 math/rand/v2
  • Loading branch information
caixw committed Mar 22, 2024
1 parent 33f1c3f commit 2301f9a
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 60 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ jobs:
test:
name: Test
runs-on: ${{ matrix.os }}

strategy:
matrix:
os: [ubuntu-latest, macOS-latest, windows-latest]
go: ['1.17.x', '1.22.x']
go: ['1.22.x']

steps:

- name: Check out code into the Go module directory
Expand All @@ -25,7 +25,7 @@ jobs:

- name: Vet
run: go vet -v ./...

- name: Test
run: go test -v -coverprofile='coverage.txt' -covermode=atomic ./...

Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ _testmain.go
*.swp
.idea/
.vscode/
.vs/
.zed/

# 测试文件
test.db
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ rands
[![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fissue9%2Frands%2Fbadge%3Fref%3Dmaster&style=flat)](https://actions-badge.atrox.dev/issue9/rands/goto?ref=master)
[![license](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](https://opensource.org/licenses/MIT)
[![codecov](https://codecov.io/gh/issue9/rands/branch/master/graph/badge.svg)](https://codecov.io/gh/issue9/rands)
[![Go Reference](https://pkg.go.dev/badge/github.com/issue9/rands.svg)](https://pkg.go.dev/github.com/issue9/rands/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/issue9/rands.svg)](https://pkg.go.dev/github.com/issue9/rands/v3)
======

rands 为一个随机字符串生成工具。

从 v3 开始只支持 go1.22 以之后的版本。

```go
// 生成一个长度为 [8,10) 之间的随机字符串
str := rands.String(8, 10, []byte("1234567890abcdefg"))
Expand All @@ -25,7 +27,7 @@ str2 := r.String()
----

```shell
go get github.com/issue9/rands/v2
go get github.com/issue9/rands/v3
```

版权
Expand Down
22 changes: 22 additions & 0 deletions chars.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2024 caixw
//
// SPDX-License-Identifier: MIT

package rands

var chars = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+[]{};':\",./<>?")

// Alpha 返回所有的字母
func Alpha() []byte { return chars[0:52] }

// Number 返回所有的数字
func Number() []byte { return chars[52:62] }

// Punct 返回所有的标点符号
func Punct() []byte { return chars[62:] }

// AlphaNumber [Alpha] + [Number]
func AlphaNumber() []byte { return chars[0:62] }

// AlphaNumberPunct [Alpha] + [Number] + [Punct]
func AlphaNumberPunct() []byte { return chars }
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module github.com/issue9/rands/v2
module github.com/issue9/rands/v3

require github.com/issue9/assert/v4 v4.1.1

go 1.17
go 1.22.0
69 changes: 24 additions & 45 deletions rands.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
// str := rands.String(6, 9, "1343567")
//
// // 生成一个带缓存功能的随机字符串生成器
// r := rands.New(time.Now().Unix(), 100, 5, 7, "adbcdefgadf;dfe1334")
// r := rands.New(nil, 100, 5, 7, "adbcdefgadf;dfe1334")
// ctx,cancel := context.WithCancel(context.Background())
// go r.Serve(ctx)
// defer cancel()
Expand All @@ -20,43 +20,15 @@ package rands

import (
"context"
"math/rand"
"time"
"math/rand/v2"
)

var (
chars = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+[]{};':\",./<>?")

random = rand.New(rand.NewSource(time.Now().UnixNano())) // 供全局函数使用的随机函数
)

// Alpha 返回所有的字母
func Alpha() []byte { return chars[0:52] }

// Number 返回所有的数字
func Number() []byte { return chars[52:62] }

// Punct 返回所有的标点符号
func Punct() []byte { return chars[62:] }

// AlphaNumber [Alpha] + [Number]
func AlphaNumber() []byte { return chars[0:62] }

// AlphaNumberPunct [Alpha] + [Number] + [Punct]
func AlphaNumberPunct() []byte { return chars }

// Seed 手动指定一个随机种子
//
// 默认情况下使用当前包初始化时的时间戳作为随机种子。
// [Bytes] 和 [String] 依赖此项。但是 [Rands] 有专门的随机函数,不受此影响。
func Seed(seed int64) { random = rand.New(rand.NewSource(seed)) } // TODO(go1.22) 改为 rand/v2

// Bytes 产生随机字符数组
//
// 其长度为[min, max),bs 所有的随机字符串从此处取。
func Bytes(min, max int, bs []byte) []byte {
checkArgs(min, max, bs)
return bytes(random, min, max, bs)
return bytes(rand.IntN, rand.Uint64, min, max, bs)
}

// String 产生一个随机字符串
Expand All @@ -66,39 +38,46 @@ func String(min, max int, bs []byte) string { return string(Bytes(min, max, bs))

// Rands 提供随机字符串的生成
type Rands struct {
random *rand.Rand
intn func(int) int
u64 func() uint64

min, max int
bytes []byte
channel chan []byte
}

// New 声明 [Rands]
//
// seed 随机种子,若为 0 表示使用当前时间作为随机种子。
// bufferSize 缓存的随机字符串数量,若为 0,表示不缓存
func New(seed int64, bufferSize, min, max int, bs []byte) *Rands {
// 如果 r 为 nil,将采用默认的随机函数;
// bufferSize 缓存的随机字符串数量,若为 0,表示不缓存
func New(r *rand.Rand, bufferSize, min, max int, bs []byte) *Rands {
checkArgs(min, max, bs)

if bufferSize <= 0 {
panic("bufferSize 必须大于零")
}

if seed == 0 {
seed = time.Now().UnixNano()
var intn func(int) int
var u64 func() uint64
if r == nil {
intn = rand.IntN
u64 = rand.Uint64
} else {
intn = r.IntN
u64 = rand.Uint64
}

return &Rands{
random: rand.New(rand.NewSource(seed)),
intn: intn,
u64: u64,

min: min,
max: max,
bytes: bs,
channel: make(chan []byte, bufferSize),
}
}

// Seed 重新指定随机种子
func (r *Rands) Seed(seed int64) { r.random.Seed(seed) }

// Bytes 产生随机字符数组
//
// 功能与全局函数 [Bytes] 相同,但参数通过 [New] 预先指定。
Expand All @@ -115,18 +94,18 @@ func (r *Rands) Serve(ctx context.Context) error {
case <-ctx.Done():
close(r.channel)
return ctx.Err()
case r.channel <- bytes(r.random, r.min, r.max, r.bytes):
case r.channel <- bytes(r.intn, r.u64, r.min, r.max, r.bytes):
}
}
}

// 生成介于 [min,max) 长度的随机字符数组
func bytes(r *rand.Rand, min, max int, bs []byte) []byte {
func bytes(intN func(int) int, u64 func() uint64, min, max int, bs []byte) []byte {
var l int
if max-1 == min {
l = min
} else {
l = min + r.Intn(max-min)
l = min + intN(max-min)
}

ll := uint64(len(bs))
Expand All @@ -146,7 +125,7 @@ func bytes(r *rand.Rand, min, max int, bs []byte) []byte {
ret := make([]byte, l)
for i := 0; i < l; {
// 在 index 不够大时,index>>bit 可能会让 index 变为 0,为 0 的 index 应该抛弃。
for index := r.Uint64(); index > 0 && i < l; {
for index := u64(); index > 0 && i < l; {
if idx := index & mask; idx < ll {
ret[i] = bs[idx]
i++
Expand Down
15 changes: 8 additions & 7 deletions rands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package rands

import (
"context"
"math/rand/v2"
"testing"
"time"

Expand Down Expand Up @@ -60,12 +61,12 @@ func TestCheckArgs(t *testing.T) {
// bytes
func TestBytes1(t *testing.T) {
a := assert.New(t, false)
r1 := random
r2 := random
r1 := rand.IntN
r2 := rand.Uint64

a.NotEqual(bytes(r1, 10, 11, []byte("1234123lks;df")), bytes(r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, 10, 11, []byte("1234123lks;df")), bytes(r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, 10, 11, []byte("1234123lks;df")), bytes(r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, r2, 10, 11, []byte("1234123lks;df")), bytes(r1, r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, r2, 10, 11, []byte("1234123lks;df")), bytes(r1, r2, 10, 11, []byte("1234123lks;df")))
a.NotEqual(bytes(r1, r2, 10, 11, []byte("1234123lks;df")), bytes(r1, r2, 10, 11, []byte("1234123lks;df")))

println("String:", String(10, 11, AlphaNumberPunct()))
}
Expand All @@ -86,10 +87,10 @@ func TestRandsBuffer(t *testing.T) {
a := assert.New(t, false)

a.PanicString(func() {
New(10000134, 0, 5, 7, []byte(";adkfjpqwei12124nbnb"))
New(rand.New(rand.NewPCG(0, 0)), 0, 5, 7, []byte(";adkfjpqwei12124nbnb"))
}, "bufferSize 必须大于零")

r := New(10000134, 2, 5, 7, []byte(";adkfjpqwei12124nbnb"))
r := New(nil, 2, 5, 7, []byte(";adkfjpqwei12124nbnb"))
a.NotNil(r)
ctx, cancel := context.WithCancel(context.Background())
go r.Serve(ctx)
Expand Down

0 comments on commit 2301f9a

Please sign in to comment.