RawBytesToNumber.js 2.2 KB

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