find-box.js 1.1 KB

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