forked from qntm/base65536
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (50 loc) · 1.45 KB
/
index.js
File metadata and controls
55 lines (50 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
Routines for converting binary data into text data which can be sent safely
through "Unicode-clean" text systems without information being lost. Analogous
to Base64 with a significantly larger character repertoire enabling the
encoding of two bytes per character (for comparison, Base64 manages 3/4 of a
byte per character).
*/
require("string.fromcodepoint");
require("string.prototype.codepointat");
var get_block_start = require("./get-block-start.json");
var get_b2 = require("./get-b2.json");
var NO_BYTE = -1;
module.exports = {
encode: function(buf) {
var strs = [];
for(var i = 0; i < buf.length; i += 2) {
var b1 = buf[i];
var b2 = i + 1 < buf.length ? buf[i + 1] : NO_BYTE;
var codePoint = get_block_start[b2] + b1;
var str = String.fromCodePoint(codePoint);
strs.push(str);
}
return strs.join("");
},
decode: function(str) {
var bufs = [];
var done = false;
for(var i = 0; i < str.length; i++) {
if(done) {
throw new Error("Base65536 sequence continued after final byte");
}
var codePoint = str.codePointAt(i);
var b1 = codePoint & ((1 << 8) - 1);
var b2 = get_b2[codePoint - b1];
if(b2 === undefined) {
throw new Error("Not a valid Base65536 code point: " + String(codePoint));
}
if(b2 === NO_BYTE) {
bufs.push(new Buffer([b1]));
done = true;
} else {
bufs.push(new Buffer([b1, b2]));
}
if(codePoint >= (1 << 16)) {
i++;
}
}
return Buffer.concat(bufs);
}
};