Skip to content

Commit

Permalink
Allow modifying next.value
Browse files Browse the repository at this point in the history
  • Loading branch information
LuKks committed Aug 14, 2023
1 parent 1241013 commit 3d5f980
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -768,7 +768,7 @@ class Batch {
if (cas && !(await cas((await node.getKeyNode(mid)).final(encoding), newNode))) return this._unlockMaybe()

node.setKey(mid, target)
return this._append(root, seq, key, value)
return this._append(root, seq, key, newNode.value)
}

if (c < 0) e = mid
Expand Down Expand Up @@ -798,7 +798,7 @@ class Batch {
}
}

return this._append(root, seq, key, value)
return this._append(root, seq, key, enc(encoding.value, newNode.value))
}

async del (key, opts) {
Expand Down
56 changes: 56 additions & 0 deletions test/cas.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,62 @@ const test = require('brittle')
const b4a = require('b4a')
const { create } = require('./helpers')

test('cas - swap with a new value', async function (t) {
const db = create({ valueEncoding: 'json' })

await db.put('/a', 0, {
cas: function (prev, next) {
t.is(prev, null)
t.alike(next, { seq: 1, key: '/a', value: 0 })
return next
}
})

t.alike(await db.get('/a'), { seq: 1, key: '/a', value: 0 })

await db.put('/a', 99, {
cas: function (prev, next) {
t.alike(prev, { seq: 1, key: '/a', value: 0 })
t.alike(next, { seq: 2, key: '/a', value: 99 })
next.value = prev.value + 1 // Overwrites so it's not 99 anymore
return next
}
})

t.alike(await db.get('/a'), { seq: 2, key: '/a', value: 1 })

await db.put('/a', 99, {
cas: function (prev, next) {
t.alike(prev, { seq: 2, key: '/a', value: 1 })
t.alike(next, { seq: 3, key: '/a', value: 99 })
next.value = prev.value + 1
return next
}
})

t.alike(await db.get('/a'), { seq: 3, key: '/a', value: 2 })
})

test('cas - should not swap', async function (t) {
t.plan(4)

const db = create({ valueEncoding: 'json' })

await db.put('/a', 1)

t.alike(await db.get('/a'), { seq: 1, key: '/a', value: 1 })

await db.put('/a', 2, {
cas: function (prev, next) {
t.alike(prev, { seq: 1, key: '/a', value: 1 })
t.alike(next, { seq: 2, key: '/a', value: 2 })
return null
}
})

t.alike(await db.get('/a'), { seq: 1, key: '/a', value: 1 })
})

test('cas is called when prev does not exists', async function (t) {
t.plan(6)

Expand Down

0 comments on commit 3d5f980

Please sign in to comment.