web: Add pushString()

This commit is contained in:
Remko Tronçon 2022-05-14 07:40:48 +02:00
parent 3d3092a24e
commit 5cbbd733ff
2 changed files with 32 additions and 7 deletions

View file

@ -2766,6 +2766,9 @@
(func (export "tos") (result i32) (func (export "tos") (result i32)
(global.get $tos)) (global.get $tos))
(func (export "here" (result i32))
(global.get $here))
(func (export "interpret") (result i32) (func (export "interpret") (result i32)
(local $result i32) (local $result i32)

View file

@ -4,6 +4,8 @@ const isSafari =
typeof navigator != "undefined" && typeof navigator != "undefined" &&
/^((?!chrome|android).)*safari/i.test(navigator.userAgent); /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const PAD_OFFSET = 400;
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
const arrayToBase64 = const arrayToBase64 =
typeof Buffer === "undefined" typeof Buffer === "undefined"
@ -26,6 +28,14 @@ function loadString(memory: WebAssembly.Memory, addr: number, len: number) {
); );
} }
function saveString(s: string, memory: WebAssembly.Memory, addr: number) {
const len = s.length;
const a = new Uint8Array(memory.buffer, addr, len);
for (let i = 0; i < len; ++i) {
a[i] = s.charCodeAt(i);
}
}
/** /**
* JavaScript shell around the WAForth WebAssembly module. * JavaScript shell around the WAForth WebAssembly module.
* *
@ -169,6 +179,14 @@ class WAForth {
memory = this.core.exports.memory as WebAssembly.Memory; memory = this.core.exports.memory as WebAssembly.Memory;
} }
memory(): WebAssembly.Memory {
return this.core!.exports.memory as WebAssembly.Memory;
}
here(): number {
return (this.core!.exports.here as any)() as number;
}
pop(): number { pop(): number {
return (this.core!.exports.pop as any)(); return (this.core!.exports.pop as any)();
} }
@ -176,16 +194,20 @@ class WAForth {
popString(): string { popString(): string {
const len = this.pop(); const len = this.pop();
const addr = this.pop(); const addr = this.pop();
return loadString( return loadString(this.memory(), addr, len);
this.core!.exports.memory as WebAssembly.Memory,
addr,
len
);
} }
push = (n: number): void => { push(n: number): void {
(this.core!.exports.push as any)(n); (this.core!.exports.push as any)(n);
}; }
pushString(s: string, offset = 0): number {
const addr = this.here() + PAD_OFFSET;
saveString(s, this.memory(), addr);
this.push(addr);
this.push(s.length);
return addr + PAD_OFFSET;
}
/** /**
* Read data `s` into the input buffer without interpreting it. * Read data `s` into the input buffer without interpreting it.