aboutsummaryrefslogtreecommitdiffstats
path: root/volume
diff options
context:
space:
mode:
authorsam-anthony <samanthony6@protonmail.com>2022-03-31 20:27:39 -0230
committersam-anthony <samanthony6@protonmail.com>2022-03-31 20:27:39 -0230
commit6634b3ff6bcdffbab38a049460ae6ea3cd68944f (patch)
tree4cbcb7829060883afe074854a2ffc82b4ab2e31b /volume
parentcc0d171c5cd1057693960b7f63aee29e7f70ee8e (diff)
downloadvolute-6634b3ff6bcdffbab38a049460ae6ea3cd68944f.zip
refactor and compressor map image widget
Diffstat (limited to 'volume')
-rw-r--r--volume/volume.go54
1 files changed, 54 insertions, 0 deletions
diff --git a/volume/volume.go b/volume/volume.go
new file mode 100644
index 0000000..020d1a6
--- /dev/null
+++ b/volume/volume.go
@@ -0,0 +1,54 @@
+package volume
+
+import (
+ "errors"
+ "fmt"
+)
+
+type unit float32
+
+const (
+ CubicCentimetre unit = 1
+ Litre unit = 1_000
+ CubicMetre unit = 1_000_000
+ CubicInch unit = 16.38706
+)
+
+// UnitStrings returns a slice of strings, each representing a
+// unit.
+// This is necessary because giu.Combo only works with strings.
+func UnitStrings() []string {
+ return []string{"cc", "L", "m³", "in³"}
+}
+
+const (
+ DefaultUnit unit = CubicCentimetre
+ // DefaulUnitIndex is used to index UnitStrings().
+ DefaultUnitIndex int32 = 0 // cc
+)
+
+func UnitFromString(s string) (unit, error) {
+ // Each case corresponds to a value in UnitStrings().
+ switch s {
+ case "cc":
+ return CubicCentimetre, nil
+ case "L":
+ return Litre, nil
+ case "m³":
+ return CubicMetre, nil
+ case "in³":
+ return CubicInch, nil
+ default:
+ return *new(unit), errors.New(fmt.Sprintf("invalid volume unit: '%s'", s))
+ }
+}
+
+type Volume struct {
+ Val float32
+ Unit unit
+}
+
+func (v Volume) AsUnit(u unit) float32 {
+ cc := v.Val * float32(v.Unit) // Convert to cubic centimetres.
+ return cc / float32(u) // Convert to desired unit.
+}