From 4c683c29b7417b7f14a8baf7d1dfce98c2d56f32 Mon Sep 17 00:00:00 2001 From: Jonathan Bluett-Duncan Date: Sun, 14 Apr 2024 13:54:10 +0100 Subject: [PATCH] unit: use more efficient sort routine --- unit/unittype.go | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/unit/unittype.go b/unit/unittype.go index 60c5f6d1..b90bbafd 100644 --- a/unit/unittype.go +++ b/unit/unittype.go @@ -6,8 +6,9 @@ package unit import ( "bytes" + "cmp" "fmt" - "sort" + "slices" "sync" "unicode/utf8" ) @@ -198,13 +199,19 @@ func (d Dimensions) String() string { // Map iterates randomly, but print should be in a fixed order. Can't use // dimension number, because for user-defined dimension that number may // not be fixed from run to run. - atoms := make(unitPrinters, 0, len(d)) + atoms := make([]atom, 0, len(d)) for dimension, power := range d { if power != 0 { atoms = append(atoms, atom{dimension, power}) } } - sort.Sort(atoms) + slices.SortFunc(atoms, func(a, b atom) int { + // Order first by positive powers, then by name. + if a.pow*b.pow < 0 { + return cmp.Compare(0, a.pow) + } + return cmp.Compare(a.String(), b.String()) + }) var b bytes.Buffer for i, a := range atoms { if i > 0 { @@ -224,24 +231,6 @@ type atom struct { pow int } -type unitPrinters []atom - -func (u unitPrinters) Len() int { - return len(u) -} - -func (u unitPrinters) Less(i, j int) bool { - // Order first by positive powers, then by name. - if u[i].pow*u[j].pow < 0 { - return u[i].pow > 0 - } - return u[i].String() < u[j].String() -} - -func (u unitPrinters) Swap(i, j int) { - u[i], u[j] = u[j], u[i] -} - // Unit represents a dimensional value. The dimensions will typically be in SI // units, but can also include dimensions created with NewDimension. The Unit type // is most useful for ensuring dimensional consistency when manipulating types