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