1 | // @flow
|
---|
2 |
|
---|
3 | import { write, read } from "@xtuc/ieee754";
|
---|
4 |
|
---|
5 | /**
|
---|
6 | * According to https://webassembly.github.io/spec/binary/values.html#binary-float
|
---|
7 | * n = 32/8
|
---|
8 | */
|
---|
9 | export const NUMBER_OF_BYTE_F32 = 4;
|
---|
10 |
|
---|
11 | /**
|
---|
12 | * According to https://webassembly.github.io/spec/binary/values.html#binary-float
|
---|
13 | * n = 64/8
|
---|
14 | */
|
---|
15 | export const NUMBER_OF_BYTE_F64 = 8;
|
---|
16 |
|
---|
17 | export const SINGLE_PRECISION_MANTISSA = 23;
|
---|
18 |
|
---|
19 | export const DOUBLE_PRECISION_MANTISSA = 52;
|
---|
20 |
|
---|
21 | export function encodeF32(v: number): Array<number> {
|
---|
22 | const buffer = [];
|
---|
23 |
|
---|
24 | write(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
|
---|
25 |
|
---|
26 | return buffer;
|
---|
27 | }
|
---|
28 |
|
---|
29 | export function encodeF64(v: number): Array<number> {
|
---|
30 | const buffer = [];
|
---|
31 |
|
---|
32 | write(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
|
---|
33 |
|
---|
34 | return buffer;
|
---|
35 | }
|
---|
36 |
|
---|
37 | export function decodeF32(bytes: Array<Byte>): number {
|
---|
38 | const buffer = Buffer.from(bytes);
|
---|
39 |
|
---|
40 | return read(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
|
---|
41 | }
|
---|
42 |
|
---|
43 | export function decodeF64(bytes: Array<Byte>): number {
|
---|
44 | const buffer = Buffer.from(bytes);
|
---|
45 |
|
---|
46 | return read(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
|
---|
47 | }
|
---|