NumberToRawBytes.js 1.9 KB

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