Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/dylink/src/util.ts
1067 views
1
//import debug from "debug";
2
//const log = debug("dylink:util");
3
4
export function nonzeroPositions(table) {
5
const v: number[] = [];
6
for (let i = 0; i < table.length; i++) {
7
if (table.get(i) != null) {
8
v.push(i);
9
}
10
}
11
return v;
12
}
13
14
const textDecoder = new TextDecoder(); // utf-8
15
const encoder = new TextEncoder();
16
17
export function recvString(
18
charPtr: number,
19
memory: WebAssembly.Memory
20
): string {
21
const len = strlen(charPtr, memory);
22
const slice = memory.buffer.slice(charPtr, charPtr + len);
23
return textDecoder.decode(slice);
24
}
25
26
// encode as utf8 and copy string into pre-allocated memory buffer as null terminated.
27
export function sendString(
28
str: string,
29
charPtr: number, // pre-allocated memory in which to put str; it better be big enough.
30
memory: WebAssembly.Memory
31
) {
32
const strAsArray = encoder.encode(str);
33
const len = strAsArray.length + 1;
34
const array = new Int8Array(memory.buffer, charPtr, len);
35
array.set(strAsArray);
36
array[len - 1] = 0;
37
}
38
39
export function strlen(charPtr: number, memory: WebAssembly.Memory): number {
40
const mem = new Uint8Array(memory.buffer);
41
let i = charPtr;
42
while (mem[i]) {
43
i += 1;
44
}
45
return i - charPtr;
46
}
47
48
export function alignMemory(size: number, alignment: number): number {
49
return Math.ceil(size / alignment) * alignment;
50
}
51
52
export function MBtoPages(MB): number {
53
// "Note: A WebAssembly page has a constant size of 65,536 bytes, i.e., 64KiB." from
54
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/Memory
55
// There's thus 1025/64 = 16 pages in a MB.
56
return MB * 16;
57
}
58
59