unit: generate the Dimless type
MODIFY
unit/generate_unit.go
unit/generate_unit.go
@@ -76,6 +76,12 @@ type Prefix struct {
var Units = []Unit{
// Base units.
+ {
+ DimensionName: "Dimless",
+ Receiver: "d",
+ TypeComment: "Dimless represents a dimensionless constant",
+ Dimensions: []Dimension{},
+ },
{
DimensionName: "Angle",
Receiver: "a",
@@ -442,7 +448,7 @@ import (
"errors"
"fmt"
"math"
- "unicode/utf8"
+ {{if .PrintString}}"unicode/utf8"{{end}}
)
// {{.TypeComment}}.
@@ -502,7 +508,7 @@ func ({{.Receiver}} {{.DimensionName}}) Format(fs fmt.State, c rune) {
case 'e', 'E', 'f', 'F', 'g', 'G':
p, pOk := fs.Precision()
w, wOk := fs.Width()
- const unit = " {{.PrintString}}"
+ {{if .PrintString}}const unit = " {{.PrintString}}"
switch {
case pOk && wOk:
fmt.Fprintf(fs, "%*.*"+string(c), pos(w-utf8.RuneCount([]byte(unit))), p, float64({{.Receiver}}))
@@ -515,7 +521,18 @@ func ({{.Receiver}} {{.DimensionName}}) Format(fs fmt.State, c rune) {
}
fmt.Fprint(fs, unit)
default:
- fmt.Fprintf(fs, "%%!%c(%T=%g {{.PrintString}})", c, {{.Receiver}}, float64({{.Receiver}}))
+ fmt.Fprintf(fs, "%%!%c(%T=%g {{.PrintString}})", c, {{.Receiver}}, float64({{.Receiver}})) {{else}} switch {
+ case pOk && wOk:
+ fmt.Fprintf(fs, "%*.*"+string(c), w, p, float64({{.Receiver}}))
+ case pOk:
+ fmt.Fprintf(fs, "%.*"+string(c), p, float64({{.Receiver}}))
+ case wOk:
+ fmt.Fprintf(fs, "%*"+string(c), w, float64({{.Receiver}}))
+ default:
+ fmt.Fprintf(fs, "%"+string(c), float64({{.Receiver}}))
+ }
+ default:
+ fmt.Fprintf(fs, "%%!%c(%T=%g)", c, {{.Receiver}}, float64({{.Receiver}})) {{end}}
}
}
`
@@ -596,13 +613,13 @@ func Test{{.DimensionName}}Format(t *testing.T) {
format string
want string
}{
- {1.23456789, "%v", "1.23456789 {{.PrintString}}"},
- {1.23456789, "%.1v", "1 {{.PrintString}}"},
- {1.23456789, "%20.1v", "{{$s := printf "1 %s" .PrintString}}{{printf "%20s" $s}}"},
- {1.23456789, "%20v", "{{$s := printf "1.23456789 %s" .PrintString}}{{printf "%20s" $s}}"},
- {1.23456789, "%1v", "1.23456789 {{.PrintString}}"},
+ {1.23456789, "%v", "1.23456789{{with .PrintString}} {{.}}{{end}}"},
+ {1.23456789, "%.1v", "1{{with .PrintString}} {{.}}{{end}}"},
+ {1.23456789, "%20.1v", "{{if .PrintString}}{{$s := printf "1 %s" .PrintString}}{{printf "%20s" $s}}{{else}}{{printf "%20s" "1"}}{{end}}"},
+ {1.23456789, "%20v", "{{if .PrintString}}{{$s := printf "1.23456789 %s" .PrintString}}{{printf "%20s" $s}}{{else}}{{printf "%20s" "1.23456789"}}{{end}}"},
+ {1.23456789, "%1v", "1.23456789{{with .PrintString}} {{.}}{{end}}"},
{1.23456789, "%#v", "unit.{{.DimensionName}}(1.23456789)"},
- {1.23456789, "%s", "%!s(unit.{{.DimensionName}}=1.23456789 {{.PrintString}})"},
+ {1.23456789, "%s", "%!s(unit.{{.DimensionName}}=1.23456789{{with .PrintString}} {{.}}{{end}})"},
} {
got := fmt.Sprintf(test.format, test.value)
if got != test.want {

unit: generate the Dimless type