time-to-botec

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

main.js (10133B)


      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 rtriang = require( './../../../base/triangular' ).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 {number} c - mode
    195 * @param {Options} [options] - stream options
    196 * @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
    197 * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
    198 * @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers
    199 * @param {string} [options.sep='\n'] - separator used to join streamed data
    200 * @param {NonNegativeInteger} [options.iter] - number of iterations
    201 * @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
    202 * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
    203 * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
    204 * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
    205 * @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
    206 * @throws {TypeError} `a` must be a number
    207 * @throws {TypeError} `b` must be a number
    208 * @throws {TypeError} `c` must be a number
    209 * @throws {RangeError} arguments must satisfy `a <= c <= b`
    210 * @throws {TypeError} options argument must be an object
    211 * @throws {TypeError} must provide valid options
    212 * @throws {Error} must provide a valid state
    213 * @returns {RandomStream} Stream instance
    214 *
    215 * @example
    216 * var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
    217 *
    218 * function log( chunk ) {
    219 *    console.log( chunk.toString() );
    220 * }
    221 *
    222 * var opts = {
    223 *     'iter': 10
    224 * };
    225 *
    226 * var stream = new RandomStream( 2.0, 5.0, 4.0, opts );
    227 *
    228 * stream.pipe( inspectStream( log )  );
    229 */
    230 function RandomStream( a, b, c, options ) {
    231 	var opts;
    232 	var err;
    233 	if ( !( this instanceof RandomStream ) ) {
    234 		if ( arguments.length > 3 ) {
    235 			return new RandomStream( a, b, c, options );
    236 		}
    237 		return new RandomStream( a, b, c );
    238 	}
    239 	if ( !isNumber( a ) || isnan( a ) ) {
    240 		throw new TypeError( 'invalid argument. First argument must be a number primitive and not `NaN`. Value: `'+a+'`.' );
    241 	}
    242 	if ( !isNumber( b ) || isnan( b ) ) {
    243 		throw new TypeError( 'invalid argument. Second argument must be a number primitive and not `NaN`. Value: `'+b+'`.' );
    244 	}
    245 	if ( !isNumber( c ) || isnan( c ) ) {
    246 		throw new TypeError( 'invalid argument. Third argument must be a number primitive and not `NaN`. Value: `'+b+'`.' );
    247 	}
    248 	if ( !(a <= c && c <= b) ) {
    249 		throw new RangeError( 'invalid arguments. The condition `a <= c <= b` must be satisfied. Value: `['+a+','+b+','+c+']`.');
    250 	}
    251 	opts = copy( DEFAULTS );
    252 	if ( arguments.length > 3 ) {
    253 		err = validate( opts, options );
    254 		if ( err ) {
    255 			throw err;
    256 		}
    257 	}
    258 	// Make the stream a readable stream:
    259 	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
    260 	Readable.call( this, opts );
    261 
    262 	// Destruction state:
    263 	setNonEnumerable( this, '_destroyed', false );
    264 
    265 	// Cache whether the stream is operating in object mode:
    266 	setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );
    267 
    268 	// Cache the separator:
    269 	setNonEnumerableReadOnly( this, '_sep', opts.sep );
    270 
    271 	// Cache the total number of iterations:
    272 	setNonEnumerableReadOnly( this, '_iter', opts.iter );
    273 
    274 	// Cache the number of iterations after which to emit the underlying PRNG state:
    275 	setNonEnumerableReadOnly( this, '_siter', opts.siter );
    276 
    277 	// Initialize an iteration counter:
    278 	setNonEnumerable( this, '_i', 0 );
    279 
    280 	// Create the underlying PRNG:
    281 	setNonEnumerableReadOnly( this, '_prng', rtriang( a, b, c, opts ) );
    282 	setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG );
    283 
    284 	return this;
    285 }
    286 
    287 /*
    288 * Inherit from the `Readable` prototype.
    289 */
    290 inherit( RandomStream, Readable );
    291 
    292 /**
    293 * PRNG seed.
    294 *
    295 * @name seed
    296 * @memberof RandomStream.prototype
    297 * @type {(PRNGSeedMT19937|null)}
    298 */
    299 setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );
    300 
    301 /**
    302 * PRNG seed length.
    303 *
    304 * @name seedLength
    305 * @memberof RandomStream.prototype
    306 * @type {(PositiveInteger|null)}
    307 */
    308 setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );
    309 
    310 /**
    311 * PRNG state getter/setter.
    312 *
    313 * @name state
    314 * @memberof RandomStream.prototype
    315 * @type {(PRNGStateMT19937|null)}
    316 * @throws {Error} must provide a valid state
    317 */
    318 setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );
    319 
    320 /**
    321 * PRNG state length.
    322 *
    323 * @name stateLength
    324 * @memberof RandomStream.prototype
    325 * @type {(PositiveInteger|null)}
    326 */
    327 setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );
    328 
    329 /**
    330 * PRNG state size (in bytes).
    331 *
    332 * @name byteLength
    333 * @memberof RandomStream.prototype
    334 * @type {(PositiveInteger|null)}
    335 */
    336 setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );
    337 
    338 /**
    339 * Implements the `_read` method.
    340 *
    341 * @private
    342 * @name _read
    343 * @memberof RandomStream.prototype
    344 * @type {Function}
    345 * @param {number} size - number (of bytes) to read
    346 * @returns {void}
    347 */
    348 setNonEnumerableReadOnly( RandomStream.prototype, '_read', read );
    349 
    350 /**
    351 * Gracefully destroys a stream, providing backward compatibility.
    352 *
    353 * @name destroy
    354 * @memberof RandomStream.prototype
    355 * @type {Function}
    356 * @param {(string|Object|Error)} [error] - error
    357 * @returns {RandomStream} Stream instance
    358 */
    359 setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy );
    360 
    361 
    362 // EXPORTS //
    363 
    364 module.exports = RandomStream;