-
Notifications
You must be signed in to change notification settings - Fork 1
/
math.go
executable file
·97 lines (88 loc) · 2.44 KB
/
math.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package bitty
import (
"fmt"
)
// AddUnits takes two units with valid symbols, sums them, then returns a new unit
// AddUnits will always default to the left unit's symbol and exponent
func AddUnits(lu, ru Unit) (Unit, error) {
var (
newExponent int
newSymbol UnitSymbol
newSize float64
lok, rok bool
)
// validate that the units can be added to each other
lok, rok = ValidateSymbols(lu.Symbol(), ru.Symbol())
if !lok && !rok {
return nil, fmt.Errorf("unable to add units with invalid symbols together: %s + %s", lu.Symbol(), ru.Symbol())
}
if lok && !rok {
return lu, fmt.Errorf("unable to add unit with invalid symbol: %s", ru.Symbol())
}
if rok && !lok {
return ru, fmt.Errorf("unable to add unit with invalid symbol: %s", lu.Symbol())
}
leftByte, rightByte := lu.ByteSize(), ru.ByteSize()
totalByte := leftByte + rightByte
newSymbol = lu.Symbol()
newExponent = lu.Exponent()
newSize = BytesToUnitSymbolSize(lu.Standard(), newSymbol, totalByte)
var u Unit
switch lu.Standard() {
case IEC:
u = &IECUnit{
size: newSize,
symbol: newSymbol,
exponent: newExponent,
}
case SI:
u = &SIUnit{
size: newSize,
symbol: newSymbol,
exponent: newExponent,
}
}
return u, nil
}
// SubtractUnits takes two units with valid symbols, subtracts them, then returns a new unit
// SubtractUnits will always default to the left unit's symbol and exponent
func SubtractUnits(lu, ru Unit) (Unit, error) {
var (
newExponent int
newSymbol UnitSymbol
newSize float64
lok, rok bool
)
// validate that the units can be added to each other
lok, rok = ValidateSymbols(lu.Symbol(), ru.Symbol())
if !lok && !rok {
return nil, fmt.Errorf("unable to add units with invalid symbols together: %s + %s", lu.Symbol(), ru.Symbol())
}
if lok && !rok {
return lu, fmt.Errorf("unable to subtract unit with invalid symbol: %s", ru.Symbol())
}
if rok && !lok {
return ru, fmt.Errorf("unable to subtract unit with invalid symbol: %s", lu.Symbol())
}
leftByte, rightByte := lu.ByteSize(), ru.ByteSize()
totalByte := leftByte - rightByte
newSymbol = lu.Symbol()
newExponent = lu.Exponent()
newSize = BytesToUnitSymbolSize(lu.Standard(), newSymbol, totalByte)
var u Unit
switch lu.Standard() {
case IEC:
u = &IECUnit{
size: newSize,
symbol: newSymbol,
exponent: newExponent,
}
case SI:
u = &SIUnit{
size: newSize,
symbol: newSymbol,
exponent: newExponent,
}
}
return u, nil
}