NumberToRawBytes.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var hasOwnProperty = require('./HasOwnProperty');
  5. var ToInt16 = require('./ToInt16');
  6. var ToInt32 = require('./ToInt32');
  7. var ToInt8 = require('./ToInt8');
  8. var ToUint16 = require('./ToUint16');
  9. var ToUint32 = require('./ToUint32');
  10. var ToUint8 = require('./ToUint8');
  11. var ToUint8Clamp = require('./ToUint8Clamp');
  12. var Type = require('./Type');
  13. var valueToFloat32Bytes = require('../helpers/valueToFloat32Bytes');
  14. var valueToFloat64Bytes = require('../helpers/valueToFloat64Bytes');
  15. var integerToNBytes = require('../helpers/integerToNBytes');
  16. var keys = require('object-keys');
  17. // https://262.ecma-international.org/8.0/#table-50
  18. var TypeToSizes = {
  19. __proto__: null,
  20. Int8: 1,
  21. Uint8: 1,
  22. Uint8C: 1,
  23. Int16: 2,
  24. Uint16: 2,
  25. Int32: 4,
  26. Uint32: 4,
  27. Float32: 4,
  28. Float64: 8
  29. };
  30. var TypeToAO = {
  31. __proto__: null,
  32. Int8: ToInt8,
  33. Uint8: ToUint8,
  34. Uint8C: ToUint8Clamp,
  35. Int16: ToInt16,
  36. Uint16: ToUint16,
  37. Int32: ToInt32,
  38. Uint32: ToUint32
  39. };
  40. // https://262.ecma-international.org/8.0/#sec-numbertorawbytes
  41. module.exports = function NumberToRawBytes(type, value, isLittleEndian) {
  42. if (typeof type !== 'string' || !hasOwnProperty(TypeToSizes, type)) {
  43. throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
  44. }
  45. if (Type(value) !== 'Number') {
  46. throw new $TypeError('Assertion failed: `value` must be a Number');
  47. }
  48. if (Type(isLittleEndian) !== 'Boolean') {
  49. throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
  50. }
  51. if (type === 'Float32') { // step 1
  52. return valueToFloat32Bytes(value, isLittleEndian);
  53. } else if (type === 'Float64') { // step 2
  54. return valueToFloat64Bytes(value, isLittleEndian);
  55. } // step 3
  56. var n = TypeToSizes[type]; // step 3.a
  57. var convOp = TypeToAO[type]; // step 3.b
  58. var intValue = convOp(value); // step 3.c
  59. return integerToNBytes(intValue, n, isLittleEndian); // step 3.d, 3.e, 4
  60. };