Skip to content

Commit

Permalink
feat(random): Added RandomStream
Browse files Browse the repository at this point in the history
  • Loading branch information
olalonde committed Sep 19, 2016
1 parent 0d74896 commit 02f8ed6
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 2 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,10 @@ size in bytes of the stream.
`new SizeStream()`

If passed a callback `new SizeStream(cb)` it will just act as a
PassThrough stream and call the callback when it's done.
PassThrough stream and call the callback when it's done.

### RandomStream

`new RandomStream(max)`

Readable stream that emits `max` random bytes before ending.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "common-streams",
"version": "1.0.1",
"version": "1.1.0",
"description": "",
"main": "./lib/index.js",
"directories": {
Expand Down
20 changes: 20 additions & 0 deletions src/RandomStream.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Readable } from 'stream'
import { randomBytes } from 'crypto'

export default class RandomStream extends Readable {
constructor(max) {
super()
this.remainingBytes = max
}
_read(requestedSize) {
if (this.remainingBytes === 0) return this.push(null)

const size = Math.min(this.remainingBytes, requestedSize)
this.remainingBytes -= size

randomBytes(size, (err, buf) => {
if (err) return this.emit('error', err)
this.push(buf)
})
}
}
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as HashStream } from './HashStream'
export { default as SizeStream } from './SizeStream'
export { default as RandomStream } from './RandomStream'
22 changes: 22 additions & 0 deletions test/random.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import test from 'blue-tape'
import concat from 'concat-stream'

import { RandomStream } from '../src/'

test('random stream', (t) => {
const rand = new RandomStream(10)

rand.pipe(concat((buf) => {
t.equal(buf.length, 10)
t.end()
}))
})

test('random stream #2', (t) => {
const rand = new RandomStream(2000)

rand.pipe(concat((buf) => {
t.equal(buf.length, 2000)
t.end()
}))
})

0 comments on commit 02f8ed6

Please sign in to comment.