From: Feross Aboukhadijeh Date: Thu, 17 Jul 2014 05:51:36 +0000 (-0700) Subject: remove private clamp and coerce functions X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=34f83369a7f43c101b14b33ae21f0a53e5ab6561;p=buffer.git remove private clamp and coerce functions made the constructor and `slice` match node’s implementation more closely --- diff --git a/index.js b/index.js index b3e3d41..746ecfd 100644 --- a/index.js +++ b/index.js @@ -53,18 +53,16 @@ function Buffer (subject, encoding, noZero) { var type = typeof subject - if (encoding === 'base64' && type === 'string') { - subject = base64clean(subject) - } - // Find the length var length if (type === 'number') - length = coerce(subject) - else if (type === 'string') + length = subject > 0 ? subject >>> 0 : 0 + else if (type === 'string') { + if (encoding === 'base64') + subject = base64clean(subject) length = Buffer.byteLength(subject, encoding) - else if (type === 'object') - length = coerce(subject.length) // assume that object is array-like + } else if (type === 'object') // assume object is array-like + length = +subject.length > 0 ? Math.floor(+subject.length) : 0 else throw new Error('First argument needs to be a number, array or string.') @@ -473,8 +471,27 @@ function utf16leSlice (buf, start, end) { Buffer.prototype.slice = function (start, end) { var len = this.length - start = clamp(start, len, 0) - end = clamp(end, len, len) + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len; + if (start < 0) + start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) + end = 0 + } else if (end > len) { + end = len + } + + if (end < start) + end = start if (Buffer._useTypedArrays) { return Buffer._augment(this.subarray(start, end)) @@ -1028,25 +1045,6 @@ function stringtrim (str) { return str.replace(/^\s+|\s+$/g, '') } -// slice(start, end) -function clamp (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index; // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} - -function coerce (length) { - // Coerce length to a number (possibly NaN), round up - // in case it's fractional (e.g. 123.456) then do a - // double negate to coerce a NaN to 0. Easy, right? - length = ~~Math.ceil(+length) - return length < 0 ? 0 : length -} - function isArray (subject) { return (Array.isArray || function (subject) { return Object.prototype.toString.call(subject) === '[object Array]'