]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmp/cmp.go
cmp: new package
[gostls13.git] / src / cmp / cmp.go
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
5 // Package cmp provides types and functions related to comparing
6 // ordered values.
7 package cmp
8
9 // Ordered is a constraint that permits any ordered type: any type
10 // that supports the operators < <= >= >.
11 // If future releases of Go add new ordered types,
12 // this constraint will be modified to include them.
13 type Ordered interface {
14         ~int | ~int8 | ~int16 | ~int32 | ~int64 |
15                 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
16                 ~float32 | ~float64 |
17                 ~string
18 }
19
20 // Less reports whether x is less than y.
21 // For floating-point types, a NaN is considered less than any non-NaN,
22 // and -0.0 is not less than (is equal to) 0.0.
23 func Less[T Ordered](x, y T) bool {
24         return (isNaN(x) && !isNaN(y)) || x < y
25 }
26
27 // Compare returns
28 //
29 //      -1 if x is less than y,
30 //       0 if x equals y,
31 //      +1 if x is greater than y.
32 //
33 // For floating-point types, a NaN is considered less than any non-NaN,
34 // a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.
35 func Compare[T Ordered](x, y T) int {
36         xNaN := isNaN(x)
37         yNaN := isNaN(y)
38         if xNaN && yNaN {
39                 return 0
40         }
41         if xNaN || x < y {
42                 return -1
43         }
44         if yNaN || x > y {
45                 return +1
46         }
47         return 0
48 }
49
50 // isNaN reports whether x is a NaN without requiring the math package.
51 // This will always return false if T is not floating-point.
52 func isNaN[T Ordered](x T) bool {
53         return x != x
54 }