github.com/zhongdalu/gf@v1.0.0/g/container/gtype/float32.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 Float32 struct { 16 value uint32 17 } 18 19 // NewFloat32 returns a concurrent-safe object for float32 type, 20 // with given initial value <value>. 21 func NewFloat32(value ...float32) *Float32 { 22 if len(value) > 0 { 23 return &Float32{ 24 value: math.Float32bits(value[0]), 25 } 26 } 27 return &Float32{} 28 } 29 30 // Clone clones and returns a new concurrent-safe object for float32 type. 31 func (v *Float32) Clone() *Float32 { 32 return NewFloat32(v.Val()) 33 } 34 35 // Set atomically stores <value> into t.value and returns the previous value of t.value. 36 func (v *Float32) Set(value float32) (old float32) { 37 return math.Float32frombits(atomic.SwapUint32(&v.value, math.Float32bits(value))) 38 } 39 40 // Val atomically loads t.value. 41 func (v *Float32) Val() float32 { 42 return math.Float32frombits(atomic.LoadUint32(&v.value)) 43 } 44 45 // Add atomically adds <delta> to t.value and returns the new value. 46 func (v *Float32) Add(delta float32) (new float32) { 47 for { 48 old := math.Float32frombits(v.value) 49 new = old + delta 50 if atomic.CompareAndSwapUint32( 51 (*uint32)(unsafe.Pointer(&v.value)), 52 math.Float32bits(old), 53 math.Float32bits(new), 54 ) { 55 break 56 } 57 } 58 return 59 } 60 61 // Cas executes the compare-and-swap operation for value. 62 func (v *Float32) Cas(old, new float32) bool { 63 return atomic.CompareAndSwapUint32(&v.value, uint32(old), uint32(new)) 64 }