NumericToRawBytes.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var hasOwnProperty = require('./HasOwnProperty');
  4. var ToBigInt64 = require('./ToBigInt64');
  5. var ToBigUint64 = require('./ToBigUint64');
  6. var ToInt16 = require('./ToInt16');
  7. var ToInt32 = require('./ToInt32');
  8. var ToInt8 = require('./ToInt8');
  9. var ToUint16 = require('./ToUint16');
  10. var ToUint32 = require('./ToUint32');
  11. var ToUint8 = require('./ToUint8');
  12. var ToUint8Clamp = require('./ToUint8Clamp');
  13. var valueToFloat16Bytes = require('../helpers/valueToFloat16Bytes');
  14. var valueToFloat32Bytes = require('../helpers/valueToFloat32Bytes');
  15. var valueToFloat64Bytes = require('../helpers/valueToFloat64Bytes');
  16. var integerToNBytes = require('../helpers/integerToNBytes');
  17. var tableTAO = require('./tables/typed-array-objects');
  18. // https://262.ecma-international.org/15.0/#table-the-typedarray-constructors
  19. var TypeToAO = {
  20. __proto__: null,
  21. $INT8: ToInt8,
  22. $UINT8: ToUint8,
  23. $UINT8C: ToUint8Clamp,
  24. $INT16: ToInt16,
  25. $UINT16: ToUint16,
  26. $INT32: ToInt32,
  27. $UINT32: ToUint32,
  28. $BIGINT64: ToBigInt64,
  29. $BIGUINT64: ToBigUint64
  30. };
  31. // https://262.ecma-international.org/16.0/#sec-numerictorawbytes
  32. module.exports = function NumericToRawBytes(type, value, isLittleEndian) {
  33. if (typeof type !== 'string' || !hasOwnProperty(tableTAO.size, '$' + type)) {
  34. throw new $TypeError('Assertion failed: `type` must be a TypedArray element type');
  35. }
  36. if (typeof value !== 'number' && typeof value !== 'bigint') {
  37. throw new $TypeError('Assertion failed: `value` must be a Number or a BigInt');
  38. }
  39. if (typeof isLittleEndian !== 'boolean') {
  40. throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
  41. }
  42. if (type === 'FLOAT16') { // step 1
  43. return valueToFloat16Bytes(value, isLittleEndian);
  44. } else if (type === 'FLOAT32') { // step 2
  45. return valueToFloat32Bytes(value, isLittleEndian);
  46. } else if (type === 'FLOAT64') { // step 3
  47. return valueToFloat64Bytes(value, isLittleEndian);
  48. } // step 4
  49. var n = tableTAO.size['$' + type]; // step 4.a
  50. var convOp = TypeToAO['$' + type]; // step 4.b
  51. var intValue = convOp(value); // step 4.c
  52. return integerToNBytes(intValue, n, isLittleEndian); // step 4.d, 4.e, 5
  53. };