Skip to content

Commit

Permalink
Implemented NameTree.get() using binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
timvandermeij committed Oct 6, 2014
1 parent b215af3 commit db8ba13
Showing 1 changed file with 62 additions and 9 deletions.
71 changes: 62 additions & 9 deletions src/core/obj.js
Original file line number Diff line number Diff line change
Expand Up @@ -485,15 +485,7 @@ var Catalog = (function CatalogClosure() {
}
if (nameTreeRef) {
var nameTree = new NameTree(nameTreeRef, xref);
var names = nameTree.getAll();
for (var name in names) {
if (!names.hasOwnProperty(name)) {
continue;
}
if (name === destinationId) {
dest = fetchDestination(names[name]);
}
}
dest = fetchDestination(nameTree.get(destinationId));
}
return dest;
},
Expand Down Expand Up @@ -1398,6 +1390,67 @@ var NameTree = (function NameTreeClosure() {
}
}
return dict;
},

get: function NameTree_get(destinationId) {
if (!this.root) {
return null;
}

var xref = this.xref;
var kidsOrNames = xref.fetchIfRef(this.root);

// Perform a binary search to quickly find the entry that
// contains the named destination we are looking for.
while (kidsOrNames.has('Kids')) {
var kids = kidsOrNames.get('Kids');

if (isArray(kids)) {
var l = 0;
var r = kids.length - 1;

while (l <= r) {
var m = (l + r) >> 1;
var kid = xref.fetchIfRef(kids[m]);
var limits = kid.get('Limits');

if (destinationId < limits[0]) {
r = m - 1;
} else if (destinationId > limits[1]) {
l = m + 1;
} else {
kidsOrNames = xref.fetchIfRef(kids[m]);
break;
}
}
if (l > r) {
return null;
}
}
}

// If we get here, then we have found the right entry. Now
// go through the named destinations in the Named dictionary
// until we find the exact destination we're looking for.
var names = kidsOrNames.get('Names');
if (isArray(names)) {
// Again perform a binary search to reduce the lookup time.
var l = 0;
var r = names.length - 1;

while (l <= r) {
var m = (l + r) & ~1;

if (destinationId < names[m]) {
r = m - 1;
} else if (destinationId > names[m]) {
l = m + 1;
} else {
return xref.fetchIfRef(names[m + 1]);
}
}
}
return null;
}
};
return NameTree;
Expand Down

0 comments on commit db8ba13

Please sign in to comment.