github.com/zhongdalu/gf@v1.0.0/g/container/gtype/float64.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gtype 8 9 import ( 10 "math" 11 "sync/atomic" 12 "unsafe" 13 ) 14 15 type Float64 struct { 16 value uint64 17 } 18 19 // NewFloat64 returns a concurrent-safe object for float64 type, 20 // with given initial value <value>. 21 func NewFloat64(value ...float64) *Float64 { 22 if len(value) > 0 { 23 return &Float64{ 24 value: math.Float64bits(value[0]), 25 } 26 } 27 return &Float64{} 28 } 29 30 // Clone clones and returns a new concurrent-safe object for float64 type. 31 func (v *Float64) Clone() *Float64 { 32 return NewFloat64(v.Val()) 33 } 34 35 // Set atomically stores <value> into t.value and returns the previous value of t.value. 36 func (v *Float64) Set(value float64) (old float64) { 37 return math.Float64frombits(atomic.SwapUint64(&v.value, math.Float64bits(value))) 38 } 39 40 // Val atomically loads t.value. 41 func (v *Float64) Val() float64 { 42 return math.Float64frombits(atomic.LoadUint64(&v.value)) 43 } 44 45 // Add atomically adds <delta> to t.value and returns the new value. 46 func (v *Float64) Add(delta float64) (new float64) { 47 for { 48 old := math.Float64frombits(v.value) 49 new = old + delta 50 if atomic.CompareAndSwapUint64( 51 (*uint64)(unsafe.Pointer(&v.value)), 52 math.Float64bits(old), 53 math.Float64bits(new), 54 ) { 55 break 56 } 57 } 58 return 59 } 60 61 // Cas executes the compare-and-swap operation for value. 62 func (v *Float64) Cas(old, new float64) bool { 63 return atomic.CompareAndSwapUint64(&v.value, uint64(old), uint64(new)) 64 }