vRp.CD2g_test/utils/super
kercylan98 fc14e73801 docs: 完善根目录 README.md,增加项目实践记录内容。生成子目录 README.md 文档 2024-01-24 11:12:34 +08:00
..
README.md docs: 完善根目录 README.md,增加项目实践记录内容。生成子目录 README.md 文档 2024-01-24 11:12:34 +08:00
bit_set.go test: super.BitSet 完善测试用例 2024-01-22 14:05:11 +08:00
bit_set_example_test.go test: super.BitSet 完善测试用例 2024-01-22 14:05:11 +08:00
bit_set_test.go test: super.BitSet 完善测试用例 2024-01-22 14:05:11 +08:00
channel.go feat: super 包新增 TryReadChannel、TryReadChannelByHandler 函数用于对 channel 尝试写入 2024-01-19 17:15:55 +08:00
error.go feat: super 包新增 RecoverTransform 函数,用于将 recover() 结果转化为 error 2023-12-25 14:39:26 +08:00
error_example_test.go feat: super 包新增 RecoverTransform 函数,用于将 recover() 结果转化为 error 2023-12-25 14:39:26 +08:00
error_test.go refactor: 重构 super 包中的 error 部分,优化设计不合理的地方,支持动态注册错误码,支持并发读写 2023-09-09 15:22:49 +08:00
function.go docs: 增加 space 包 README.md 文档,优化 room 相关内容可读性 2023-12-23 10:59:20 +08:00
gofmt.go feat: super 包支持使用 super.GoFormat 函数格式化 go 文件 2023-07-17 17:05:21 +08:00
if.go init commit 2023-04-07 11:21:50 +08:00
json.go fix: 修复 super 包 JSON 解析部分零值不正确的问题 2024-01-16 16:15:51 +08:00
loss_counter.go feat: super.LossCounter 支持打印 2023-11-10 11:55:51 +08:00
match.go feat: super 包支持 match 控制函数 2023-07-14 21:24:27 +08:00
match_test.go feat: super 包支持 match 控制函数 2023-07-14 21:24:27 +08:00
number.go feat: super 包新增 NumberToRome 函数,支持将整数转为罗马数字 2023-12-11 11:47:39 +08:00
number_test.go feat: super 包新增 NumberToRome 函数,支持将整数转为罗马数字 2023-12-11 11:47:39 +08:00
parse.go fix: #40 uint 类型溢出问题处理 2023-08-22 15:52:11 +08:00
permission.go feat: super 包新增简单的权限控制器,可通过 super.NewPermission 函数进行创建 2023-10-16 12:44:38 +08:00
permission_test.go feat: super 包新增简单的权限控制器,可通过 super.NewPermission 函数进行创建 2023-10-16 12:44:38 +08:00
retry.go feat: super.RetryByExponentialBackoff 和 super.ConditionalRetryByExponentialBackoff 支持设置忽略的错误,当返回忽略的错误时将不再进行重试 2023-12-12 10:52:51 +08:00
stack.go refactor: 调整 server 数据包相关处理函数的接收参数不再为 server.Packet,同时移除 server.Packet 2023-08-23 19:29:55 +08:00
super.go fix: log 包日志配置无效问题修复 2023-11-29 18:34:29 +08:00
unsafe.go feat: super 包支持使用 Convert 强制转换数据类型 2023-07-27 18:24:45 +08:00
unsafe_test.go test: 2023-07-27 18:26:21 +08:00
verify.go feat: super 包新增 Verify 函数,适用于业务条件校验 2023-07-29 10:03:43 +08:00
verify_example_test.go feat: super 包新增 Verify 函数,适用于业务条件校验 2023-07-29 10:03:43 +08:00
version.go feat: super 包新增 OldVersion 和 CompareVersion 函数用于版本比较 2023-11-29 20:01:35 +08:00
version_benchmark_test.go test: super 包中新增版本比较相关的测试用例 2023-12-05 12:07:50 +08:00
version_example_test.go test: super 包中新增版本比较相关的测试用例 2023-12-05 12:07:50 +08:00
version_test.go test: super 包中新增版本比较相关的测试用例 2023-12-05 12:07:50 +08:00

README.md

Super

Go doc

暂无介绍...

目录导航

列出了该 package 下所有的函数及类型定义,可通过目录导航进行快捷跳转 ❤️

展开 / 折叠目录导航

包级函数定义

函数名称 描述
NewBitSet 通过指定的 Bit 位创建一个 BitSet
TryWriteChannel 尝试写入 channel如果 channel 无法写入则忽略,返回是否写入成功
TryWriteChannelByHandler 尝试写入 channel如果 channel 无法写入则执行 handler
TryReadChannel 尝试读取 channel如果 channel 无法读取则忽略,返回是否读取成功
TryReadChannelByHandler 尝试读取 channel如果 channel 无法读取则执行 handler
RegError 通过错误码注册错误,返回错误的引用
RegErrorRef 通过错误码注册错误,返回错误的引用
GetError 通过错误引用获取错误码和真实错误信息,如果错误不存在则返回 0如果错误引用不存在则返回原本的错误
RecoverTransform recover 错误转换
Handle 执行 f 函数,如果 f 为 nil则不执行
HandleErr 执行 f 函数,如果 f 为 nil则不执行
HandleV 执行 f 函数,如果 f 为 nil则不执行
GoFormat go 代码格式化
If 暂无描述...
MarshalJSON 将对象转换为 json
MarshalJSONE 将对象转换为 json
UnmarshalJSON 将 json 转换为对象
MarshalIndentJSON 将对象转换为 json
MarshalToTargetWithJSON 将对象转换为目标对象
StartLossCounter 开始损耗计数
Match 匹配
IsNumber 判断是否为数字
NumberToRome 将数字转换为罗马数字
StringToInt 字符串转换为整数
StringToFloat64 字符串转换为 float64
StringToBool 字符串转换为 bool
StringToUint64 字符串转换为 uint64
StringToUint 字符串转换为 uint
StringToFloat32 字符串转换为 float32
StringToInt64 字符串转换为 int64
StringToUint32 字符串转换为 uint32
StringToInt32 字符串转换为 int32
StringToUint16 字符串转换为 uint16
StringToInt16 字符串转换为 int16
StringToUint8 字符串转换为 uint8
StringToInt8 字符串转换为 int8
StringToByte 字符串转换为 byte
StringToRune 字符串转换为 rune
IntToString 整数转换为字符串
Float64ToString float64 转换为字符串
BoolToString bool 转换为字符串
Uint64ToString uint64 转换为字符串
UintToString uint 转换为字符串
Float32ToString float32 转换为字符串
Int64ToString int64 转换为字符串
Uint32ToString uint32 转换为字符串
Int32ToString int32 转换为字符串
Uint16ToString uint16 转换为字符串
Int16ToString int16 转换为字符串
Uint8ToString uint8 转换为字符串
Int8ToString int8 转换为字符串
ByteToString byte 转换为字符串
RuneToString rune 转换为字符串
StringToSlice 字符串转换为切片
SliceToString 切片转换为字符串
NewPermission 创建权限
Retry 根据提供的 count 次数尝试执行 f 函数,如果 f 函数返回错误,则在 interval 后重试,直到成功或者达到 count 次数
RetryByRule 根据提供的规则尝试执行 f 函数,如果 f 函数返回错误,则根据 rule 的返回值进行重试
RetryByExponentialBackoff 根据指数退避算法尝试执行 f 函数
ConditionalRetryByExponentialBackoff 该函数与 RetryByExponentialBackoff 类似,但是可以被中断
RetryAsync 与 Retry 类似,但是是异步执行
RetryForever 根据提供的 interval 时间间隔尝试执行 f 函数,如果 f 函数返回错误,则在 interval 后重试,直到成功
NewStackGo 返回一个用于获取上一个协程调用的堆栈信息的收集器
LaunchTime 获取程序启动时间
Hostname 获取主机名
PID 获取进程 PID
StringToBytes 以零拷贝的方式将字符串转换为字节切片
BytesToString 以零拷贝的方式将字节切片转换为字符串
Convert 以零拷贝的方式将一个对象转换为另一个对象
Verify 对特定表达式进行校验,当表达式不成立时,将执行 handle
OldVersion 检查 version2 对于 version1 来说是不是旧版本
CompareVersion 返回一个整数,用于表示两个版本号的比较结果:

类型定义

类型 名称 描述
STRUCT BitSet 是一个可以动态增长的比特位集合
STRUCT LossCounter 暂无描述...
STRUCT Matcher 匹配器
STRUCT Permission 暂无描述...
STRUCT StackGo 用于获取上一个协程调用的堆栈信息
STRUCT VerifyHandle 校验句柄

详情信息

func NewBitSet[Bit generic.Integer](bits ...Bit) *BitSet[Bit]

通过指定的 Bit 位创建一个 BitSet

  • 当指定的 Bit 位存在负数时,将会 panic

示例代码:


func ExampleNewBitSet() {
	var bs = super.NewBitSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
	bs.Set(10)
	fmt.Println(bs.Bits())
}

查看 / 收起单元测试

func TestNewBitSet(t *testing.T) {
	var cases = []struct {
		name        string
		in          []int
		shouldPanic bool
	}{{name: "normal", in: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}}, {name: "empty", in: make([]int, 0)}, {name: "nil", in: nil}, {name: "negative", in: []int{-1, -2}, shouldPanic: true}}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			defer func() {
				if r := recover(); r != nil && !c.shouldPanic {
					t.Fatalf("panic: %v", r)
				}
			}()
			bs := super.NewBitSet(c.in...)
			t.Log(bs)
		})
	}
}


func TryWriteChannel[T any](ch chan T, data T) bool

尝试写入 channel如果 channel 无法写入则忽略,返回是否写入成功

  • 无法写入的情况包括channel 已满、channel 已关闭

func TryWriteChannelByHandler[T any](ch chan T, data T, handler func ())

尝试写入 channel如果 channel 无法写入则执行 handler

  • 无法写入的情况包括channel 已满、channel 已关闭

func TryReadChannel[T any](ch chan T) (v T, suc bool)

尝试读取 channel如果 channel 无法读取则忽略,返回是否读取成功

  • 无法读取的情况包括channel 已空、channel 已关闭

func TryReadChannelByHandler[T any](ch chan T, handler func (ch chan T) T) (v T)

尝试读取 channel如果 channel 无法读取则执行 handler

  • 无法读取的情况包括channel 已空、channel 已关闭

func RegError(code int, message string) error

通过错误码注册错误,返回错误的引用


func RegErrorRef(code int, message string, ref error) error

通过错误码注册错误,返回错误的引用

  • 引用将会被重定向到注册的错误信息

func GetError(err error) (int, error)

通过错误引用获取错误码和真实错误信息,如果错误不存在则返回 0如果错误引用不存在则返回原本的错误

查看 / 收起单元测试

func TestGetError(t *testing.T) {
	var ErrNotFound = errors.New("not found")
	var _ = super.RegErrorRef(100, "test error", ErrNotFound)
	t.Log(super.GetError(ErrNotFound))
}


func RecoverTransform(a any) error

recover 错误转换

示例代码:


func ExampleRecoverTransform() {
	defer func() {
		if err := super.RecoverTransform(recover()); err != nil {
			fmt.Println(err)
		}
	}()
	panic("test")
}


func Handle(f func ())

执行 f 函数,如果 f 为 nil则不执行


func HandleErr(f func () error) error

执行 f 函数,如果 f 为 nil则不执行


func HandleV[V any](v V, f func (v V))

执行 f 函数,如果 f 为 nil则不执行


func GoFormat(filePath string)

go 代码格式化


func If[T any](expression bool, t T, f T) T


func MarshalJSON(v interface {}) []byte

将对象转换为 json

  • 当转换失败时,将返回 json 格式的空对象

func MarshalJSONE(v interface {}) ([]byte, error)

将对象转换为 json

  • 当转换失败时,将返回错误信息

func UnmarshalJSON(data []byte, v interface {}) error

将 json 转换为对象


func MarshalIndentJSON(v interface {}, prefix string, indent string) []byte

将对象转换为 json


func MarshalToTargetWithJSON(src interface {}, dest interface {}) error

将对象转换为目标对象


func StartLossCounter() *LossCounter

开始损耗计数


func Match[Value any, Result any](value Value) *Matcher[Value, Result]

匹配

查看 / 收起单元测试

func TestMatch(t *testing.T) {
	Convey("TestMatch", t, func() {
		So(super.Match[int, string](1).Case(1, "a").Case(2, "b").Default("c"), ShouldEqual, "a")
		So(super.Match[int, string](2).Case(1, "a").Case(2, "b").Default("c"), ShouldEqual, "b")
		So(super.Match[int, string](3).Case(1, "a").Case(2, "b").Default("c"), ShouldEqual, "c")
	})
}


