1// Copyright (c) 2020 Uber Technologies, Inc.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21package atomic
22
23import (
24	"math"
25	"strconv"
26)
27
28//go:generate bin/gen-atomicwrapper -name=Float64 -type=float64 -wrapped=Uint64 -pack=math.Float64bits -unpack=math.Float64frombits -swap -json -imports math -file=float64.go
29
30// Add atomically adds to the wrapped float64 and returns the new value.
31func (f *Float64) Add(delta float64) float64 {
32	for {
33		old := f.Load()
34		new := old + delta
35		if f.CAS(old, new) {
36			return new
37		}
38	}
39}
40
41// Sub atomically subtracts from the wrapped float64 and returns the new value.
42func (f *Float64) Sub(delta float64) float64 {
43	return f.Add(-delta)
44}
45
46// CAS is an atomic compare-and-swap for float64 values.
47//
48// Note: CAS handles NaN incorrectly. NaN != NaN using Go's inbuilt operators
49// but CAS allows a stored NaN to compare equal to a passed in NaN.
50// This avoids typical CAS loops from blocking forever, e.g.,
51//
52//   for {
53//     old := atom.Load()
54//     new = f(old)
55//     if atom.CAS(old, new) {
56//       break
57//     }
58//   }
59//
60// If CAS did not match NaN to match, then the above would loop forever.
61func (f *Float64) CAS(old, new float64) (swapped bool) {
62	return f.v.CAS(math.Float64bits(old), math.Float64bits(new))
63}
64
65// String encodes the wrapped value as a string.
66func (f *Float64) String() string {
67	// 'g' is the behavior for floats with %v.
68	return strconv.FormatFloat(f.Load(), 'g', -1, 64)
69}
70