unit: don't panic when multiplying dimless with dimensioned Uniter
MODIFY
unit/unit_test.go
unit/unit_test.go
@@ -159,6 +159,47 @@ func TestDimensionEquality(t *testing.T) {
}
}
+var operationTests = []struct {
+ recvOp func(Uniter) *Unit
+ param Uniter
+ want Uniter
+}{
+ {Dimless(1).Unit().Add, Dimless(2), Dimless(3)},
+ {Dimless(1).Unit().Mul, Dimless(2), Dimless(2)},
+ {Dimless(1).Unit().Mul, Length(2), Length(2)},
+ {Length(1).Unit().Mul, Dimless(2), Length(2)},
+ {Dimless(1).Unit().Div, Length(2), New(0.5, Dimensions{LengthDim: -1})},
+ {Length(1).Unit().Div, Dimless(2), Length(0.5)},
+}
+
+func TestOperations(t *testing.T) {
+ for i, test := range operationTests {
+ var got Uniter
+ if panics(func() { got = test.recvOp(test.param) }) {
+ t.Errorf("unexpected panic for test %d", i)
+ continue
+ }
+ if !DimensionsMatch(got, test.want) {
+ t.Errorf("dimension mismatch for test %d: got=%v want=%v", i, got.Unit(), test.want.Unit())
+ }
+ if got.Unit().Value() != test.want.Unit().Value() {
+ t.Errorf("value mismatch for test %d: got=%v want=%v", i, got.Unit().Value(), test.want.Unit().Value())
+ }
+ }
+}
+
+// panics returns true if the function panics.
+func panics(f func()) (b bool) {
+ defer func() {
+ err := recover()
+ if err != nil {
+ b = true
+ }
+ }()
+ f()
+ return
+}
+
type UnitStructer interface {
UnitStruct() *UnitStruct
}

MODIFY
unit/unittype.go
unit/unittype.go
@@ -167,7 +167,7 @@ var (
type Dimensions map[Dimension]int
func (d Dimensions) clone() Dimensions {
- if len(d) == 0 {
+ if d == nil {
return nil
}
c := make(Dimensions, len(d))

unit: don't panic when multiplying dimless with dimensioned Uniter