From 0811b653bd20f08f98b6412e587f8b2360d6e55c Mon Sep 17 00:00:00 2001 From: Lucas Barrena Date: Mon, 14 Aug 2023 14:12:11 -0300 Subject: [PATCH] Allow modifying next.value --- index.js | 5 ++--- test/cas.js | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 9079b68..1434026 100644 --- a/index.js +++ b/index.js @@ -741,7 +741,6 @@ class Batch { value } key = enc(encoding.key, key) - value = enc(encoding.value, value) const stack = [] @@ -768,7 +767,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, enc(encoding.value, newNode.value)) } if (c < 0) e = mid @@ -798,7 +797,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) { diff --git a/test/cas.js b/test/cas.js index 101f0f4..72bdcfc 100644 --- a/test/cas.js +++ b/test/cas.js @@ -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)