NumericToRawBytes.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 valueToFloat32Bytes = require('../helpers/valueToFloat32Bytes');
  14. var valueToFloat64Bytes = require('../helpers/valueToFloat64Bytes');
  15. var integerToNBytes = require('../helpers/integerToNBytes');
  16. var tableTAO = require('./tables/typed-array-objects');
  17. // https://262.ecma-international.org/11.0/#table-the-typedarray-constructors
  18. var TypeToAO = {
  19. __proto__: null,
  20. $Int8: ToInt8,
  21. $Uint8: ToUint8,
  22. $Uint8C: ToUint8Clamp,
  23. $Int16: ToInt16,
  24. $Uint16: ToUint16,
  25. $Int32: ToInt32,
  26. $Uint32: ToUint32,
  27. $BigInt64: ToBigInt64,
  28. $BigUint64: ToBigUint64
  29. };
  30. // https://262.ecma-international.org/11.0/#sec-numerictorawbytes
  31. module.exports = function NumericToRawBytes(type, value, isLittleEndian) {
  32. if (typeof type !== 'string' || !hasOwnProperty(tableTAO.size, '$' + type)) {
  33. throw new $TypeError('Assertion failed: `type` must be a TypedArray element type');
  34. }
  35. if (typeof value !== 'number' && typeof value !== 'bigint') {
  36. throw new $TypeError('Assertion failed: `value` must be a Number or a BigInt');
  37. }
  38. if (typeof isLittleEndian !== 'boolean') {
  39. throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
  40. }
  41. if (type === 'Float32') { // step 1
  42. return valueToFloat32Bytes(value, isLittleEndian);
  43. } else if (type === 'Float64') { // step 2
  44. return valueToFloat64Bytes(value, isLittleEndian);
  45. } // step 3
  46. var n = tableTAO.size['$' + type]; // step 3.a
  47. var convOp = TypeToAO['$' + type]; // step 3.b
  48. var intValue = convOp(value); // step 3.c
  49. return integerToNBytes(intValue, n, isLittleEndian); // step 3.d, 3.e, 4
  50. };