import { fromBuffer } from './fromBuffer' ; import { _isProbablyPrime , _isProbablyPrimeWorkerUrl } from './isProbablyPrime' ; import { randBits , randBitsSync } from './randBits' ; import { _useWorkers , WorkerToMainMsg , MainToWorkerMsg } from './workerUtils' ; param bitLength param iterations throws returns export function prime ( bitLength , iterations = 16 ) { if ( bitLength < 1 ) throw new RangeError ( 'bitLength MUST be > 0' ) ; if ( ! _useWorkers ) { let rnd = 0n ; do { rnd = fromBuffer ( randBitsSync ( bitLength , true ) ) ; } while ( ! _isProbablyPrime ( rnd , iterations ) ) ; return new Promise ( ( resolve ) => { resolve ( rnd ) ; } ) ; } return new Promise ( ( resolve , reject ) => { const workerList = [ ] ; const _onmessage = ( msg , newWorker ) : void => { if ( msg . isPrime ) { for ( let j = 0 ; j < workerList . length ; j ++ ) { workerList [ j ] . terminate ( ) ; } while ( workerList . length > 0 ) { workerList . pop ( ) ; } resolve ( msg . value ) ; } else { const buf = randBitsSync ( bitLength , true ) ; const rnd = fromBuffer ( buf ) ; try { const msgToWorker = { rnd : rnd , iterations : iterations , id : msg . id } ; newWorker . postMessage ( msgToWorker ) ; } catch ( error ) { } } } ; if ( IS_BROWSER ) { const workerURL = _isProbablyPrimeWorkerUrl ( ) ; for ( let i = 0 ; i < self . navigator . hardwareConcurrency - 1 ; i ++ ) { const newWorker = new Worker ( workerURL ) ; newWorker . onmessage = ( event ) => _onmessage ( event . data , newWorker ) ; workerList . push ( newWorker ) ; } } else { const { cpus } = require ( 'os' ) ; const { Worker } = require ( 'worker_threads' ) ; for ( let i = 0 ; i < cpus ( ) . length - 1 ; i ++ ) { const newWorker = new Worker ( __filename ) ; newWorker . on ( 'message' , ( msg ) => _onmessage ( msg , newWorker ) ) ; workerList . push ( newWorker ) ; } } for ( let i = 0 ; i < workerList . length ; i ++ ) { randBits ( bitLength , true ) . then ( function ( buf ) { const rnd = fromBuffer ( buf ) ; workerList [ i ] . postMessage ( { rnd : rnd , iterations : iterations , id : i } ) ; } ) . catch ( reject ) ; } } ) ; } param bitLength param iterations throws returns export function primeSync ( bitLength , iterations = 16 ) { if ( bitLength < 1 ) throw new RangeError ( 'bitLength MUST be > 0' ) ; let rnd = 0n ; do { rnd = fromBuffer ( randBitsSync ( bitLength , true ) ) ; } while ( ! _isProbablyPrime ( rnd , iterations ) ) ; return rnd ; }