Skip to content

Commit

Permalink
perf(parse): cache length, return early (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtextrem authored Oct 2, 2024
1 parent d6f39b0 commit 9e7ca51
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
3 changes: 2 additions & 1 deletion benchmark/parse-top.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@
"support.google.com": "UUU=000=l0llUUlUllU0UlllU0U0U0UlU-Ulll0lUlllU0UUllUUlUUUlllllUUUU-UUllUllU0lUU0U0U00lU0UUlUl0l0lUUlUUUUl0lUU0UUllUlUlUUlUlUUUU0ll0l0UU0lllU0lllUUUU0U0lU0U00l0Ul0UlU-U0UllU00lUUl0U; UUU=000=l0llUUlUllU0UlllU0U0U0UlU-Ulll0lUlllU0UUllUUlUUUlllllUUUU-UUllUllU0lUU0U0U00lU0UUlUl0l0lUUlUUUUl0lUU0UUllUlUlUUlUlUUUU0ll0l0UU0lllU0lllUUUU0U0lU0U00l0Ul0UlU-U0UllU00lUUl0U",
"www.google.com": "0U_UUU=0000-00-00-00; UUU=Ullll0Ullll0U0llUllU00U_lllll0lUUlUl0UllUlUUl0lUlUUUl00UUl; UUU=000=lUU0U0U0U0UllUUUlUUlUUU_UlUll_l0U0UU00lUlUlUlllllUUUl00UllllUU_0ll0UllUllUUU-UUUlllU0UlUlUllUlUllUll00UllU0U00llUUl0lU00lUlUUlllUl_U00UUlU0UU0UllUlUU0lUUlUUUl00lUUlUUUU0ll",
"youtu.be": "UUU=0; UUU=ll0UU-l0lUl; UUUUUUU_UUUU0_UUUU=0_llUUlUllU; UUUUUUU_UUUUUUU_UUUUUUUU=UlUUUlUUUlU%22",
"youtube.com": "UUU=0; UUU=l0_UlUUUlUl; UUUUUUU_UUUU0_UUUU=UUUUlUUUlll; UUUUUUU_UUUUUUU_UUUUUUUU=UlUUUlUUUlU%22"
"youtube.com": "UUU=0; UUU=l0_UlUUUlUl; UUUUUUU_UUUU0_UUUU=UUUUlUUUlll; UUUUUUU_UUUUUUU_UUUUUUUU=UlUUUlUUUlU%22",
"example.com": ""
}
15 changes: 8 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,17 @@ function parse(str, options) {
}

var obj = {};
var opt = options || {};
var dec = opt.decode || decode;

var len = str.length;
// RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.
var max = len - 2;
if (max < 0) return obj;

var dec = (options && options.decode) || decode;
var index = 0;
var eqIdx = 0;
var endIdx = 0;
var len = str.length;
var max = len - 2;

while (index < max) {
do {
eqIdx = str.indexOf('=', index);

// no more cookie pairs
Expand Down Expand Up @@ -142,7 +143,7 @@ function parse(str, options) {
}

index = endIdx + 1
}
} while (index < max);

return obj;
}
Expand Down
4 changes: 4 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ describe('cookie.parse(str)', function () {
assert.deepEqual(cookie.parse('foo=; bar='), { foo: '', bar: '' })
})

it('should parse cookie with minimum length', function () {
assert.deepEqual(cookie.parse('f='), { f: '' })
})

it('should URL-decode values', function () {
assert.deepEqual(cookie.parse('foo="bar=123456789&name=Magic+Mouse"'),
{ foo: 'bar=123456789&name=Magic+Mouse' })
Expand Down

0 comments on commit 9e7ca51

Please # to comment.