1
0
mirror of https://github.com/fumiama/gofastTEA.git synced 2026-06-28 14:20:23 +08:00

optimize: drop linkname

This commit is contained in:
源文雨
2024-11-09 01:34:07 +09:00
parent 3a1a8fa624
commit 7d42c37612
4 changed files with 35 additions and 15 deletions

19
rand_1.21.go Normal file
View File

@@ -0,0 +1,19 @@
//go:build !go1.22
package tea
import (
_ "unsafe" // required by go:linkname
)
// randuint32 returns a lock free uint32 value.
//
// Too much legacy code has go:linkname references
// to runtime.fastrand and friends, so keep these around for now.
// Code should migrate to math/rand/v2.Uint64,
// which is just as fast, but that's only available in Go 1.22+.
// It would be reasonable to remove these in Go 1.24.
// Do not call these from package runtime.
//
//go:linkname randuint32 runtime.fastrand
func randuint32() uint32

11
rand_1.22.go Normal file
View File

@@ -0,0 +1,11 @@
//go:build go1.22
package tea
import (
"math/rand/v2"
)
func randuint32() uint32 {
return rand.Uint32()
}

5
tea.go
View File

@@ -4,15 +4,10 @@ package tea
import ( import (
"encoding/binary" "encoding/binary"
_ "unsafe" // required by go:linkname
) )
type TEA [4]uint32 type TEA [4]uint32
// randuint32 returns a lock free uint32 value.
//go:linkname randuint32 runtime.fastrand
func randuint32() uint32
//go:nosplit //go:nosplit
func NewTeaCipher(key []byte) (t TEA) { func NewTeaCipher(key []byte) (t TEA) {
if len(key) == 16 { if len(key) == 16 {

View File

@@ -1,6 +1,3 @@
//go:build ignore
// +build ignore
package tea package tea
import ( import (
@@ -8,8 +5,6 @@ import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"testing" "testing"
"github.com/Mrs4s/MiraiGo/utils"
) )
var testTEA = NewTeaCipher([]byte("0123456789ABCDEF")) var testTEA = NewTeaCipher([]byte("0123456789ABCDEF"))
@@ -32,7 +27,7 @@ var sampleData = func() [][3]string {
} }
for i := range out { for i := range out {
c, _ := hex.DecodeString(out[i][ENC]) c, _ := hex.DecodeString(out[i][ENC])
out[i][ENC] = utils.B2S(c) out[i][ENC] = string(c)
} }
return out return out
}() }()
@@ -40,13 +35,13 @@ var sampleData = func() [][3]string {
func TestTEA(t *testing.T) { func TestTEA(t *testing.T) {
// Self Testing // Self Testing
for _, sample := range sampleData { for _, sample := range sampleData {
tea := NewTeaCipher(utils.S2B(sample[KEY])) tea := NewTeaCipher([]byte(sample[KEY]))
dat := utils.B2S(tea.Decrypt(utils.S2B(sample[ENC]))) dat := string(tea.Decrypt([]byte(sample[ENC])))
if dat != sample[DAT] { if dat != sample[DAT] {
t.Fatalf("error decrypt %v %x", sample, dat) t.Fatalf("error decrypt %v %x", sample, dat)
} }
enc := utils.B2S(tea.Encrypt(utils.S2B(sample[DAT]))) enc := string(tea.Encrypt([]byte(sample[DAT])))
dat = utils.B2S(tea.Decrypt(utils.S2B(enc))) dat = string(tea.Decrypt([]byte(enc)))
if dat != sample[DAT] { if dat != sample[DAT] {
t.Fatal("error self test", sample) t.Fatal("error self test", sample)
} }