Skip to content

Commit

Permalink
fix: Prevent $state bigints incrementing and decrementing from th…
Browse files Browse the repository at this point in the history
…rowing (#14485)

* Fix `$.update` and `$.update_pre` for bigints

* resolve conflicts

* fix some things

* fix thing i definitely didn't just break

* hopefully this will fix it

* fix formatting

* simplify

* style consistency

* simplify

* changeset

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
  • Loading branch information
Ocean-OS and Rich-Harris authored Dec 1, 2024
1 parent fe15ad4 commit 945b625
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/young-beds-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: correctly increment/decrement bigints
25 changes: 17 additions & 8 deletions packages/svelte/src/internal/client/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -1068,23 +1068,32 @@ function get_parent_context(component_context) {
}

/**
* @param {Value<number>} signal
* @template {number | bigint} T
* @param {Value<T>} signal
* @param {1 | -1} [d]
* @returns {number}
* @returns {T}
*/
export function update(signal, d = 1) {
var value = +get(signal);
set(signal, value + d);
return value;
var value = get(signal);
var result = d === 1 ? value++ : value--;

set(signal, value);

// @ts-expect-error
return result;
}

/**
* @param {Value<number>} signal
* @template {number | bigint} T
* @param {Value<T>} signal
* @param {1 | -1} [d]
* @returns {number}
* @returns {T}
*/
export function update_pre(signal, d = 1) {
return set(signal, +get(signal) + d);
var value = get(signal);

// @ts-expect-error
return set(signal, d === 1 ? ++value : --value);
}

/**
Expand Down
16 changes: 16 additions & 0 deletions packages/svelte/tests/signals/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,4 +765,20 @@ describe('signals', () => {
assert.deepEqual(a.deriveds, null);
};
});

test('bigint states update correctly', () => {
return () => {
const count = state(0n);

assert.doesNotThrow(() => $.update(count));
assert.equal($.get(count), 1n);
assert.doesNotThrow(() => $.update(count, -1));
assert.equal($.get(count), 0n);

assert.doesNotThrow(() => $.update_pre(count));
assert.equal($.get(count), 1n);
assert.doesNotThrow(() => $.update_pre(count, -1));
assert.equal($.get(count), 0n);
};
});
});

0 comments on commit 945b625

Please sign in to comment.