Skip to content

Instantly share code, notes, and snippets.

@nikcorg
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikcorg/9e46d65a92e5aec18d52 to your computer and use it in GitHub Desktop.
Save nikcorg/9e46d65a92e5aec18d52 to your computer and use it in GitHub Desktop.
Streaming (8-bit) rot13 - still teaching myself streams, this seemed like a "useful" idea.
var through = require("through");
var rot13 = through(function write(buffer) {
var transformed = new Buffer(buffer.length);
var rot = 13;
var lcase = { min: 97, max: 122 };
var ucase = { min: 65, max: 90 };
for (var i = 0, b = buffer.readUInt8(i); i < buffer.length; ++i, b = buffer.readUInt8(i, true)) {
if (ucase.min <= b && b <= ucase.max) {
b += rot;
// Fix overflow
if (ucase.max < b) {
b = ucase.min + (b - ucase.max - 1);
}
} else if (lcase.min <= b && b <= lcase.max) {
b += rot;
// Fix overflow
if (lcase.max < b) {
b = lcase.min + (b - lcase.max - 1);
}
}
transformed.writeUInt8(b, i);
}
if (this.paused) {
this.queue(transformed);
} else {
this.emit("data", transformed);
}
});
process.stdin.pipe(rot13).pipe(process.stdout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment