Skip to content

Commit

Permalink
整理代码
Browse files Browse the repository at this point in the history
  • Loading branch information
pangdogs committed Jan 17, 2025
1 parent d562144 commit fdde291
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 23 deletions.
13 changes: 7 additions & 6 deletions utils/iface/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,21 @@ import (
"unsafe"
)

// Cache 因为Golang原生的接口转换性能较差,所以在某些性能要求较高的场景下,需要尽量较少接口转换。
var (
NilCache Cache // nil cache
)

// Cache 接口存储器,因为Golang原生的接口转换性能较差,所以在某些性能要求较高的场景下,需要尽量较少接口转换。
// 如果必须转换接口,那么目前可用的优化方案是,在编码时已知接口类型,可以将接口转换为[2]unsafe.Pointer,使用时再转换回接口。
// Cache套件就是使用此优化方案,注意不安全,在明确了解此方案时再使用。
type Cache [2]unsafe.Pointer

// NilCache nil cache
var NilCache Cache

// Cache2Iface Cache转换为接口
// Cache2Iface 接口存储器(Cache)转换为接口
func Cache2Iface[T any](c Cache) T {
return *(*T)(unsafe.Pointer(&c))
}

// Iface2Cache 接口转换为Cache
// Iface2Cache 接口转换为接口存储器(Cache)
func Iface2Cache[T any](i T) Cache {
return *(*Cache)(unsafe.Pointer(&i))
}
34 changes: 17 additions & 17 deletions utils/iface/face.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,37 +24,37 @@ import (
"reflect"
)

// Face 用于存储接口与Cache,接口可用于断言转换类型,存储器可用于转换为接口
// FaceAny face with any
type FaceAny = Face[any]

// MakeFaceAny 创建 FaceAny
func MakeFaceAny[C any](cache C) FaceAny {
return Face[any]{
Iface: cache,
Cache: Iface2Cache[C](cache),
}
}

// Face 面,用于存储接口与接口存储器,接口用于断言转换类型,接口存储器用于重解释接口
type Face[T any] struct {
Iface T
Cache Cache
Iface T // 接口
Cache Cache // 接口存储器
}

// IsNil 是否为空
func (f *Face[T]) IsNil() bool {
return Iface2Cache[T](f.Iface) == NilCache || f.Cache == NilCache
}

// FaceAny any face
type FaceAny = Face[any]

// MakeFaceT 创建Face,不使用Cache
// MakeFaceT 创建面(Face),接口存储器重解释接口与接口类型相同
func MakeFaceT[T any](iface T) Face[T] {
return Face[T]{
Iface: iface,
Cache: Iface2Cache[T](iface),
}
}

// MakeFaceAny 创建FaceAny,使用Cache,不使用接口
func MakeFaceAny[C any](iface C) FaceAny {
return Face[any]{
Iface: iface,
Cache: Iface2Cache[C](iface),
}
}

// MakeFaceTC 创建Face,使用Cache,传入接口与Cache
// MakeFaceTC 创建面(Face),接口存储器重解释接口与接口类型可以不同
func MakeFaceTC[T, C any](iface T, cache C) Face[T] {
if Iface2Cache(iface)[1] != Iface2Cache(cache)[1] {
exception.Panicf("%w: incorrect face pointer", exception.ErrCore)
Expand All @@ -65,7 +65,7 @@ func MakeFaceTC[T, C any](iface T, cache C) Face[T] {
}
}

// MakeFaceTReflectC 创建Face,使用Cache,自动反射Cache类型
// MakeFaceTReflectC 创建面(Face),自动反射获取接口存储器
func MakeFaceTReflectC[T, C any](iface T) Face[T] {
return Face[T]{
Iface: iface,
Expand Down

0 comments on commit fdde291

Please sign in to comment.