Skip to content

Instantly share code, notes, and snippets.

@dorentus
Last active August 29, 2015 13:57
Show Gist options
  • Save dorentus/9385976 to your computer and use it in GitHub Desktop.
Save dorentus/9385976 to your computer and use it in GitHub Desktop.
String.prototype.bytes = function () {
var bytes = [], i = 0;
while ( true ) {
var byte = this.charCodeAt(i);
if ( isNaN(byte) ) break;
bytes.push(byte);
i += 1;
}
return bytes;
}
String.prototype.toAscii85 = function () {
var encode_base85_block = function (block) {
var padding_length = 0, bytes = [];
for ( var i = 0; i < 4; ++i ) {
if ( block[i] === undefined ) {
block[i] = 0;
padding_length += 1;
}
}
if ( padding_length === 0 && block.every(function (v) { return v === 0; }) ) {
return [122];
}
var n = (block[0] << 24) + (block[1] << 16) + (block[2] << 8) + block[3];
while ( n < 0 ) {
n += 4294967296;
}
while ( true ) {
var new_n = Math.floor(n / 85);
bytes.push(n - new_n * 85 + 33);
n = new_n;
if ( bytes.length === 5 ) break;
}
return bytes.reverse().slice(0, 5 - padding_length);
}, bytes = this.bytes(), result_bytes = [60, 126];
for ( var i = 0, n = bytes.length ; i < n; i = i + 4 ) {
result_bytes = result_bytes.concat(encode_base85_block([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]));
}
result_bytes.push(126);
result_bytes.push(62);
return result_bytes.map(function (v) { return String.fromCharCode(v); }).join('');
};
String.prototype.fromAscii85 = function () {
var decode_base85_block = function (block) {
var padding_length = 0;
for ( var i = 0; i < 5; ++i ) {
if ( block[i] === undefined ) {
block[i] = 117;
padding_length += 1;
}
}
var n = block.reduce(function (m, v, index) {
return m + (v - 33) * Math.pow(85, 4 - index);
}, 0);
var bytes = [];
bytes.push(n >> 24)
bytes.push((n & 0xffffff) >> 16)
bytes.push((n & 0xffff) >> 8)
bytes.push(n & 0xff)
bytes = bytes.map(function (v) {
while ( v < 0 ) {
v += 256;
}
return v;
});
return bytes.slice(0, 4 - padding_length);
}
var subject = this.replace(/\s/g, '').replace(/^<~/, '').replace(/~>$/, '').replace(/z/g, '!!!!!');
var result_bytes = [];
var bytes = subject.bytes();
for ( var i = 0, n = bytes.length; i < n; i += 5 ) {
var block = [bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3], bytes[i + 4]];
result_bytes = result_bytes.concat(decode_base85_block(block));
}
return result_bytes.map(function (v) { return String.fromCharCode(v); }).join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment