summaryrefslogtreecommitdiff
path: root/lib/containers/ordered.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2023-02-12 02:44:35 -0700
committerLuke Shumaker <lukeshu@lukeshu.com>2023-02-12 02:44:35 -0700
commit128e4d9aa876e14a1203ce98bfaa7ad399ad97c7 (patch)
tree039c3c549414c21b15d58c3d695ee87c3feb1402 /lib/containers/ordered.go
parent53d7fbb73869eb5defa1ca5c52b26abd346b13b9 (diff)
parent696a7d192e5eefa53230168a4b200ec0560c8a10 (diff)
Merge branch 'lukeshu/containers'
Diffstat (limited to 'lib/containers/ordered.go')
-rw-r--r--lib/containers/ordered.go33
1 files changed, 28 insertions, 5 deletions
diff --git a/lib/containers/ordered.go b/lib/containers/ordered.go
index d918149..1ebc17e 100644
--- a/lib/containers/ordered.go
+++ b/lib/containers/ordered.go
@@ -1,4 +1,4 @@
-// Copyright (C) 2022 Luke Shumaker <lukeshu@lukeshu.com>
+// Copyright (C) 2022-2023 Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later
@@ -9,16 +9,38 @@ import (
)
type _Ordered[T any] interface {
- Cmp(T) int
+ Compare(T) int
}
+// An Ordered[T] is a type that has a
+//
+// func (a T) Compare(b T) int
+//
+// method that returns a value <1 if a is "less than" b, >1 if a is
+// "greater than" b, or 0 if a is "equal to" b.
+//
+// You can conceptualize as subtraction:
+//
+// func (a T) Compare(b T) int {
+// return a - b
+// }
+//
+// Be careful to avoid integer overflow if actually implementing it as
+// subtraction.
type Ordered[T _Ordered[T]] _Ordered[T]
+// NativeOrdered takes a type that is natively-ordered (integer types,
+// float types, and string types), and wraps them such that they
+// implement the Ordered interface.
type NativeOrdered[T constraints.Ordered] struct {
Val T
}
-func NativeCmp[T constraints.Ordered](a, b T) int {
+// NativeCompare[T] implements the Ordered[T] Compare operation for
+// natively-ordered (integer types, float types, and string types).
+// While this operation be conceptualized as subtration,
+// NativeCompare[T] is careful to avoid integer overflow.
+func NativeCompare[T constraints.Ordered](a, b T) int {
switch {
case a < b:
return -1
@@ -29,8 +51,9 @@ func NativeCmp[T constraints.Ordered](a, b T) int {
}
}
-func (a NativeOrdered[T]) Cmp(b NativeOrdered[T]) int {
- return NativeCmp(a.Val, b.Val)
+// Compare implements Ordered[T].
+func (a NativeOrdered[T]) Compare(b NativeOrdered[T]) int {
+ return NativeCompare(a.Val, b.Val)
}
var _ Ordered[NativeOrdered[int]] = NativeOrdered[int]{}