Skip to content
This repository has been archived by the owner on Feb 29, 2020. It is now read-only.

Commit

Permalink
fix(screenshots): Split bytes into smaller chunks to run through from…
Browse files Browse the repository at this point in the history
…CharCode (#3101)
  • Loading branch information
Mardak committed Aug 8, 2017
1 parent 54a5392 commit 14c051f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
20 changes: 19 additions & 1 deletion system-addon/lib/Screenshots.jsm
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");

this.Screenshots = {
/**
* Convert bytes to a string using extremely fast String.fromCharCode without
* exceeding the max number of arguments that can be provided to a function.
*/
_bytesToString(bytes) {
// NB: This comes from js/src/vm/ArgumentsObject.h ARGS_LENGTH_MAX
const ARGS_LENGTH_MAX = 500 * 1000;
let i = 0;
let str = "";
let {length} = bytes;
while (i < length) {
const start = i;
i += ARGS_LENGTH_MAX;
str += String.fromCharCode.apply(null, bytes.slice(start, i));
}
return str;
},

async getScreenshotForURL(url) {
let screenshot = null;
try {
Expand All @@ -34,7 +52,7 @@ this.Screenshots = {

const contentType = MIMEService.getTypeFromFile(nsFile);
const bytes = await file.read();
const encodedData = btoa(String.fromCharCode.apply(null, bytes));
const encodedData = btoa(this._bytesToString(bytes));
file.close();
screenshot = `data:${contentType};base64,${encodedData}`;
} catch (err) {
Expand Down
23 changes: 23 additions & 0 deletions system-addon/test/unit/lib/Screenshots.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,27 @@ describe("Screenshots", () => {
assert.equal(screenshot, null);
});
});

describe("#_bytesToString", () => {
it("should convert no bytes to empty string", () => {
assert.equal(Screenshots._bytesToString([]), "");
});
it("should convert bytes to a string", () => {
const str = Screenshots._bytesToString([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]);

assert.equal(str, "hello world");
});
it("should convert very many bytes to a long string", () => {
const bytes = [];
for (let i = 0; i < 1000 * 1000; i++) {
bytes.push(9);
}

const str = Screenshots._bytesToString(bytes);

assert.propertyVal(str, 0, "\t");
assert.propertyVal(str, "length", 1000000);
assert.propertyVal(str, 999999, "\u0009");
});
});
});

0 comments on commit 14c051f

Please sign in to comment.