Optimized chunks flatten

This commit is contained in:
Vitaly Puzrin 2014-02-14 08:09:21 +04:00
parent 8ea9fc4924
commit c78fe44ca1
2 changed files with 33 additions and 19 deletions

View file

@ -126,26 +126,8 @@ function deflate(input, options) {
};
deflator.onEnd = function(error) {
var i, l, len, pos, chunk;
if (error) { throw error; }
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = utils.arrayCreate(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
len = chunk.length;
utils.arraySet(result, chunk, 0, len, pos);
pos += len;
}
result = utils.flattenChunks(chunks);
};
deflator.push(input);

View file

@ -84,6 +84,8 @@ exports.array16Create = function (length) {
};
// Fill Array || Typed Array with constant
//
exports.fill = function (buf, val) {
var len = buf.length;
@ -92,3 +94,33 @@ exports.fill = function (buf, val) {
// fastest for untyped Array
while (--len) { buf[len] = val; }
};
// Join array of chunks to single array.
// Expect Array of (Array(Bytes) || Uint8Array).
//
exports.flattenChunks = function(chunks) {
var i, l, len, pos, chunk, result;
if (typedOk()) {
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
// Fallback for untyped arrays
return [].concat.apply([], chunks);
};