Skip to content

Commit c681bda

Browse files
committed
extract magic constant, add [0,len] special case
1 parent fd60fb3 commit c681bda

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

index.js

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -622,16 +622,6 @@ function base64Slice (buf, start, end) {
622622
}
623623
}
624624

625-
function decodeCodePointsArray (buf) {
626-
var len = buf.length
627-
628-
if (len <= 0x10000) {
629-
return String.fromCharCode.apply(String, buf) // avoid extra slice()
630-
}
631-
632-
return binarySlice(buf, 0, len)
633-
}
634-
635625
function utf8Slice (buf, start, end) {
636626
end = Math.min(buf.length, end)
637627
var res = []
@@ -700,7 +690,7 @@ function utf8Slice (buf, start, end) {
700690
i += bytesPerSequence
701691
}
702692

703-
return decodeCodePointsArray(res)
693+
return binarySlice(res, 0, res.length)
704694
}
705695

706696
function asciiSlice (buf, start, end) {
@@ -713,17 +703,28 @@ function asciiSlice (buf, start, end) {
713703
return ret
714704
}
715705

706+
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
707+
// the lowest limit is Chrome, with 0x10000 args.
708+
var MAX_ARGUMENTS_LENGTH = 0x10000
709+
716710
function binarySlice (buf, start, end) {
717-
var chunk = 0x10000
711+
var len = buf.length
712+
end = Math.min(len, end)
713+
714+
// TODO: verify, this is probably the average case
715+
if (start === 0 && end === len && end <= MAX_ARGUMENTS_LENGTH) {
716+
return String.fromCharCode.apply(String, buf)
717+
}
718+
718719
var res = ''
719720

720721
// Decode in chunks to avoid "call stack size exceeded".
721-
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
722-
// the lowest limit is Chrome, with 0x10000 args.
723-
for (var i = start; i < end; i += chunk) {
724-
var chunkEnd = Math.min(end, i + chunk)
722+
for (var i = start; i < end; i += MAX_ARGUMENTS_LENGTH) {
723+
var chunkEnd = Math.min(i + MAX_ARGUMENTS_LENGTH, end)
724+
725725
res += String.fromCharCode.apply(String, buf.slice(i, chunkEnd))
726726
}
727+
727728
return res
728729
}
729730

0 commit comments

Comments
 (0)