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