diff --git a/internal/runtimex/runtime_go_1.22.go b/internal/runtimex/runtime_go_1.22.go new file mode 100644 index 00000000..c7b4f206 --- /dev/null +++ b/internal/runtimex/runtime_go_1.22.go @@ -0,0 +1,25 @@ +// Copyright 2024 ByteDance Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build go1.22 +// +build go1.22 + +package runtimex + +import ( + _ "unsafe" // for linkname +) + +//go:linkname Fastrand runtime.cheaprand +func Fastrand() uint32 diff --git a/internal/runtimex/runtime.go b/internal/runtimex/runtime_pre_go_1.22.go similarity index 94% rename from internal/runtimex/runtime.go rename to internal/runtimex/runtime_pre_go_1.22.go index ab9ae2c4..2acb430d 100644 --- a/internal/runtimex/runtime.go +++ b/internal/runtimex/runtime_pre_go_1.22.go @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !go1.22 +// +build !go1.22 + package runtimex import ( diff --git a/internal/runtimex/runtime_test.go b/internal/runtimex/runtime_test.go new file mode 100644 index 00000000..61d43751 --- /dev/null +++ b/internal/runtimex/runtime_test.go @@ -0,0 +1,38 @@ +// Copyright 2024 ByteDance Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package runtimex + +import "testing" + +func TestFastrand(t *testing.T) { + var isRandom bool + for i := 0; i < 3; i++ { + x := Fastrand() + y := Fastrand() + if x != y { + isRandom = true + break + } + } + if !isRandom { + t.Fatal("Invalid fastrand results") + } +} + +func BenchmarkFastrand(b *testing.B) { + for i := 0; i < b.N; i++ { + Fastrand() + } +}