aboutsummaryrefslogtreecommitdiffstats
path: root/volume.go
blob: cb7098a74b8f9042c37944cadc57b493cc90ee9f (plain) (blame)
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
package main

import (
	"errors"
	"fmt"
)

type volumeUnit float32

const (
	cubicCentimetre volumeUnit = 1
	litre           volumeUnit = 1_000
	cubicMetre      volumeUnit = 1_000_000
	cubicInch       volumeUnit = 16.38706
)

// volumeUnitStrings returns a slice of strings, each representing a
// volumeUnit.
// This is necessary because giu.Combo only works with strings.
func volumeUnitStrings() []string {
	return []string{"cc", "L", "m³", "in³"}
}

const (
	defaultVolumeUnit volumeUnit = cubicCentimetre
	// Used to index volumeUnitStrings
	defaultVolumeUnitIndex int32 = 0 // cc
)

func volumeUnitFromString(s string) (volumeUnit, error) {
	// Each case corresponds to a value in volumeUnitStrings
	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(volumeUnit), errors.New(fmt.Sprintf("invalid volumeUnit: '%s'", s))
	}
}

type volume struct {
	val  float32
	unit volumeUnit
}

func (v volume) asUnit(u volumeUnit) float32 {
	cc := v.val * float32(v.unit) // Convert to cubic centimetres.
	return cc / float32(u)        // Convert to desired unit.
}