RawBytesToNumber.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. var callBound = require('call-bind/callBound');
  3. var $RangeError = require('es-errors/range');
  4. var $TypeError = require('es-errors/type');
  5. var $charAt = callBound('String.prototype.charAt');
  6. var $reverse = callBound('Array.prototype.reverse');
  7. var $slice = callBound('Array.prototype.slice');
  8. var hasOwnProperty = require('./HasOwnProperty');
  9. var IsArray = require('./IsArray');
  10. var bytesAsFloat32 = require('../helpers/bytesAsFloat32');
  11. var bytesAsFloat64 = require('../helpers/bytesAsFloat64');
  12. var bytesAsInteger = require('../helpers/bytesAsInteger');
  13. var every = require('../helpers/every');
  14. var isByteValue = require('../helpers/isByteValue');
  15. var keys = require('object-keys');
  16. // https://262.ecma-international.org/8.0/#table-50
  17. var TypeToSizes = {
  18. __proto__: null,
  19. Int8: 1,
  20. Uint8: 1,
  21. Uint8C: 1,
  22. Int16: 2,
  23. Uint16: 2,
  24. Int32: 4,
  25. Uint32: 4,
  26. Float32: 4,
  27. Float64: 8
  28. };
  29. // https://262.ecma-international.org/8.0/#sec-rawbytestonumber
  30. module.exports = function RawBytesToNumber(type, rawBytes, isLittleEndian) {
  31. if (typeof type !== 'string' || !hasOwnProperty(TypeToSizes, type)) {
  32. throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
  33. }
  34. if (!IsArray(rawBytes) || !every(rawBytes, isByteValue)) {
  35. throw new $TypeError('Assertion failed: `rawBytes` must be an Array of bytes');
  36. }
  37. if (typeof isLittleEndian !== 'boolean') {
  38. throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
  39. }
  40. var elementSize = TypeToSizes[type]; // step 1
  41. if (rawBytes.length !== elementSize) {
  42. // this assertion is not in the spec, but it'd be an editorial error if it were ever violated
  43. throw new $RangeError('Assertion failed: `rawBytes` must have a length of ' + elementSize + ' for type ' + type);
  44. }
  45. // eslint-disable-next-line no-param-reassign
  46. rawBytes = $slice(rawBytes, 0, elementSize);
  47. if (!isLittleEndian) {
  48. $reverse(rawBytes); // step 2
  49. }
  50. if (type === 'Float32') { // step 3
  51. return bytesAsFloat32(rawBytes);
  52. }
  53. if (type === 'Float64') { // step 4
  54. return bytesAsFloat64(rawBytes);
  55. }
  56. return bytesAsInteger(rawBytes, elementSize, $charAt(type, 0) === 'U', false);
  57. };