Skip to content

Commit

Permalink
Numerical instead of lexicographic sorting of config keys
Browse files Browse the repository at this point in the history
  • Loading branch information
yperbasis committed Oct 23, 2023
1 parent a87d9a0 commit e07deef
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
23 changes: 13 additions & 10 deletions params/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -750,23 +750,26 @@ func (c *BorConfig) IsSprintStart(number uint64) bool {
}

func borKeyValueConfigHelper[T uint64 | string](field map[string]T, number uint64) T {
keys := make([]string, 0, len(field))
for k := range field {
keys = append(keys, k)
keys := make([]uint64, 0, len(field))
fieldUint := make(map[uint64]T)
for k, v := range field {
keyUint, err := strconv.ParseUint(k, 10, 64)
if err != nil {
panic(err)
}
keys = append(keys, keyUint)
fieldUint[keyUint] = v
}

sort.Strings(keys)
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })

for i := 0; i < len(keys)-1; i++ {
valUint, _ := strconv.ParseUint(keys[i], 10, 64)
valUintNext, _ := strconv.ParseUint(keys[i+1], 10, 64)

if number >= valUint && number < valUintNext {
return field[keys[i]]
if number >= keys[i] && number < keys[i+1] {
return fieldUint[keys[i]]
}
}

return field[keys[len(keys)-1]]
return fieldUint[keys[len(keys)-1]]
}

func (c *BorConfig) CalculateBurntContract(number uint64) string {
Expand Down
14 changes: 14 additions & 0 deletions params/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,18 @@ func TestBorKeyValueConfigHelper(t *testing.T) {
assert.Equal(t, borKeyValueConfigHelper(backupMultiplier, 29638656-1), uint64(5))
assert.Equal(t, borKeyValueConfigHelper(backupMultiplier, 29638656), uint64(2))
assert.Equal(t, borKeyValueConfigHelper(backupMultiplier, 29638656+1), uint64(2))

config := map[string]uint64{
"0": 1,
"90000000": 2,
"100000000": 3,
}
assert.Equal(t, borKeyValueConfigHelper(config, 0), uint64(1))
assert.Equal(t, borKeyValueConfigHelper(config, 1), uint64(1))
assert.Equal(t, borKeyValueConfigHelper(config, 90000000-1), uint64(1))
assert.Equal(t, borKeyValueConfigHelper(config, 90000000), uint64(2))
assert.Equal(t, borKeyValueConfigHelper(config, 90000000+1), uint64(2))
assert.Equal(t, borKeyValueConfigHelper(config, 100000000-1), uint64(2))
assert.Equal(t, borKeyValueConfigHelper(config, 100000000), uint64(3))
assert.Equal(t, borKeyValueConfigHelper(config, 100000000+1), uint64(3))
}

0 comments on commit e07deef

Please sign in to comment.