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

Adding support for big Uint8Arrays in to_string() (that doesn't split buffers arbitrarily) #58

Merged
merged 1 commit into from
May 31, 2016
Merged
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
49 changes: 49 additions & 0 deletions wrapper/wrap-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,55 @@
return new TextDecoder("utf-8", {fatal: true}).decode(bytes);
}

var numChunks = Math.ceil(bytes.length / toStringChunkSize);
if (numChunks > 1){
var totalString = '';
var sequenceReadOffset = 0;
for (var i = 0; i < numChunks; i++){
var currentChunk = Array.prototype.slice.call(bytes, i * toStringChunkSize + sequenceReadOffset, (i + 1) * toStringChunkSize + sequenceReadOffset);
//Depending on how much we have shifted
if (currentChunk.length == 0) continue;

//Checking that we didn't cut the buffer in the middle of a UTF8 sequence.
//If we did, remove the bytes of the "cut" sequence and
//decrement sequenceReadOffset for each removed byte
var sequenceDetectionComplete;
var sequenceIndex = currentChunk.length;
var sequenceLength = 0;

//This loop will read the chunk from its end, looking for sequence start bytes
do {
sequenceIndex--;
var currentByte = currentChunk[sequenceIndex];

if (currentByte >= 240){ //Beginning of a 4-byte UTF-8 sequence
sequenceLength = 4;
sequenceDetectionComplete = true;
} else if (currentByte >= 224){ //Beginning of a 3-byte UTF-8 sequence
sequenceLength = 3;
sequenceDetectionComplete = true;
} else if (currentByte >= 192){ //Beginning of a 2-byte UTF-8 sequence
sequenceLength = 2;
sequenceDetectionComplete = true;
} else if (currentByte < 128){ //A one byte UTF-8 char
sequenceLength = 1;
sequenceDetectionComplete = true;
}
//The values between [128, 192[ are part of a UTF-8 sequence.
//The loop will not exit in that case, and will iterate one byte backwards instead
} while (!sequenceDetectionComplete);

var extraBytes = sequenceLength - (currentChunk.length - sequenceIndex);
for (var j = 0; j < extraBytes; j++){
sequenceReadOffset--;
currentChunk.pop();
}

totalString += to_string(currentChunk);
}
return totalString;
}

try {
return decodeURIComponent(escape(String.fromCharCode.apply(null, bytes)));
}
Expand Down