github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/helper/math/math_helper.go (about)

     1  // Copyright 2021 iLogtail Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package math
    16  
    17  import (
    18  	"math"
    19  	"runtime"
    20  	"sync/atomic"
    21  	"unsafe"
    22  
    23  	"github.com/alibaba/ilogtail/pkg/constraints"
    24  )
    25  
    26  func Max[T constraints.IntUintFloat](x T, y T) T {
    27  	if x > y {
    28  		return x
    29  	}
    30  	return y
    31  }
    32  
    33  func Min[T constraints.IntUintFloat](x T, y T) T {
    34  	if x < y {
    35  		return x
    36  	}
    37  	return y
    38  }
    39  
    40  func AtomicAddFloat64(dst *float64, n float64) {
    41  	for {
    42  		i := 0
    43  		/* #nosec G103 */
    44  		bits := atomic.LoadUint64((*uint64)(unsafe.Pointer(dst)))
    45  		now := math.Float64bits(math.Float64frombits(bits) + n)
    46  		/* #nosec G103 */
    47  		if atomic.CompareAndSwapUint64((*uint64)(unsafe.Pointer(dst)), bits, now) {
    48  			return
    49  		}
    50  		i++
    51  		if i > 128 {
    52  			runtime.Gosched()
    53  			i = 0
    54  		}
    55  	}
    56  }
    57  
    58  func AtomicLoadFloat64(dst *float64) float64 {
    59  	/* #nosec G103 */
    60  	return math.Float64frombits(atomic.LoadUint64((*uint64)(unsafe.Pointer(dst))))
    61  }
    62  
    63  func AtomicStoreFloat64(dst *float64, n float64) {
    64  	/* #nosec G103 */
    65  	atomic.StoreUint64((*uint64)(unsafe.Pointer(dst)), math.Float64bits(n))
    66  }