NumericToRawBytes.js 2.2 KB

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