1 | 'use strict';
|
---|
2 |
|
---|
3 | var callBound = require('call-bind/callBound');
|
---|
4 |
|
---|
5 | var $RangeError = require('es-errors/range');
|
---|
6 | var $TypeError = require('es-errors/type');
|
---|
7 |
|
---|
8 | var $charAt = callBound('String.prototype.charAt');
|
---|
9 | var $reverse = callBound('Array.prototype.reverse');
|
---|
10 | var $slice = callBound('Array.prototype.slice');
|
---|
11 |
|
---|
12 | var hasOwnProperty = require('./HasOwnProperty');
|
---|
13 | var IsArray = require('./IsArray');
|
---|
14 |
|
---|
15 | var bytesAsFloat32 = require('../helpers/bytesAsFloat32');
|
---|
16 | var bytesAsFloat64 = require('../helpers/bytesAsFloat64');
|
---|
17 | var bytesAsInteger = require('../helpers/bytesAsInteger');
|
---|
18 | var every = require('../helpers/every');
|
---|
19 | var isByteValue = require('../helpers/isByteValue');
|
---|
20 |
|
---|
21 | var keys = require('object-keys');
|
---|
22 |
|
---|
23 | // https://262.ecma-international.org/8.0/#table-50
|
---|
24 | var TypeToSizes = {
|
---|
25 | __proto__: null,
|
---|
26 | Int8: 1,
|
---|
27 | Uint8: 1,
|
---|
28 | Uint8C: 1,
|
---|
29 | Int16: 2,
|
---|
30 | Uint16: 2,
|
---|
31 | Int32: 4,
|
---|
32 | Uint32: 4,
|
---|
33 | Float32: 4,
|
---|
34 | Float64: 8
|
---|
35 | };
|
---|
36 |
|
---|
37 | // https://262.ecma-international.org/8.0/#sec-rawbytestonumber
|
---|
38 |
|
---|
39 | module.exports = function RawBytesToNumber(type, rawBytes, 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 (!IsArray(rawBytes) || !every(rawBytes, isByteValue)) {
|
---|
44 | throw new $TypeError('Assertion failed: `rawBytes` must be an Array of bytes');
|
---|
45 | }
|
---|
46 | if (typeof isLittleEndian !== 'boolean') {
|
---|
47 | throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
|
---|
48 | }
|
---|
49 |
|
---|
50 | var elementSize = TypeToSizes[type]; // step 1
|
---|
51 |
|
---|
52 | if (rawBytes.length !== elementSize) {
|
---|
53 | // this assertion is not in the spec, but it'd be an editorial error if it were ever violated
|
---|
54 | throw new $RangeError('Assertion failed: `rawBytes` must have a length of ' + elementSize + ' for type ' + type);
|
---|
55 | }
|
---|
56 |
|
---|
57 | // eslint-disable-next-line no-param-reassign
|
---|
58 | rawBytes = $slice(rawBytes, 0, elementSize);
|
---|
59 | if (!isLittleEndian) {
|
---|
60 | $reverse(rawBytes); // step 2
|
---|
61 | }
|
---|
62 |
|
---|
63 | if (type === 'Float32') { // step 3
|
---|
64 | return bytesAsFloat32(rawBytes);
|
---|
65 | }
|
---|
66 |
|
---|
67 | if (type === 'Float64') { // step 4
|
---|
68 | return bytesAsFloat64(rawBytes);
|
---|
69 | }
|
---|
70 |
|
---|
71 | return bytesAsInteger(rawBytes, elementSize, $charAt(type, 0) === 'U', false);
|
---|
72 | };
|
---|