Last active
August 29, 2015 14:01
-
-
Save jcoglan/10b8d8895ce96a470354 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I need a better name for the thing below called StreamReader. It essentially | |
// lets you split a stream into a sequence of smaller streams of fixed size, | |
// simplifying parsing TCP input for certain protocols. | |
// | |
// What it does: | |
// | |
// * It's a writable stream that buffers everything written to it | |
// | |
// * It has a fork() method, that takes a number n and returns a stream that | |
// will yield up to n bytes before emitting 'end', with no guarantees about | |
// where the chunk buffer boundaries occur | |
// | |
// * When a stream is created with fork(n), if there are no streams ahead of it | |
// in the queue, StreamReader routes up to n of its buffered bytes to this | |
// new stream | |
// | |
// * As new bytes are written, they are routed to the first stream in the queue | |
// until that stream has reached its byte limit | |
// | |
// * Once a stream reaches its limit it is shifted off the queue and input is | |
// routed to the next forked stream | |
var sr = new StreamReader(); | |
var a = sr.fork(3), b = sr.fork(4), c = sr.fork(5); | |
a.on('data', function(buf) { console.log('A', buf) }); | |
b.on('data', function(buf) { console.log('B', buf) }); | |
c.on('data', function(buf) { console.log('C', buf) }); | |
var hello = new Buffer('Hello, world'); | |
console.log(hello); | |
sr.write(hello); | |
/* -> <Buffer 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64> | |
A <Buffer 48 65 6c> | |
B <Buffer 6c 6f 2c 20> | |
C <Buffer 77 6f 72 6c 64> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment