github.com/blend/go-sdk@v1.20220411.3/expvar/float64.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package expvar
     9  
    10  import (
    11  	"math"
    12  	"strconv"
    13  	"sync/atomic"
    14  )
    15  
    16  // Assert that `Float64` implements `Var`.
    17  var (
    18  	_ Var = (*Float64)(nil)
    19  )
    20  
    21  // Float64 is a 64-bit float variable that satisfies the Var interface.
    22  type Float64 struct {
    23  	f uint64
    24  }
    25  
    26  // Value returns the underlying float64 value.
    27  func (v *Float64) Value() float64 {
    28  	return math.Float64frombits(atomic.LoadUint64(&v.f))
    29  }
    30  
    31  // String satisfies `Var`.
    32  func (v *Float64) String() string {
    33  	return strconv.FormatFloat(
    34  		math.Float64frombits(atomic.LoadUint64(&v.f)), 'g', -1, 64)
    35  }
    36  
    37  // Add adds delta to v.
    38  func (v *Float64) Add(delta float64) {
    39  	for {
    40  		cur := atomic.LoadUint64(&v.f)
    41  		curVal := math.Float64frombits(cur)
    42  		nxtVal := curVal + delta
    43  		nxt := math.Float64bits(nxtVal)
    44  		if atomic.CompareAndSwapUint64(&v.f, cur, nxt) {
    45  			return
    46  		}
    47  	}
    48  }
    49  
    50  // Set sets v to value.
    51  func (v *Float64) Set(value float64) {
    52  	atomic.StoreUint64(&v.f, math.Float64bits(value))
    53  }