Skip to content

Commit

Permalink
check key order in dictionaries
Browse files Browse the repository at this point in the history
  • Loading branch information
stbuehler committed Jun 21, 2013
1 parent 04e7440 commit 0bf7a21
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/bencode.js
Expand Up @@ -78,9 +78,6 @@ function findchar(str, pos, c) {

function copy(str, start, len) {
return str.slice(start, start+len);
// var buf = new Buffer(len);
// str.copy(buf, 0, start, start+len);
// return buf;
}

// parse a bencoded string
Expand Down Expand Up @@ -120,9 +117,18 @@ function bparseList(str, pos) {
return [list, pos+1];
}

function compareBuffers(a, b) {
var i, l = Math.min(a.length, b.length);
for (i = 0; i < l; ++i) {
if (a[i] != b[i]) return (a[i] < b[i]) ? -1 : 1;
}
if (a.length === b.length) return 0;
return (a.length < b.length) ? -1 : 1;
}

// parse a bencoded dictionary
function bparseDict(str, pos) {
var key, val, dict = {};
var key, val, dict = {}, oldkey = false, cmpkey;
while (pos < str.length && str.charAt(pos) !== "e") {
key = bparseString(str, pos);
if (null === key) throw new Error("unexpected null element");
Expand All @@ -132,6 +138,13 @@ function bparseDict(str, pos) {
val = bparse(str, pos);
if (null === val) throw new Error("unexpected null element");

if (oldkey !== false) {
cmpkey = compareBuffers(oldkey, key[0]);
if (0 === cmpkey) throw new Error("duplicate key in dictionary");
if (1 === cmpkey) throw new Error("wrong key order in dictionary");
}
oldkey = key[0];

dict[key[0]] = val[0];
pos = val[1];
}
Expand Down
3 changes: 3 additions & 0 deletions lib/test.js
Expand Up @@ -38,3 +38,6 @@ checkDecodeThrows("d3:key5:value", Error, "unexpected end of data");

checkDecodeThrows("l", Error, "unexpected end of data");
checkDecodeThrows("l7:element", Error, "unexpected end of data");

checkDecodeThrows("d3:kez0:3:key0:e", Error, "wrong key order in dictionary");
checkDecodeThrows("d3:key0:3:key0:e", Error, "duplicate key in dictionary");

0 comments on commit 0bf7a21

Please sign in to comment.