func IsNumber(v any) bool

判断是否为数字


func NumberToRome(num int) string

将数字转换为罗马数字

查看 / 收起单元测试

func TestNumberToRome(t *testing.T) {
	tests := []struct {
		input  int
		output string
	}{{input: 1, output: "I"}, {input: 5, output: "V"}, {input: 10, output: "X"}, {input: 50, output: "L"}, {input: 100, output: "C"}, {input: 500, output: "D"}, {input: 1000, output: "M"}}
	for _, test := range tests {
		result := super.NumberToRome(test.input)
		if result != test.output {
			t.Errorf("NumberToRome(%d) = %s; want %s", test.input, result, test.output)
		}
	}
}


func StringToInt(value string) int

字符串转换为整数


func StringToFloat64(value string) float64

字符串转换为 float64


func StringToBool(value string) bool

字符串转换为 bool


func StringToUint64(value string) uint64

字符串转换为 uint64


func StringToUint(value string) uint

字符串转换为 uint


func StringToFloat32(value string) float32

字符串转换为 float32


func StringToInt64(value string) int64

字符串转换为 int64


func StringToUint32(value string) uint32

字符串转换为 uint32


func StringToInt32(value string) int32

字符串转换为 int32


func StringToUint16(value string) uint16

字符串转换为 uint16


func StringToInt16(value string) int16

字符串转换为 int16


func StringToUint8(value string) uint8

字符串转换为 uint8


func StringToInt8(value string) int8

字符串转换为 int8


func StringToByte(value string) byte

字符串转换为 byte


func StringToRune(value string) rune

字符串转换为 rune


func IntToString(value int) string

整数转换为字符串


func Float64ToString(value float64) string

float64 转换为字符串


func BoolToString(value bool) string

bool 转换为字符串


func Uint64ToString(value uint64) string

uint64 转换为字符串


func UintToString(value uint) string

uint 转换为字符串


func Float32ToString(value float32) string

float32 转换为字符串


func Int64ToString(value int64) string

int64 转换为字符串


func Uint32ToString(value uint32) string

uint32 转换为字符串


func Int32ToString(value int32) string

int32 转换为字符串


func Uint16ToString(value uint16) string

uint16 转换为字符串


func Int16ToString(value int16) string

int16 转换为字符串


func Uint8ToString(value uint8) string

uint8 转换为字符串


func Int8ToString(value int8) string

int8 转换为字符串


func ByteToString(value byte) string

byte 转换为字符串


func RuneToString(value rune) string

rune 转换为字符串


func StringToSlice(value string) []string

字符串转换为切片


func SliceToString(value []string) string

切片转换为字符串


func NewPermission[Code generic.Integer, EntityID comparable]() *Permission[Code, EntityID]

创建权限

查看 / 收起单元测试

func TestNewPermission(t *testing.T) {
	const (
		Read = 1 << iota
		Write
		Execute
	)
	p := super.NewPermission[int, int]()
	p.AddPermission(1, Read, Write)
	t.Log(p.HasPermission(1, Read))
	t.Log(p.HasPermission(1, Write))
	p.SetPermission(2, Read|Write)
	t.Log(p.HasPermission(2, Read))
	t.Log(p.HasPermission(2, Execute))
	p.SetPermission(2, Execute)
	t.Log(p.HasPermission(2, Execute))
	t.Log(p.HasPermission(2, Read))
	t.Log(p.HasPermission(2, Write))
	p.RemovePermission(2, Execute)
	t.Log(p.HasPermission(2, Execute))
}


func Retry(count int, interval time.Duration, f func () error) error

根据提供的 count 次数尝试执行 f 函数,如果 f 函数返回错误,则在 interval 后重试,直到成功或者达到 count 次数


func RetryByRule(f func () error, rule func (count int) time.Duration) error

根据提供的规则尝试执行 f 函数,如果 f 函数返回错误,则根据 rule 的返回值进行重试

  • rule 将包含一个入参,表示第几次重试,返回值表示下一次重试的时间间隔,当返回值为 0 时,表示不再重试
  • rule 的 count 将在 f 首次失败后变为 1因此 rule 的入参将从 1 开始

