aboutsummaryrefslogtreecommitdiffstats
path: root/pressure.go
blob: 74f035d5d4ad412c25ddf4568e816d47b9cb4330 (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
55
56
57
58
package main

import (
	"errors"
	"fmt"
)

type pressureUnit float32

const (
	pascal              pressureUnit = 1
	kilopascal          pressureUnit = 1_000
	bar                 pressureUnit = 100_000
	poundsPerSquareInch pressureUnit = 6_894.757
)

// pressureUnitStrings returns a slice of strings, each representing a
// pressureUnit.
// This is necessary because giu.Combo only works with strings.
func pressureUnitStrings() []string {
	return []string{"Pa", "kPa", "bar", "psi"}
}

const (
	defaultPressureUnit pressureUnit = kilopascal
	// Used to index pressureUnitStrings
	defaultPressureUnitIndex int32 = 1 // kPa
)

func pressureUnitFromString(s string) (pressureUnit, error) {
	// Each case corresponds to a value in pressureUnitStrings
	switch s {
	case "Pa":
		return pascal, nil
	case "kPa":
		return kilopascal, nil
	case "bar":
		return bar, nil
	case "psi":
		return poundsPerSquareInch, nil
	default:
		return *new(pressureUnit), errors.New(fmt.Sprintf("invalid pressureUnit: '%s'", s))
	}
}

type pressure struct {
	val  float32
	unit pressureUnit
}

func newPressure() pressure {
	return pressure{100, defaultPressureUnit}
}

func (p pressure) asUnit(u pressureUnit) float32 {
	pa := p.val * float32(p.unit) // Convert to pascals.
	return pa / float32(u)        // Convert to desired unit.
}