Skip to content

Commit

Permalink
Simplify horrible boolean logic
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 authored and edwardmack committed Feb 14, 2022
1 parent 32e2063 commit 683d582
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions lib/trie/trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,12 +250,7 @@ func findNextKeyLeaf(leaf *node.Leaf, prefix, searchKey []byte) (nextKey []byte)
fullKey = append(fullKey, prefix...)
fullKey = append(fullKey, parentLeafKey...)

searchKeyBigger :=
(len(searchKey) < len(fullKey) &&
bytes.Compare(searchKey, fullKey[:len(searchKey)]) == 1) ||
(len(searchKey) >= len(fullKey) &&
bytes.Compare(searchKey[:len(fullKey)], fullKey) != -1)
if searchKeyBigger {
if keyIsLexicographicallyBigger(searchKey, fullKey) {
return nil
}

Expand All @@ -272,19 +267,10 @@ func findNextKeyBranch(parentBranch *node.Branch, prefix, searchKey []byte) (nex
return findNextKeyChild(parentBranch.Children, startChildIndex, fullKey, searchKey)
}

searchKeyShorter := len(searchKey) < len(fullKey)
searchKeyLonger := len(searchKey) > len(fullKey)

searchKeyBigger :=
(searchKeyShorter &&
bytes.Compare(searchKey, fullKey[:len(searchKey)]) == 1) ||
(!searchKeyShorter &&
bytes.Compare(searchKey[:len(fullKey)], fullKey) != -1)

if searchKeyBigger {
if searchKeyShorter {
if keyIsLexicographicallyBigger(searchKey, fullKey) {
if len(searchKey) < len(fullKey) {
return nil
} else if searchKeyLonger {
} else if len(searchKey) > len(fullKey) {
startChildIndex := searchKey[len(fullKey)]
return findNextKeyChild(parentBranch.Children,
startChildIndex, fullKey, searchKey)
Expand All @@ -300,6 +286,13 @@ func findNextKeyBranch(parentBranch *node.Branch, prefix, searchKey []byte) (nex
fullKey, searchKey)
}

func keyIsLexicographicallyBigger(key, key2 []byte) (bigger bool) {
if len(key) < len(key2) {
return bytes.Compare(key, key2[:len(key)]) == 1
}
return bytes.Compare(key[:len(key2)], key2) != -1
}

// findNextKeyChild searches for a next key in the children
// given and returns a next key or nil if no next key is found.
func findNextKeyChild(children [16]node.Node, startIndex byte,
Expand Down

0 comments on commit 683d582

Please sign in to comment.