From 148a341b6fc1451a4d673d1ffb704ce458ab282c Mon Sep 17 00:00:00 2001 From: Alexander Chuprov Date: Mon, 17 Feb 2025 11:49:10 +0300 Subject: [PATCH] [#294] object: Implement Cmp() function for ID struct Signed-off-by: Alexander Chuprov --- object/id/id.go | 7 +++++++ object/id/id_test.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/object/id/id.go b/object/id/id.go index d1dfe80..29e6a3a 100644 --- a/object/id/id.go +++ b/object/id/id.go @@ -4,6 +4,7 @@ import ( "crypto/ecdsa" "crypto/sha256" "fmt" + "strings" "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/refs" frostfscrypto "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/crypto" @@ -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 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()) +} diff --git a/object/id/id_test.go b/object/id/id_test.go index e1a2e26..9df6186 100644 --- a/object/id/id_test.go +++ b/object/id/id_test.go @@ -3,7 +3,9 @@ package oid import ( "crypto/rand" "crypto/sha256" + "slices" "strconv" + "strings" "testing" "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/refs" @@ -180,3 +182,16 @@ 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++ { + require.NotEqual(t, strings.Compare(arr[i-1].EncodeToString(), arr[i].EncodeToString()), 1, "array is not sorted correctly") + } +}