From 58c1602cffe1949d8a9e2ec33c91758f8bb23234 Mon Sep 17 00:00:00 2001 From: Alexander Chuprov Date: Thu, 13 Feb 2025 19:30:41 +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 | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/object/id/id.go b/object/id/id.go index d1dfe80..1f04678 100644 --- a/object/id/id.go +++ b/object/id/id.go @@ -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())) +} diff --git a/object/id/id_test.go b/object/id/id_test.go index e1a2e26..3cf9258 100644 --- a/object/id/id_test.go +++ b/object/id/id_test.go @@ -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") + } + } +}