github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/internal/math.go (about)

     1  package internal
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/jxskiss/gopkg/v2/internal/linkname"
     7  )
     8  
     9  // AddJitter adds random jitter to a duration.
    10  //
    11  // It adds or subtracts time from the duration within a given jitter fraction.
    12  // For example for 10s and jitter 0.1, it returns a duration within [9s, 11s).
    13  func AddJitter(duration time.Duration, jitter float64) time.Duration {
    14  	// See math/rand/v2.Float64.
    15  	randf64 := float64(linkname.Runtime_fastrand64()<<11>>11) / (1 << 53)
    16  	x := jitter * (randf64*2 - 1)
    17  	return time.Duration(float64(duration) * (1 + x))
    18  }
    19  
    20  func NextPowerOfTwo(x uint) uint {
    21  	if x <= 1 {
    22  		return 1
    23  	}
    24  
    25  	x--
    26  	x |= x >> 1
    27  	x |= x >> 2
    28  	x |= x >> 4
    29  	x |= x >> 8
    30  	x |= x >> 16
    31  	x |= x >> 32
    32  
    33  	return x + 1
    34  }