find-box.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var toUnsigned = require('../utils/bin').toUnsigned;
  2. var parseType = require('./parse-type.js');
  3. var findBox = function(data, path) {
  4. var results = [],
  5. i, size, type, end, subresults;
  6. if (!path.length) {
  7. // short-circuit the search for empty paths
  8. return null;
  9. }
  10. for (i = 0; i < data.byteLength;) {
  11. size = toUnsigned(data[i] << 24 |
  12. data[i + 1] << 16 |
  13. data[i + 2] << 8 |
  14. data[i + 3]);
  15. type = parseType(data.subarray(i + 4, i + 8));
  16. end = size > 1 ? i + size : data.byteLength;
  17. if (type === path[0]) {
  18. if (path.length === 1) {
  19. // this is the end of the path and we've found the box we were
  20. // looking for
  21. results.push(data.subarray(i + 8, end));
  22. } else {
  23. // recursively search for the next box along the path
  24. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  25. if (subresults.length) {
  26. results = results.concat(subresults);
  27. }
  28. }
  29. }
  30. i = end;
  31. }
  32. // we've finished searching all of data
  33. return results;
  34. };
  35. module.exports = findBox;