time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

main.js (9865B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // MODULES //
     22 
     23 var Readable = require( 'readable-stream' ).Readable;
     24 var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
     25 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     26 var isError = require( '@stdlib/assert/is-error' );
     27 var copy = require( '@stdlib/utils/copy' );
     28 var inherit = require( '@stdlib/utils/inherit' );
     29 var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
     30 var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
     31 var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
     32 var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
     33 var runiform = require( './../../../base/uniform' ).factory;
     34 var string2buffer = require( '@stdlib/buffer/from-string' );
     35 var nextTick = require( '@stdlib/utils/next-tick' );
     36 var DEFAULTS = require( './defaults.json' );
     37 var validate = require( './validate.js' );
     38 var debug = require( './debug.js' );
     39 
     40 
     41 // FUNCTIONS //
     42 
     43 /**
     44 * Returns the PRNG seed.
     45 *
     46 * @private
     47 * @returns {(PRNGSeedMT19937|null)} seed
     48 */
     49 function getSeed() {
     50 	return this._prng.seed; // eslint-disable-line no-invalid-this
     51 }
     52 
     53 /**
     54 * Returns the PRNG seed length.
     55 *
     56 * @private
     57 * @returns {(PositiveInteger|null)} seed length
     58 */
     59 function getSeedLength() {
     60 	return this._prng.seedLength; // eslint-disable-line no-invalid-this
     61 }
     62 
     63 /**
     64 * Returns the PRNG state length.
     65 *
     66 * @private
     67 * @returns {(PositiveInteger|null)} state length
     68 */
     69 function getStateLength() {
     70 	return this._prng.stateLength; // eslint-disable-line no-invalid-this
     71 }
     72 
     73 /**
     74 * Returns the PRNG state size (in bytes).
     75 *
     76 * @private
     77 * @returns {(PositiveInteger|null)} state size (in bytes)
     78 */
     79 function getStateSize() {
     80 	return this._prng.byteLength; // eslint-disable-line no-invalid-this
     81 }
     82 
     83 /**
     84 * Returns the current PRNG state.
     85 *
     86 * @private
     87 * @returns {(PRNGStateMT19937|null)} current state
     88 */
     89 function getState() {
     90 	return this._prng.state; // eslint-disable-line no-invalid-this
     91 }
     92 
     93 /**
     94 * Sets the PRNG state.
     95 *
     96 * @private
     97 * @param {PRNGStateMT19937} s - generator state
     98 * @throws {Error} must provide a valid state
     99 */
    100 function setState( s ) {
    101 	this._prng.state = s; // eslint-disable-line no-invalid-this
    102 }
    103 
    104 /**
    105 * Implements the `_read` method.
    106 *
    107 * @private
    108 * @param {number} size - number (of bytes) to read
    109 * @returns {void}
    110 */
    111 function read() {
    112 	/* eslint-disable no-invalid-this */
    113 	var FLG;
    114 	var r;
    115 
    116 	if ( this._destroyed ) {
    117 		return;
    118 	}
    119 	FLG = true;
    120 	while ( FLG ) {
    121 		this._i += 1;
    122 		if ( this._i > this._iter ) {
    123 			debug( 'Finished generating pseudorandom numbers.' );
    124 			return this.push( null );
    125 		}
    126 		r = this._prng();
    127 
    128 		debug( 'Generated a new pseudorandom number. Value: %d. Iter: %d.', r, this._i );
    129 
    130 		if ( this._objectMode === false ) {
    131 			r = r.toString();
    132 			if ( this._i === 1 ) {
    133 				r = string2buffer( r );
    134 			} else {
    135 				r = string2buffer( this._sep+r );
    136 			}
    137 		}
    138 		FLG = this.push( r );
    139 		if ( this._i%this._siter === 0 ) {
    140 			this.emit( 'state', this.state );
    141 		}
    142 	}
    143 
    144 	/* eslint-enable no-invalid-this */
    145 }
    146 
    147 /**
    148 * Gracefully destroys a stream, providing backward compatibility.
    149 *
    150 * @private
    151 * @param {(string|Object|Error)} [error] - error
    152 * @returns {RandomStream} Stream instance
    153 */
    154 function destroy( error ) {
    155 	/* eslint-disable no-invalid-this */
    156 	var self;
    157 	if ( this._destroyed ) {
    158 		debug( 'Attempted to destroy an already destroyed stream.' );
    159 		return this;
    160 	}
    161 	self = this;
    162 	this._destroyed = true;
    163 
    164 	nextTick( close );
    165 
    166 	return this;
    167 
    168 	/**
    169 	* Closes a stream.
    170 	*
    171 	* @private
    172 	*/
    173 	function close() {
    174 		if ( error ) {
    175 			debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
    176 			self.emit( 'error', error );
    177 		}
    178 		debug( 'Closing the stream...' );
    179 		self.emit( 'close' );
    180 	}
    181 
    182 	/* eslint-enable no-invalid-this */
    183 }
    184 
    185 
    186 // MAIN //
    187 
    188 /**
    189 * Stream constructor for generating a stream of pseudorandom numbers drawn from a uniform distribution.
    190 *
    191 * @constructor
    192 * @param {number} a - minimum support
    193 * @param {number} b - maximum support
    194 * @param {Options} [options] - stream options
    195 * @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
    196 * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
    197 * @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers
    198 * @param {string} [options.sep='\n'] - separator used to join streamed data
    199 * @param {NonNegativeInteger} [options.iter] - number of iterations
    200 * @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
    201 * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
    202 * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
    203 * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
    204 * @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
    205 * @throws {TypeError} `a` must be a number
    206 * @throws {TypeError} `b` must be a number
    207 * @throws {RangeError} `a` must be less than `b`
    208 * @throws {TypeError} options argument must be an object
    209 * @throws {TypeError} must provide valid options
    210 * @throws {Error} must provide a valid state
    211 * @returns {RandomStream} Stream instance
    212 *
    213 * @example
    214 * var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    215 *
    216 * function log( chunk ) {
    217 *    console.log( chunk.toString() );
    218 * }
    219 *
    220 * var opts = {
    221 *     'iter': 10
    222 * };
    223 *
    224 * var stream = new RandomStream( 2.0, 5.0, opts );
    225 *
    226 * stream.pipe( inspectStream( log )  );
    227 */
    228 function RandomStream( a, b, options ) {
    229 	var opts;
    230 	var err;
    231 	if ( !( this instanceof RandomStream ) ) {
    232 		if ( arguments.length > 2 ) {
    233 			return new RandomStream( a, b, options );
    234 		}
    235 		return new RandomStream( a, b );
    236 	}
    237 	if ( !isNumber( a ) || isnan( a ) ) {
    238 		throw new TypeError( 'invalid argument. First argument must be a number primitive and not `NaN`. Value: `'+a+'`.' );
    239 	}
    240 	if ( !isNumber( b ) || isnan( b ) ) {
    241 		throw new TypeError( 'invalid argument. Second argument must be a number primitive and not `NaN`. Value: `'+b+'`.' );
    242 	}
    243 	if ( a >= b ) {
    244 		throw new RangeError( 'invalid argument. Minimum support `a` must be less than maximum support `b`. Value: `['+a+','+b+']`.');
    245 	}
    246 	opts = copy( DEFAULTS );
    247 	if ( arguments.length > 2 ) {
    248 		err = validate( opts, options );
    249 		if ( err ) {
    250 			throw err;
    251 		}
    252 	}
    253 	// Make the stream a readable stream:
    254 	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
    255 	Readable.call( this, opts );
    256 
    257 	// Destruction state:
    258 	setNonEnumerable( this, '_destroyed', false );
    259 
    260 	// Cache whether the stream is operating in object mode:
    261 	setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );
    262 
    263 	// Cache the separator:
    264 	setNonEnumerableReadOnly( this, '_sep', opts.sep );
    265 
    266 	// Cache the total number of iterations:
    267 	setNonEnumerableReadOnly( this, '_iter', opts.iter );
    268 
    269 	// Cache the number of iterations after which to emit the underlying PRNG state:
    270 	setNonEnumerableReadOnly( this, '_siter', opts.siter );
    271 
    272 	// Initialize an iteration counter:
    273 	setNonEnumerable( this, '_i', 0 );
    274 
    275 	// Create the underlying PRNG:
    276 	setNonEnumerableReadOnly( this, '_prng', runiform( a, b, opts ) );
    277 	setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG );
    278 
    279 	return this;
    280 }
    281 
    282 /*
    283 * Inherit from the `Readable` prototype.
    284 */
    285 inherit( RandomStream, Readable );
    286 
    287 /**
    288 * PRNG seed.
    289 *
    290 * @name seed
    291 * @memberof RandomStream.prototype
    292 * @type {(PRNGSeedMT19937|null)}
    293 */
    294 setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );
    295 
    296 /**
    297 * PRNG seed length.
    298 *
    299 * @name seedLength
    300 * @memberof RandomStream.prototype
    301 * @type {(PositiveInteger|null)}
    302 */
    303 setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );
    304 
    305 /**
    306 * PRNG state getter/setter.
    307 *
    308 * @name state
    309 * @memberof RandomStream.prototype
    310 * @type {(PRNGStateMT19937|null)}
    311 * @throws {Error} must provide a valid state
    312 */
    313 setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );
    314 
    315 /**
    316 * PRNG state length.
    317 *
    318 * @name stateLength
    319 * @memberof RandomStream.prototype
    320 * @type {(PositiveInteger|null)}
    321 */
    322 setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );
    323 
    324 /**
    325 * PRNG state size (in bytes).
    326 *
    327 * @name byteLength
    328 * @memberof RandomStream.prototype
    329 * @type {(PositiveInteger|null)}
    330 */
    331 setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );
    332 
    333 /**
    334 * Implements the `_read` method.
    335 *
    336 * @private
    337 * @name _read
    338 * @memberof RandomStream.prototype
    339 * @type {Function}
    340 * @param {number} size - number (of bytes) to read
    341 * @returns {void}
    342 */
    343 setNonEnumerableReadOnly( RandomStream.prototype, '_read', read );
    344 
    345 /**
    346 * Gracefully destroys a stream, providing backward compatibility.
    347 *
    348 * @name destroy
    349 * @memberof RandomStream.prototype
    350 * @type {Function}
    351 * @param {(string|Object|Error)} [error] - error
    352 * @returns {RandomStream} Stream instance
    353 */
    354 setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy );
    355 
    356 
    357 // EXPORTS //
    358 
    359 module.exports = RandomStream;