Skip to content

Commit

Permalink
radixdb: allow insertion on path node
Browse files Browse the repository at this point in the history
  • Loading branch information
toru committed Oct 7, 2024
1 parent b866159 commit aef297a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
12 changes: 10 additions & 2 deletions radixdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,17 @@ func (rdb *RadixDB) Insert(key []byte, value []byte) error {
for {
prefix := longestCommonPrefix(current.key, key)

// Exact match: Duplicate insertion is disallowed.
// Exact match found on the node key. If the current node is marked as
// a record, enforce the no-duplicate key constraint. Otherwise assign
// the current node with the given value, and mark it as a record.
if len(prefix) == len(current.key) && len(prefix) == len(newNode.key) {
return ErrDuplicateKey
if current.isRecord {
return ErrDuplicateKey
} else {
current.value = value
current.isRecord = true
return nil
}
}

// newNode's key matches the longest common prefix and is shorter than
Expand Down
20 changes: 15 additions & 5 deletions radixdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,23 @@ func TestInsert(t *testing.T) {
t.Errorf("Len(): got:%d, want:5", len)
}

// Expected tree structure:
// Test insertion on path component node (e.g. split/intermediate node).
if err := rdb.Insert([]byte("ba"), []byte("flights")); err != nil {
t.Errorf("unexpected error: %v", err)
}

// Second insertion must fail.
if err := rdb.Insert([]byte("ba"), []byte("flights")); err == nil {
t.Errorf("expected error: got:%v, want:%v", err, ErrDuplicateKey)
}

// Expected tree structure at this point:
// .
// ├─ ap ("<nil>")
// │ ├─ ple ("juice")
// │ │ └─ t ("app")
// │ └─ ricot ("farm")
// └─ ba ("<nil>")
// └─ ba ("flights")
// ├─ nana ("smoothie")
// └─ king ("show")

Expand Down Expand Up @@ -229,8 +239,8 @@ func TestInsert(t *testing.T) {
}

if bytes.Equal(baNode.key, []byte("ba")) {
if baNode.isRecord {
t.Errorf("node.isRecord: got:%t, want:%t", baNode.isRecord, false)
if !baNode.isRecord {
t.Errorf("node.isRecord: got:%t, want:%t", baNode.isRecord, true)
}

if len := len(baNode.children); len != 2 {
Expand All @@ -241,7 +251,7 @@ func TestInsert(t *testing.T) {
}

// Mild fuzzing: Insert random keys for memory errors.
numRandomInserts := 3000
numRandomInserts := 5000
numRecordsBefore := rdb.Len()
numRecordsExpected := uint64(numRandomInserts + int(numRecordsBefore))

Expand Down

0 comments on commit aef297a

Please sign in to comment.