Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly sort hashmap keys #329

Merged
merged 2 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions tlb/address.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tlb

import (
"bytes"
"fmt"

"github.com/tonkeeper/tongo/boc"
Expand All @@ -21,6 +22,14 @@ func (addr AddressWithWorkchain) Equal(other any) bool {
return addr.Workchain == otherAddr.Workchain && addr.Address == otherAddr.Address
}

func (addr AddressWithWorkchain) Compare(other any) int {
otherAddr, ok := other.(AddressWithWorkchain)
if !ok {
return 0
}
return bytes.Compare(addr.Address[:], otherAddr.Address[:])
}

func (addr AddressWithWorkchain) FixedSize() int {
return 288
}
Expand Down
3 changes: 2 additions & 1 deletion tlb/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ func main() {
// Code autogenerated. DO NOT EDIT.

import (
"bytes"
"encoding/hex"
"fmt"
"math/big"
"strings"
"strconv"
"strings"

"github.com/tonkeeper/tongo/boc"
)
Expand Down
15 changes: 13 additions & 2 deletions tlb/hashmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"

"github.com/tonkeeper/tongo/boc"
Expand All @@ -12,6 +13,7 @@ import (
type fixedSize interface {
FixedSize() int
Equal(other any) bool
Compare(other any) int
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does it make sense to change the method to:

Compare(other any) (int, bool)
or 
Compare (other any) (int, error)

because returning 0 when we can't cast other to a specific type looks unreliable

}

// HashmapItem represents a key-value pair stored in HashmapE[T].
Expand Down Expand Up @@ -323,8 +325,17 @@ func (h *Hashmap[keyT, T]) Put(key keyT, value T) {
return
}
}
h.values = append(h.values, value)
h.keys = append(h.keys, key) //todo: i think we need to sort keys

index := len(h.keys)
for idx, other := range h.keys {
if key.Compare(other) < 0 {
index = idx
break
}
}

h.keys = slices.Insert(h.keys, index, key)
h.values = slices.Insert(h.values, index, value)
}

type HashmapE[keyT fixedSize, T any] struct {
Expand Down
Loading