You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.1 KiB

7 years ago
  1. /*!
  2. * range-parser
  3. * Copyright(c) 2012-2014 TJ Holowaychuk
  4. * MIT Licensed
  5. */
  6. 'use strict';
  7. /**
  8. * Module exports.
  9. * @public
  10. */
  11. module.exports = rangeParser;
  12. /**
  13. * Parse "Range" header `str` relative to the given file `size`.
  14. *
  15. * @param {Number} size
  16. * @param {String} str
  17. * @return {Array}
  18. * @public
  19. */
  20. function rangeParser(size, str) {
  21. var valid = true;
  22. var i = str.indexOf('=');
  23. if (-1 == i) return -2;
  24. var arr = str.slice(i + 1).split(',').map(function(range){
  25. var range = range.split('-')
  26. , start = parseInt(range[0], 10)
  27. , end = parseInt(range[1], 10);
  28. // -nnn
  29. if (isNaN(start)) {
  30. start = size - end;
  31. end = size - 1;
  32. // nnn-
  33. } else if (isNaN(end)) {
  34. end = size - 1;
  35. }
  36. // limit last-byte-pos to current length
  37. if (end > size - 1) end = size - 1;
  38. // invalid
  39. if (isNaN(start)
  40. || isNaN(end)
  41. || start > end
  42. || start < 0) valid = false;
  43. return {
  44. start: start,
  45. end: end
  46. };
  47. });
  48. arr.type = str.slice(0, i);
  49. return valid ? arr : -1;
  50. }