Skip to content
Permalink
Newer
Older
100644 74 lines (60 sloc) 1.96 KB
Ignoring revisions in .git-blame-ignore-revs.
1
'use strict';
2
3
var GetIntrinsic = require('get-intrinsic');
4
5
var $TypeError = GetIntrinsic('%TypeError%');
6
7
var hasOwnProperty = require('./HasOwnProperty');
8
var ToInt16 = require('./ToInt16');
9
var ToInt32 = require('./ToInt32');
10
var ToInt8 = require('./ToInt8');
11
var ToUint16 = require('./ToUint16');
12
var ToUint32 = require('./ToUint32');
13
var ToUint8 = require('./ToUint8');
14
var ToUint8Clamp = require('./ToUint8Clamp');
15
var Type = require('./Type');
16
17
var valueToFloat32Bytes = require('../helpers/valueToFloat32Bytes');
18
var valueToFloat64Bytes = require('../helpers/valueToFloat64Bytes');
19
var integerToNBytes = require('../helpers/integerToNBytes');
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
var TypeToAO = {
38
__proto__: null,
39
Int8: ToInt8,
40
Uint8: ToUint8,
41
Uint8C: ToUint8Clamp,
42
Int16: ToInt16,
43
Uint16: ToUint16,
44
Int32: ToInt32,
45
Uint32: ToUint32
46
};
47
48
// https://262.ecma-international.org/8.0/#sec-numbertorawbytes
49
50
module.exports = function NumberToRawBytes(type, value, isLittleEndian) {
51
if (typeof type !== 'string' || !hasOwnProperty(TypeToSizes, type)) {
52
throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
53
}
54
if (Type(value) !== 'Number') {
55
throw new $TypeError('Assertion failed: `value` must be a Number');
56
}
57
if (Type(isLittleEndian) !== 'Boolean') {
58
throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
59
}
60
61
if (type === 'Float32') { // step 1
62
return valueToFloat32Bytes(value, isLittleEndian);
63
} else if (type === 'Float64') { // step 2
64
return valueToFloat64Bytes(value, isLittleEndian);
65
} // step 3
66
67
var n = TypeToSizes[type]; // step 3.a
68
69
var convOp = TypeToAO[type]; // step 3.b
70
71
var intValue = convOp(value); // step 3.c
72
73
return integerToNBytes(intValue, n, isLittleEndian); // step 3.d, 3.e, 4