-
Notifications
You must be signed in to change notification settings - Fork 1
/
addsub128.go
57 lines (50 loc) · 983 Bytes
/
addsub128.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package fixed
import "math/bits"
func add(x, y Fixed) Fixed {
xs, ys := x.hi&signMask, y.hi&signMask
if xs != ys {
if ys != 0 {
// x + -y => x - y
return usub(x, y.abs())
}
// -x + y => y - x
return usub(y, x.abs())
}
return uadd(x.abs(), y.abs()).setSignAs(x)
}
func addx(x Fixed, y ...Fixed) Fixed {
for _, a := range y {
x = add(x, a)
}
return x
}
func sub(x, y Fixed) Fixed {
return add(x, y.neg())
}
func subx(x Fixed, y ...Fixed) Fixed {
for _, a := range y {
x = sub(x, a)
}
return x
}
func uadd(x, y Fixed) Fixed {
r, c := Fixed{}, uint64(0)
r.lo, c = bits.Add64(x.lo, y.lo, c)
r.hi, c = bits.Add64(x.hi, y.hi, c)
if c|r.hi&signMask != 0 {
panic(ErrOverflow)
}
return r
}
func usub(x, y Fixed) (r Fixed) {
c := uint64(0)
if x.less(y) {
r.lo, c = bits.Sub64(y.lo, x.lo, c)
r.hi, _ = bits.Sub64(y.hi, x.hi, c)
r.hi |= signMask
return
}
r.lo, c = bits.Sub64(x.lo, y.lo, c)
r.hi, _ = bits.Sub64(x.hi, y.hi, c)
return r
}