Signed-off-by: Andrew C. Bodine <acbodine@us.ibm.com>
This commit is contained in:
parent
feb02197c1
commit
2da8e34079
2 changed files with 15 additions and 12 deletions
|
@ -10,10 +10,8 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
// ErrNoID is thrown when attempting to use empty prefixes
|
||||
ErrNoID = errors.New("prefix can't be empty")
|
||||
// ErrDuplicateID is thrown when a duplicated id was found
|
||||
ErrDuplicateID = errors.New("multiple IDs were found")
|
||||
ErrEmptyPrefix = errors.New("Prefix can't be empty")
|
||||
ErrAmbiguousPrefix = errors.New("Multiple IDs found with provided prefix")
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
@ -47,7 +45,7 @@ func (idx *TruncIndex) addID(id string) error {
|
|||
return fmt.Errorf("illegal character: ' '")
|
||||
}
|
||||
if id == "" {
|
||||
return ErrNoID
|
||||
return ErrEmptyPrefix
|
||||
}
|
||||
if _, exists := idx.ids[id]; exists {
|
||||
return fmt.Errorf("id already exists: '%s'", id)
|
||||
|
@ -87,26 +85,26 @@ func (idx *TruncIndex) Delete(id string) error {
|
|||
// Get retrieves an ID from the TruncIndex. If there are multiple IDs
|
||||
// with the given prefix, an error is thrown.
|
||||
func (idx *TruncIndex) Get(s string) (string, error) {
|
||||
idx.RLock()
|
||||
defer idx.RUnlock()
|
||||
if s == "" {
|
||||
return "", ErrEmptyPrefix
|
||||
}
|
||||
var (
|
||||
id string
|
||||
)
|
||||
if s == "" {
|
||||
return "", ErrNoID
|
||||
}
|
||||
subTreeVisitFunc := func(prefix patricia.Prefix, item patricia.Item) error {
|
||||
if id != "" {
|
||||
// we haven't found the ID if there are two or more IDs
|
||||
id = ""
|
||||
return ErrDuplicateID
|
||||
return ErrAmbiguousPrefix
|
||||
}
|
||||
id = string(prefix)
|
||||
return nil
|
||||
}
|
||||
|
||||
idx.RLock()
|
||||
defer idx.RUnlock()
|
||||
if err := idx.trie.VisitSubtree(patricia.Prefix(s), subTreeVisitFunc); err != nil {
|
||||
return "", fmt.Errorf("no such id: %s", s)
|
||||
return "", err
|
||||
}
|
||||
if id != "" {
|
||||
return id, nil
|
||||
|
|
|
@ -59,6 +59,11 @@ func TestTruncIndex(t *testing.T) {
|
|||
assertIndexGet(t, index, id[:4], "", true)
|
||||
assertIndexGet(t, index, id[:1], "", true)
|
||||
|
||||
// An ambiguous id prefix should return an error
|
||||
if _, err := index.Get(id[:4]); err == nil || err == nil {
|
||||
t.Fatal("An ambiguous id prefix should return an error")
|
||||
}
|
||||
|
||||
// 7 characters should NOT conflict
|
||||
assertIndexGet(t, index, id[:7], id, false)
|
||||
assertIndexGet(t, index, id2[:7], id2, false)
|
||||
|
|
Loading…
Reference in a new issue