Skip to content

Commit

Permalink
perpare for more compact bit operations in JS (nim-lang#16728)
Browse files Browse the repository at this point in the history
  • Loading branch information
ringabout authored and ardek66 committed Mar 26, 2021
1 parent 817faaa commit 9cbfb68
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
15 changes: 8 additions & 7 deletions lib/pure/math.nim
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,15 @@ func isNaN*(x: SomeFloat): bool {.inline, since: (1,5,1).} =
else: result = c_isnan(x)

when defined(js):
import std/private/jsutils

proc toBitsImpl(x: float): array[2, uint32] =
asm """
const buffer = new ArrayBuffer(8);
const floatBuffer = new Float64Array(buffer);
const uintBuffer = new Uint32Array(buffer);
floatBuffer[0] = `x`;
`result` = uintBuffer
"""
let buffer = newArrayBuffer(8)
let floatBuffer = newFloat64Array(buffer)
let uintBuffer = newUint32Array(buffer)
floatBuffer[0] = x
{.emit: "`result` = `uintBuffer`;".}
# result = cast[array[2, uint32]](uintBuffer)

proc signbit*(x: SomeFloat): bool {.inline, since: (1, 5, 1).} =
## Returns true if `x` is negative, false otherwise.
Expand Down
12 changes: 12 additions & 0 deletions lib/std/private/jsutils.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
when defined(js):
type
ArrayBuffer* = ref object of JsRoot
Float64Array* = ref object of JsRoot
Uint32Array* = ref object of JsRoot

func newArrayBuffer*(n: int): ArrayBuffer {.importjs: "new ArrayBuffer(#)".}
func newFloat64Array*(buffer: ArrayBuffer): Float64Array {.importjs: "new Float64Array(#)".}
func newUint32Array*(buffer: ArrayBuffer): Uint32Array {.importjs: "new Uint32Array(#)".}

func `[]`*(arr: Uint32Array, i: int): uint32 {.importjs: "#[#]".}
func `[]=`*(arr: Float64Array, i: int, v: float) {.importjs: "#[#] = #".}

0 comments on commit 9cbfb68

Please sign in to comment.