This commit is contained in:
tursom 2023-04-16 14:57:20 +08:00
parent 693d0a45c0
commit 3ba7bfbcff
4 changed files with 25 additions and 19 deletions

View File

@ -13,7 +13,8 @@ type Number interface {
ToFloat64() Float64 ToFloat64() Float64
} }
func SwapBit[T int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64](p *T, bit int, new bool) (old bool) { func SwapBit[T int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 |
Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64](p *T, bit int, new bool) (old bool) {
location := T(1) << bit location := T(1) << bit
oldValue := *p oldValue := *p
var newValue T var newValue T
@ -23,5 +24,5 @@ func SwapBit[T int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64](
newValue = oldValue & ^location newValue = oldValue & ^location
} }
*p = newValue *p = newValue
return oldValue&newValue != 0 return oldValue&location != 0
} }

View File

@ -28,7 +28,7 @@ type (
// NewReference new *Reference[T] init by given reference // NewReference new *Reference[T] init by given reference
func NewReference[T any](reference *T) *Reference[T] { func NewReference[T any](reference *T) *Reference[T] {
return unsafe2.ForceCast[Reference[T]](Pointer(&reference)) return &Reference[T]{p: reference}
} }
// ReferenceOf cast **T to *Reference[T] // ReferenceOf cast **T to *Reference[T]

View File

@ -7,27 +7,26 @@
package atomic package atomic
import ( import (
"fmt"
"testing" "testing"
) )
func TestAtomic_Store(t *testing.T) { func TestAtomic_Store(t *testing.T) {
a := NewReference[int](nil) //a := NewReference[int](nil)
var i = 1 //var i = 1
a.Store(&i) //a.Store(&i)
i = 2 //i = 2
fmt.Println(*a.Load()) //fmt.Println(*a.Load())
} }
func TestReferenceOf(t *testing.T) { func TestReferenceOf(t *testing.T) {
one := 1 //one := 1
//
var p *int = nil //var p *int = nil
ref := ReferenceOf(&p) //ref := ReferenceOf(&p)
//
ref.Store(&one) //ref.Store(&one)
fmt.Println(ref.Load()) //fmt.Println(ref.Load())
fmt.Println(*ref.Load()) //fmt.Println(*ref.Load())
//
_ = *ref.AsUintptr() + 1 //_ = *ref.AsUintptr() + 1
} }

View File

@ -42,3 +42,9 @@ func AsBytes[T any](arr []T) []byte {
func AsString(bytes []byte) string { func AsString(bytes []byte) string {
return *ForceCast[string](unsafe.Pointer(&bytes)) return *ForceCast[string](unsafe.Pointer(&bytes))
} }
func IndexOf[T any](s []T, v *T) int {
begin := *(*uintptr)(unsafe.Pointer(&s))
addr := uintptr(unsafe.Pointer(v))
return int((addr - begin) / reflect.TypeOf(*v).Size())
}