You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
1000 B

4 years ago
  1. import { write, read } from "@xtuc/ieee754";
  2. /**
  3. * According to https://webassembly.github.io/spec/binary/values.html#binary-float
  4. * n = 32/8
  5. */
  6. export var NUMBER_OF_BYTE_F32 = 4;
  7. /**
  8. * According to https://webassembly.github.io/spec/binary/values.html#binary-float
  9. * n = 64/8
  10. */
  11. export var NUMBER_OF_BYTE_F64 = 8;
  12. export var SINGLE_PRECISION_MANTISSA = 23;
  13. export var DOUBLE_PRECISION_MANTISSA = 52;
  14. export function encodeF32(v) {
  15. var buffer = [];
  16. write(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
  17. return buffer;
  18. }
  19. export function encodeF64(v) {
  20. var buffer = [];
  21. write(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
  22. return buffer;
  23. }
  24. export function decodeF32(bytes) {
  25. var buffer = Buffer.from(bytes);
  26. return read(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32);
  27. }
  28. export function decodeF64(bytes) {
  29. var buffer = Buffer.from(bytes);
  30. return read(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64);
  31. }