Skip to content
Myr

Fix pool pollution, infinite loop (#508)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

When nanoid is called with a fractional value, there were a number of undesirable effects: - in browser and non-secure, the code infinite loops on `while (size--)` - in node, the value of poolOffset becomes fractional, causing calls to nanoid to return zeroes until the pool is next filled: when `i` is initialized to `poolOffset`, `pool[i] & 63` -> `undefined & 63` -> `0` - if the first call in node is a fractional argument, the initial buffer allocation fails with an error I chose `|0` to cast to a signed integer primarily because that has a slightly better outcome in the third case above: if the first call is negative (e.g. `nanoid(-1)`) then Node will throw an error for an invalid Buffer size, rather than attempting to allocate a buffer of size `2**32-1`. It's also more compact than `>>>0`, which would be necessary to cast to an unsigned integer. I don't _think_ there is a use case for generating ids longer than `2**31-1` :)

authored by Kris Reeves · committed by GitHub · parent 009b5f4 · Browse files · 4 files+15 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+15 added−8 removed

  • tests:+7 added−0 removed
  • other:+8 added−8 removed

4 files+15 added−8 removed

modified:non-secure/index.js+2 added-2 removed
modified:test/index.test.js+7 added
55 unmodified lines
56 used[id] = true57 }58 })5960 test(`avoids pool pollution, infinite loop`, () => {61 nanoid(2.1)62 const second = nanoid()63 const third = nanoid()64 notEqual(second, third)65 })6667 test(`has flat distribution`, () => {68 let COUNT = 100 * 100069 let LENGTH = nanoid().length70
136 unmodified lines
modified:index.browser.js+2 added-2 removed
modified:index.js+4 added-4 removed