Skip to content

Fix hang on size below 1 in customRandom() - #623

Closed
nk-batman21 wants to merge 1 commit into
ai:mainfrom
nk-batman21:fix-custom-random-size-below-one
Closed

nk-batman21 wants to merge 1 commit into
ai:mainfrom
nk-batman21:fix-custom-random-size-below-one

Conversation

@nk-batman21

Copy link
Copy Markdown

Since #616 (released in 6.0.2), the power-of-two branch of customRandom() never returns when the size is between 0 and 1. if (!size) lets 0.5 through, then size |= 0 turns it into 0, so the inner loop does nothing and while (true) spins forever. The browser tab or Node process freezes.

It is reachable through the public API. In the browser, React Native and edge builds customAlphabet() is customRandom(), so a computed size like customAlphabet('0123456789abcdef')(length / 2) with length = 1 hangs. In Node, customRandom(urlAlphabet, 10, random)(0.5) and multi-byte power-of-two alphabets such as customAlphabet('абвг')(0.5) hang the same way. Before #616 these calls returned one character, and nanoid(0.5) and the Node customAlphabet() fast path already return ''.

This change moves the existing size |= 0 into the empty-size check, so the check sees the integer. Sizes that truncate to 0, like 0.5 or -0.5, now return '' like nanoid(). Infinity also returns '' now (it looped in Node and threw in the browser build), the same as nanoid(Infinity). Normal integer and larger fractional sizes behave as before, negative ones still throw, and getRandom always gets an integer. customAlphabet grows by 6 B (220 B to 226 B), so I bumped the limit. A micro-benchmark of the power-of-two path in both builds showed no difference beyond run-to-run noise.

Ran: bnt --coverage 100 (90 tests pass, 100% coverage), oxlint, size-limit and test/check-prebuild.js on Node 24.
Checked: the new test hangs on main and passes with the change.

@ai

ai commented Oct 26, 2026

Copy link
Copy Markdown
Owner

2% is too much for absolutely theoretical issue.

Please don't open based on LLM ideas. Open source maintainers prefer spend time for real issue.

@ai ai closed this Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants