From 4aca74566e861cef0f902602501bf274ba5c43f8 Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Mon, 4 Sep 2023 13:01:40 +0100 Subject: Bitwise int functions --- src/gleam_stdlib.mjs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'src/gleam_stdlib.mjs') diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs index a2fbaa6..fb255d9 100644 --- a/src/gleam_stdlib.mjs +++ b/src/gleam_stdlib.mjs @@ -752,3 +752,32 @@ function try_get_field(value, field, or_else) { export function byte_size(string) { return new TextEncoder().encode(string).length; } + +// In Javascript bitwise operations convert numbers to a sequence of 32 bits +// while Erlang uses arbitrary precision. +// To get around this problem and get consistent results use BigInt and then +// downcast the value back to a Number value. + +export function bitwise_and(x, y) { + return Number(BigInt(x) & BigInt(y)); +} + +export function bitwise_not(x) { + return Number(~BigInt(x)); +} + +export function bitwise_or(x, y) { + return Number(BigInt(x) | BigInt(y)); +} + +export function bitwise_exclusive_or(x, y) { + return Number(BigInt(x) ^ BigInt(y)); +} + +export function bitwise_shift_left(x, y) { + return Number(BigInt(x) << BigInt(y)); +} + +export function bitwise_shift_right(x, y) { + return Number(BigInt(x) >> BigInt(y)); +} -- cgit v1.2.3