import { randomFillSync } from "crypto";
import { urlAlphabet } from "./url-alphabet/index.js";
export { urlAlphabet };
var POOL_SIZE_MULTIPLIER = 128;
var pool, poolOffset;
var fillPool = function fillPool(bytes) {
    if (!pool || pool.length < bytes) {
        pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
        randomFillSync(pool);
        poolOffset = 0;
    } else if (poolOffset + bytes > pool.length) {
        randomFillSync(pool);
        poolOffset = 0;
    }
    poolOffset += bytes;
};
export var random = function random(bytes) {
    fillPool(bytes -= 0);
    return pool.subarray(poolOffset - bytes, poolOffset);
};
export var customRandom = function customRandom(alphabet, defaultSize, getRandom) {
    var mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
    var step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
    return function() {
        var size = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : defaultSize;
        var id = '';
        while(true){
            var bytes = getRandom(step);
            var i = step;
            while(i--){
                id += alphabet[bytes[i] & mask] || '';
                if (id.length === size) return id;
            }
        }
    };
};
export var customAlphabet = function customAlphabet(alphabet) {
    var size = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 21;
    return customRandom(alphabet, size, random);
};
export var nanoid = function nanoid() {
    var size = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 21;
    fillPool(size -= 0);
    var id = '';
    for(var i = poolOffset - size; i < poolOffset; i++){
        id += urlAlphabet[pool[i] & 63];
    }
    return id;
};
