[#294] object: Implement Cmp() function for ID struct
Signed-off-by: Alexander Chuprov <a.chuprov@yadro.com>
This commit is contained in:
parent
7bdc78f2b5
commit
58c1602cff
2 changed files with 24 additions and 0 deletions
|
@ -1,6 +1,7 @@
|
|||
package oid
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
|
@ -167,3 +168,9 @@ func (id *ID) UnmarshalJSON(data []byte) error {
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cmp returns an integer comparing two base58 encoded object ID lexicographically.
|
||||
// The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
|
||||
func (id ID) Cmp(id2 ID) int {
|
||||
return bytes.Compare([]byte(id.EncodeToString()), []byte(id2.EncodeToString()))
|
||||
}
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
package oid
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"slices"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
|
@ -180,3 +182,18 @@ func TestID_Encode(t *testing.T) {
|
|||
require.Equal(t, emptyID, id.EncodeToString())
|
||||
})
|
||||
}
|
||||
|
||||
func TestID__Cmp(t *testing.T) {
|
||||
id1 := randID(t)
|
||||
id2 := randID(t)
|
||||
id3 := randID(t)
|
||||
|
||||
arr := []ID{id1, id2, id3}
|
||||
|
||||
slices.SortFunc(arr, ID.Cmp)
|
||||
for i := 1; i < len(arr); i++ {
|
||||
if bytes.Compare([]byte(arr[i-1].EncodeToString()), []byte(arr[i].EncodeToString())) > 0 {
|
||||
t.Fatalf("arrays are not sorted correctly")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue