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