Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#84 WIP convert to binary instead of to utf8 #107

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 18 additions & 36 deletions src/BufferStream.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,18 @@
//http://jonisalonen.com/2012/from-utf-16-to-utf-8-in-javascript/
function toUTF8Array(str) {
var utf8 = [];
for (var i = 0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f));
} else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(
0xe0 | (charcode >> 12),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f)
);
}
// surrogate pair
else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode =
0x10000 +
(((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
utf8.push(
0xf0 | (charcode >> 18),
0x80 | ((charcode >> 12) & 0x3f),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f)
);
}
}
return utf8;
/**
* Converts input into a binary/latin1-encoded array
* @param {*} str
* @return {Number[]}
*/
function toBinaryArray(str) {
if (typeof str === "number") {
// somehow numbers are passed into here from the reader
str = str.toString();
}
if (typeof str !== "string") {
// just in case there are other non-strings passed in
return [];
}
return str.split("").map(char => char.charCodeAt(0)); // split and map to char code
}

function toInt(val) {
Expand Down Expand Up @@ -118,13 +100,13 @@ class BufferStream {

writeString(value) {
value = value || "";
var utf8 = toUTF8Array(value),
bytelen = utf8.length;
var bin = toBinaryArray(value),
bytelen = bin.length;

this.checkSize(bytelen);
var startOffset = this.offset;
for (var i = 0; i < bytelen; i++) {
this.view.setUint8(startOffset, utf8[i]);
this.view.setUint8(startOffset, bin[i]);
startOffset++;
}
return this.increment(bytelen);
Expand Down