func RetryByExponentialBackoff(f func () error, maxRetries int, baseDelay time.Duration, maxDelay time.Duration, multiplier float64, randomization float64, ignoreErrors ...error) error

根据指数退避算法尝试执行 f 函数

  • maxRetries最大重试次数
  • baseDelay基础延迟
  • maxDelay最大延迟
  • multiplier延迟时间的乘数通常为 2
  • randomization延迟时间的随机化因子通常为 0.5
  • ignoreErrors忽略的错误当 f 返回的错误在 ignoreErrors 中时,将不会进行重试

func ConditionalRetryByExponentialBackoff(f func () error, cond func () bool, maxRetries int, baseDelay time.Duration, maxDelay time.Duration, multiplier float64, randomization float64, ignoreErrors ...error) error

该函数与 RetryByExponentialBackoff 类似,但是可以被中断

  • cond 为中断条件,当 cond 返回 false 时,将会中断重试

该函数通常用于在重试过程中,需要中断重试的场景,例如:

  • 用户请求开始游戏,由于网络等情况,进入重试状态。此时用户再次发送开始游戏请求,此时需要中断之前的重试,避免重复进入游戏

func RetryAsync(count int, interval time.Duration, f func () error, callback func (err error))

与 Retry 类似,但是是异步执行

  • 传入的 callback 函数会在执行完毕后被调用,如果执行成功,则 err 为 nil否则为错误信息
  • 如果 callback 为 nil则不会在执行完毕后被调用

func RetryForever(interval time.Duration, f func () error)

根据提供的 interval 时间间隔尝试执行 f 函数,如果 f 函数返回错误,则在 interval 后重试,直到成功


func NewStackGo() *StackGo

返回一个用于获取上一个协程调用的堆栈信息的收集器


func LaunchTime() time.Time

获取程序启动时间


func Hostname() string

获取主机名


func PID() int

获取进程 PID


func StringToBytes(s string) []byte

以零拷贝的方式将字符串转换为字节切片


func BytesToString(b []byte) string

以零拷贝的方式将字节切片转换为字符串


func Convert[A any, B any](src A) B

以零拷贝的方式将一个对象转换为另一个对象

  • 两个对象字段必须完全一致
  • 该函数可以绕过私有字段的访问限制
查看 / 收起单元测试

func TestConvert(t *testing.T) {
	type B struct {
		nocmp [0]func()
		v     atomic.Value
	}
	var a = atomic.NewString("hello")
	var b = super.Convert[*atomic.String, *B](a)
	fmt.Println(b.v.Load())
}


func Verify[V any](handle func ( V)) *VerifyHandle[V]

对特定表达式进行校验,当表达式不成立时,将执行 handle

示例代码:


func ExampleVerify() {
	var getId = func() int {
		return 1
	}
	var n *super.VerifyHandle[int]
	super.Verify(func(err error) {
		fmt.Println(err)
	}).Case(getId() == 1, errors.New("id can't be 1")).Do()
	super.Verify(func(err error) {
		fmt.Println(err)
	}).PreCase(func() bool {
		return n == nil
	}, errors.New("n can't be nil"), func(verify *super.VerifyHandle[error]) bool {
		return verify.Do()
	})
}


func OldVersion(version1 string, version2 string) bool

检查 version2 对于 version1 来说是不是旧版本

示例代码:


func ExampleOldVersion() {
	result := super.OldVersion("1.2.3", "1.2.2")
	fmt.Println(result)
}

查看 / 收起单元测试

func TestOldVersion(t *testing.T) {
	testCases := []struct {
		version1 string
		version2 string
		want     bool
	}{{"1.2.3", "1.2.2", true}, {"1.2.1", "1.2.2", false}, {"1.2.3", "1.2.3", false}, {"v1.2.3", "v1.2.2", true}, {"v1.2.3", "v1.2.4", false}, {"v1.2.3", "1.2.3", false}, {"vxx2faf.d2ad5.dd3", "gga2faf.d2ad5.dd2", true}, {"awd2faf.d2ad4.dd3", "vsd2faf.d2ad5.dd3", false}, {"vxd2faf.d2ad5.dd3", "qdq2faf.d2ad5.dd3", false}, {"1.2.3", "vdafe2faf.d2ad5.dd3", false}, {"v1.2.3", "vdafe2faf.d2ad5.dd3", false}}
	for _, tc := range testCases {
		got := super.OldVersion(tc.version1, tc.version2)
		if got != tc.want {
			t.Errorf("OldVersion(%q, %q) = %v; want %v", tc.version1, tc.version2, got, tc.want)
		}
	}
}

查看 / 收起基准测试

func BenchmarkOldVersion(b *testing.B) {
	for i := 0; i < b.N; i++ {
		super.OldVersion("vfe2faf.d2ad5.dd3", "vda2faf.d2ad5.dd2")
	}
}


func CompareVersion(version1 string, version2 string) int

返回一个整数,用于表示两个版本号的比较结果:

  • 如果 version1 大于 version2它将返回 1
  • 如果 version1 小于 version2它将返回 -1
  • 如果 version1 和 version2 相等,它将返回 0

示例代码:


func ExampleCompareVersion() {
	result := super.CompareVersion("1.2.3", "1.2.2")
	fmt.Println(result)
}

查看 / 收起单元测试

func TestCompareVersion(t *testing.T) {
	testCases := []struct {
		version1 string
		version2 string
		want     int
	}{{"1.2.3", "1.2.2", 1}, {"1.2.1", "1.2.2", -1}, {"1.2.3", "1.2.3", 0}, {"v1.2.3", "v1.2.2", 1}, {"v1.2.3", "v1.2.4", -1}, {"v1.2.3", "1.2.3", 0}, {"vde2faf.d2ad5.dd3", "e2faf.d2ad5.dd2", 1}, {"vde2faf.d2ad4.dd3", "vde2faf.d2ad5.dd3", -1}, {"vfe2faf.d2ad5.dd3", "ve2faf.d2ad5.dd3", 0}, {"1.2.3", "vdafe2faf.d2ad5.dd3", -1}, {"v1.2.3", "vdafe2faf.d2ad5.dd3", -1}}
	for _, tc := range testCases {
		got := super.CompareVersion(tc.version1, tc.version2)
		if got != tc.want {
			t.Errorf("CompareVersion(%q, %q) = %v; want %v", tc.version1, tc.version2, got, tc.want)
		}
	}
}

查看 / 收起基准测试

func BenchmarkCompareVersion(b *testing.B) {
	for i := 0; i < b.N; i++ {
		super.CompareVersion("vfe2faf.d2ad5.dd3", "afe2faf.d2ad5.dd2")
	}
}


BitSet STRUCT

是一个可以动态增长的比特位集合

  • 默认情况下将使用 64 位无符号整数来表示比特位,当需要表示的比特位超过 64 位时,将自动增长
type BitSet[Bit generic.Integer] struct {
	set []uint64
}

func (*BitSet) Set(bit Bit) *BitSet[Bit]

将指定的位 bit 设置为 1

示例代码:


func ExampleBitSet_Set() {
	var bs = super.NewBitSet[int]()
	bs.Set(10)
	fmt.Println(bs.Bits())
}

查看 / 收起单元测试

func TestBitSet_Set(t *testing.T) {
	var cases = []struct {
		name        string
		in          []int
		shouldPanic bool
	}{{name: "normal", in: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}}, {name: "empty", in: make([]int, 0)}, {name: "nil", in: nil}, {name: "negative", in: []int{-1, -2}, shouldPanic: true}}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			defer func() {
				if r := recover(); r != nil && !c.shouldPanic {
					t.Fatalf("panic: %v", r)
				}
			}()
			bs := super.NewBitSet[int]()
			for _, bit := range c.in {
				bs.Set(bit)
			}
			for _, bit := range c.in {
				if !bs.Has(bit) {
					t.Fatalf("bit %v not set", bit)
				}
			}
		})
	}
}


func (*BitSet) Del(bit Bit) *BitSet[Bit]

将指定的位 bit 设置为 0

示例代码:


func ExampleBitSet_Del() {
	var bs = super.NewBitSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
	bs.Del(1)
	fmt.Println(bs.Bits())
}

查看 / 收起单元测试

func TestBitSet_Del(t *testing.T) {
	var cases = []struct {
		name        string
		in          []int
		shouldPanic bool
	}{{name: "normal", in: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}}, {name: "empty", in: make([]int, 0)}, {name: "nil", in: nil}, {name: "negative", in: []int{-1, -2}, shouldPanic: true}}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			defer func() {
				if r := recover(); r != nil && !c.shouldPanic {
					t.Fatalf("panic: %v", r)
				}
			}()
			bs := super.NewBitSet[int]()
			for _, bit := range c.in {
				bs.Set(bit)
			}
			for _, bit := range c.in {
				bs.Del(bit)
			}
			for _, bit := range c.in {
				if bs.Has(bit) {
					t.Fatalf("bit %v not del", bit)
				}
			}
		})
	}
}


func (*BitSet) Shrink() *BitSet[Bit]

将 BitSet 中的比特位集合缩小到最小

  • 正常情况下当 BitSet 中的比特位超出 64 位时,将自动增长,当 BitSet 中的比特位数量减少时,可以使用该方法将 BitSet 中的比特位集合缩小到最小

示例代码:


func ExampleBitSet_Shrink() {
	var bs = super.NewBitSet(111, 222, 333, 444)
	fmt.Println(bs.Cap())
	bs.Del(444)
	fmt.Println(bs.Cap())
	bs.Shrink()
	fmt.Println(bs.Cap())
}

查看 / 收起单元测试

func TestBitSet_Shrink(t *testing.T) {
	var cases = []struct {
		name string
		in   []int
	}{{name: "normal", in: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}}, {name: "empty", in: make([]int, 0)}, {name: "nil", in: nil}}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			bs := super.NewBitSet(c.in...)
			for _, v := range c.in {
				bs.Del(v)
			}
			bs.Shrink()
			if bs.Cap() != 0 {
				t.Fatalf("cap %v != 0", bs.Cap())
			}
		})
	}
}


func (*BitSet) Cap() int

返回当前 BitSet 中可以表示的最大比特位数量

示例代码:


func ExampleBitSet_Cap() {
	var bs = super.NewBitSet(63)
	fmt.Println(bs.Cap())
}


func (*BitSet) Has(bit Bit) bool

检查指定的位 bit 是否被设置为 1

示例代码:


func ExampleBitSet_Has() {
	var bs = super.NewBitSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
	fmt.Println(bs.Has(1))
	fmt.Println(bs.Has(10))
}


func (*BitSet) Clear() *BitSet[Bit]

清空所有的比特位

示例代码:


func ExampleBitSet_Clear() {
	var bs = super.NewBitSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
	bs.Clear()
	fmt.Println(bs.Bits())
}


func (*BitSet) Len() int

返回当前 BitSet 中被设置的比特位数量

示例代码:


func ExampleBitSet_Len() {
	var bs = super.NewBitSet(1, 2, 3, 4, 5, 6, 7, 8, 9)
	fmt.Println(bs.Len())
}


func (*BitSet) Bits() []Bit

返回当前 BitSet 中被设置的比特位


func (*BitSet) Reverse() *BitSet[Bit]

反转当前 BitSet 中的所有比特位


func (*BitSet) Not() *BitSet[Bit]

返回当前 BitSet 中所有比特位的反转


func (*BitSet) And(other *BitSet[Bit]) *BitSet[Bit]

将当前 BitSet 与另一个 BitSet 进行按位与运算


func (*BitSet) Or(other *BitSet[Bit]) *BitSet[Bit]

将当前 BitSet 与另一个 BitSet 进行按位或运算


func (*BitSet) Xor(other *BitSet[Bit]) *BitSet[Bit]

将当前 BitSet 与另一个 BitSet 进行按位异或运算


func (*BitSet) Sub(other *BitSet[Bit]) *BitSet[Bit]

将当前 BitSet 与另一个 BitSet 进行按位减运算


func (*BitSet) IsZero() bool

检查当前 BitSet 是否为空


func (*BitSet) Clone() *BitSet[Bit]

返回当前 BitSet 的副本


func (*BitSet) Equal(other *BitSet[Bit]) bool

检查当前 BitSet 是否与另一个 BitSet 相等


func (*BitSet) Contains(other *BitSet[Bit]) bool

检查当前 BitSet 是否包含另一个 BitSet


func (*BitSet) ContainsAny(other *BitSet[Bit]) bool

检查当前 BitSet 是否包含另一个 BitSet 中的任意比特位


func (*BitSet) ContainsAll(other *BitSet[Bit]) bool

检查当前 BitSet 是否包含另一个 BitSet 中的所有比特位


