[#294] container: Implement Cmp() functions for ID struct

Signed-off-by: Alexander Chuprov <a.chuprov@yadro.com>
This commit is contained in:
Alexander Chuprov 2025-02-13 19:33:04 +03:00
parent 6dd92d7f28
commit f9daa30be4
Signed by: achuprov
GPG key ID: 2D916FFD803B0EDD
2 changed files with 25 additions and 0 deletions

View file

@ -1,6 +1,7 @@
package cid
import (
"bytes"
"crypto/sha256"
"fmt"
@ -113,3 +114,9 @@ func (id *ID) DecodeString(s string) error {
func (id ID) String() string {
return id.EncodeToString()
}
// Cmp returns an integer comparing two base58 encoded container 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()))
}

View file

@ -1,8 +1,10 @@
package cid_test
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"slices"
"testing"
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/refs"
@ -106,3 +108,19 @@ func TestID_Encode(t *testing.T) {
require.Equal(t, emptyID, id.EncodeToString())
})
}
func TestID__Cmp(t *testing.T) {
var arr []cid.ID
for i := 0; i < 3; i++ {
checksum := randSHA256Checksum()
arr = append(arr, cidtest.IDWithChecksum(checksum))
}
slices.SortFunc(arr, cid.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")
}
}
}