Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HasOrPut api method #49

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,59 @@ func (db *DB) Put(key []byte, value []byte) error {
return nil
}

// HasOrPut sets value if the given key is missing
func (db *DB) HasOrPut(key, value []byte) (bool, error) {
if len(key) > MaxKeyLength {
return false, errKeyTooLarge
}
if len(value) > MaxValueLength {
return false, errValueTooLarge
}
found := false
h := db.hash(key)
db.mu.Lock()
defer db.mu.Unlock()
err := db.index.get(h, func(sl slot) (bool, error) {
if uint16(len(key)) != sl.keySize {
return false, nil
}
slKey, err := db.datalog.readKey(sl)
if err != nil {
return true, err
}
if bytes.Equal(key, slKey) {
found = true
return true, nil
}
return false, nil
})
if err != nil {
return false, err
}
if !found {
segID, offset, err := db.datalog.put(key, value)
if err != nil {
return false, err
}
sl := slot{
hash: h,
segmentID: segID,
keySize: uint16(len(key)),
valueSize: uint32(len(value)),
offset: offset,
}

if err := db.put(sl, key); err != nil {
return false, err
}

if db.syncWrites {
return found, db.sync()
}
}
return found, nil
}

func (db *DB) del(h uint32, key []byte, writeWAL bool) error {
err := db.index.delete(h, func(sl slot) (b bool, e error) {
if uint16(len(key)) != sl.keySize {
Expand Down