Skip to content

Commit

Permalink
revert alphabet.Index to binary search instead of map
Browse files Browse the repository at this point in the history
  • Loading branch information
anatoly-kussul committed Dec 1, 2024
1 parent cf697af commit 27a53ad
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions alphabet.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const (

type alphabet struct {
chars []rune
indexMap map[rune]int
len int64
encLen int64
singleBytes bool
Expand All @@ -35,13 +34,12 @@ func newAlphabet(s string) alphabet {
len: int64(len(abc)),
encLen: int64(math.Ceil(128 / math.Log2(float64(len(abc))))),
singleBytes: true,
indexMap: make(map[rune]int, len(abc)),
}
for i, c := range a.chars {
for _, c := range a.chars {
if c > rune1Max {
a.singleBytes = false
break
}
a.indexMap[c] = i
}

return a
Expand All @@ -54,8 +52,17 @@ func (a *alphabet) Length() int64 {
// Index returns the index of the first instance of t in the alphabet, or an
// error if t is not present.
func (a *alphabet) Index(t rune) (int64, error) {
if i, ok := a.indexMap[t]; ok {
return int64(i), nil
i, j := 0, int(a.len)
for i < j {
h := int(uint(i+j) >> 1)
if a.chars[h] < t {
i = h + 1
} else {
j = h
}
}
if i >= int(a.len) || a.chars[i] != t {
return 0, fmt.Errorf("element '%v' is not part of the alphabet", t)
}
return 0, fmt.Errorf("element '%v' is not part of the alphabet", t)
return int64(i), nil
}

0 comments on commit 27a53ad

Please sign in to comment.