cmp.go 976 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package slices
  5. import "golang.org/x/exp/constraints"
  6. // min is a version of the predeclared function from the Go 1.21 release.
  7. func min[T constraints.Ordered](a, b T) T {
  8. if a < b || isNaN(a) {
  9. return a
  10. }
  11. return b
  12. }
  13. // max is a version of the predeclared function from the Go 1.21 release.
  14. func max[T constraints.Ordered](a, b T) T {
  15. if a > b || isNaN(a) {
  16. return a
  17. }
  18. return b
  19. }
  20. // cmpLess is a copy of cmp.Less from the Go 1.21 release.
  21. func cmpLess[T constraints.Ordered](x, y T) bool {
  22. return (isNaN(x) && !isNaN(y)) || x < y
  23. }
  24. // cmpCompare is a copy of cmp.Compare from the Go 1.21 release.
  25. func cmpCompare[T constraints.Ordered](x, y T) int {
  26. xNaN := isNaN(x)
  27. yNaN := isNaN(y)
  28. if xNaN && yNaN {
  29. return 0
  30. }
  31. if xNaN || x < y {
  32. return -1
  33. }
  34. if yNaN || x > y {
  35. return +1
  36. }
  37. return 0
  38. }