Fast, generic, concurrency-safe constructs for ordering anything.
The package compare
aims to bring a consistent implementation of a Less
function for integers, floats and strings.
With type parameters introduced in Go 1.18, a (currently experimental) package for the standard library has been proposed called constraints, which defines the following type constraint:
// Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >.
// If future releases of Go add new ordered types, this constraint will be modified to include them.
type Ordered interface {
Integer | Float | ~string
}
However, to actually order elements whose underlying type is constraints.Ordered
, one must not rely upon the <
operator alone. The standard library sort
interface describes why:
// Note that floating-point comparison (the < operator on float32 or float64 values)
// is not a transitive ordering when not-a-number (NaN) values are involved.
// See Float64Slice.Less for a correct implementation for floating-point values.
This is what compare
solves.
This package provides a consistent interface for ordering these types, with corresponding implementations of LessFunc. To achieve this three type constraints have been defined:
- compare.SimpleOrdered
Use this whenever you only care ordering integers or strings. The LessFunc defined for this type is just the<
operator. - compare.FloatOrdered
Use this whenever you only care about ordering floating point types. The LessFunc defined for this type uses anIsNaN
check to ensure a transitive ordering. - compare.Ordered
The union of the two above, and also a copy ofconstraints.Ordered
. The LessFunc defined for this type uses anIsNaN
check to ensure a transitive ordering. Use this for whenever you're usingconstraints.Ordered
and you don't want to use the more constrainedSimpleOrdered
orFloatOrdered
.
Along with the associated LessFuncs (respectively):
LessSimple
LessFloat
Less
See chansort README.md.
See atomicbit README.md.