find-box.js 1.1 KB

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