func (*BitSet) Intersect(other *BitSet[Bit]) bool

检查当前 BitSet 是否与另一个 BitSet 有交集


func (*BitSet) Union(other *BitSet[Bit]) bool

检查当前 BitSet 是否与另一个 BitSet 有并集


func (*BitSet) Difference(other *BitSet[Bit]) bool

检查当前 BitSet 是否与另一个 BitSet 有差集


func (*BitSet) SymmetricDifference(other *BitSet[Bit]) bool

检查当前 BitSet 是否与另一个 BitSet 有对称差集


func (*BitSet) Subset(other *BitSet[Bit]) bool

检查当前 BitSet 是否为另一个 BitSet 的子集


func (*BitSet) Superset(other *BitSet[Bit]) bool

检查当前 BitSet 是否为另一个 BitSet 的超集


func (*BitSet) Complement(other *BitSet[Bit]) bool

检查当前 BitSet 是否为另一个 BitSet 的补集


func (*BitSet) Max() Bit

返回当前 BitSet 中最大的比特位


func (*BitSet) Min() Bit

返回当前 BitSet 中最小的比特位


func (*BitSet) String() string

返回当前 BitSet 的字符串表示


func (*BitSet) MarshalJSON() ( []byte, error)

实现 json.Marshaler 接口


func (*BitSet) UnmarshalJSON(data []byte) error

实现 json.Unmarshaler 接口


LossCounter STRUCT

type LossCounter struct {
	curr    time.Time
	loss    []time.Duration
	lossKey []string
}

func (*LossCounter) Record(name string)

记录一次损耗


func (*LossCounter) GetLoss(handler func (step int, name string, loss time.Duration))

获取损耗


func (*LossCounter) String() string


Matcher STRUCT

匹配器

type Matcher[Value any, Result any] struct {
	value Value
	r     Result
	d     bool
}

func (*Matcher) Case(value Value, result Result) *Matcher[Value, Result]

匹配


func (*Matcher) Default(value Result) Result

默认


Permission STRUCT

type Permission[Code generic.Integer, EntityID comparable] struct {
	permissions map[EntityID]Code
	l           sync.RWMutex
}

func (*Permission) HasPermission(entityId EntityID, permission Code) bool

是否有权限


func (*Permission) AddPermission(entityId EntityID, permission ...Code)

添加权限


func (*Permission) RemovePermission(entityId EntityID, permission ...Code)

移除权限


func (*Permission) SetPermission(entityId EntityID, permission ...Code)

设置权限


StackGo STRUCT

用于获取上一个协程调用的堆栈信息

  • 应当最先运行 Wait 函数,然后在其他协程中调用 Stack 函数或者 GiveUp 函数
  • 适用于跨协程同步通讯,例如单线程的消息处理统计耗时打印堆栈信息
type StackGo struct {
	stack   chan *struct{}
	collect chan []byte
}

func (*StackGo) Wait()

等待收集消息堆栈

  • 在调用 Wait 函数后,当前协程将会被挂起,直到调用 Stack 或 GiveUp 函数

func (*StackGo) Stack() []byte

获取消息堆栈

  • 在调用 Wait 函数后调用该函数,将会返回上一个协程的堆栈信息
  • 在调用 GiveUp 函数后调用该函数,将会 panic

func (*StackGo) GiveUp()

放弃收集消息堆栈

  • 在调用 Wait 函数后调用该函数,将会放弃收集消息堆栈并且释放资源
  • 在调用 GiveUp 函数后调用 Stack 函数,将会 panic

VerifyHandle STRUCT

校验句柄

type VerifyHandle[V any] struct {
	handle func(V)
	v      V
	hit    bool
}

func (*VerifyHandle) PreCase(expression func () bool, value V, caseHandle func (verify *VerifyHandle[V]) bool) bool

先决校验用例,当 expression 成立时,将跳过 caseHandle 的执行,直接执行 handle 并返回 false

  • 常用于对前置参数的空指针校验,例如当 a 为 nil 时,不执行 a.B(),而是直接返回 false

func (*VerifyHandle) Case(expression bool, value V) *VerifyHandle[V]

校验用例,当 expression 成立时,将忽略后续 Case并将在 Do 时执行 handle返回 false


func (*VerifyHandle) Do() bool

执行校验,当校验失败时,将执行 handle并返回 false