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

Signed-off-by: Alexander Chuprov <a.chuprov@yadro.com>
This commit is contained in:
Alexander Chuprov 2025-02-17 11:49:39 +03:00
parent 51b68055ee
commit 523626635e
Signed by: achuprov
GPG key ID: 2D916FFD803B0EDD
2 changed files with 23 additions and 0 deletions

View file

@ -3,6 +3,7 @@ package cid
import (
"crypto/sha256"
"fmt"
"strings"
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/refs"
"github.com/mr-tron/base58"
@ -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 id1 == id2, -1 if id1 < id2, and +1 if id1 > id2.
func (id ID) Cmp(id2 ID) int {
return strings.Compare(id.EncodeToString(), id2.EncodeToString())
}

View file

@ -3,6 +3,8 @@ package cid_test
import (
"crypto/rand"
"crypto/sha256"
"slices"
"strings"
"testing"
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/refs"
@ -106,3 +108,17 @@ 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++ {
require.NotEqual(t, strings.Compare(arr[i-1].EncodeToString(), arr[i].EncodeToString()), 1, "array is not sorted correctly")
}
}