[d565449] | 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 keys = require('object-keys');
|
---|
| 19 |
|
---|
| 20 | // https://262.ecma-international.org/8.0/#table-50
|
---|
| 21 | var TypeToSizes = {
|
---|
| 22 | __proto__: null,
|
---|
| 23 | Int8: 1,
|
---|
| 24 | Uint8: 1,
|
---|
| 25 | Uint8C: 1,
|
---|
| 26 | Int16: 2,
|
---|
| 27 | Uint16: 2,
|
---|
| 28 | Int32: 4,
|
---|
| 29 | Uint32: 4,
|
---|
| 30 | Float32: 4,
|
---|
| 31 | Float64: 8
|
---|
| 32 | };
|
---|
| 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 | };
|
---|
| 44 |
|
---|
| 45 | // https://262.ecma-international.org/8.0/#sec-numbertorawbytes
|
---|
| 46 |
|
---|
| 47 | module.exports = function NumberToRawBytes(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 (typeof value !== 'number') {
|
---|
| 52 | throw new $TypeError('Assertion failed: `value` must be a Number');
|
---|
| 53 | }
|
---|
| 54 | if (typeof isLittleEndian !== 'boolean') {
|
---|
| 55 | throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
|
---|
| 56 | }
|
---|
| 57 |
|
---|
| 58 | if (type === 'Float32') { // step 1
|
---|
| 59 | return valueToFloat32Bytes(value, isLittleEndian);
|
---|
| 60 | } else if (type === 'Float64') { // step 2
|
---|
| 61 | return valueToFloat64Bytes(value, isLittleEndian);
|
---|
| 62 | } // step 3
|
---|
| 63 |
|
---|
| 64 | var n = TypeToSizes[type]; // step 3.a
|
---|
| 65 |
|
---|
| 66 | var convOp = TypeToAO[type]; // step 3.b
|
---|
| 67 |
|
---|
| 68 | var intValue = convOp(value); // step 3.c
|
---|
| 69 |
|
---|
| 70 | return integerToNBytes(intValue, n, isLittleEndian); // step 3.d, 3.e, 4
|
---|
| 71 | };
|
---|