-
- Notifications
You must be signed in to change notification settings - Fork 677
Description
In many cases, I find it useful to have type-checked pointers (as opposed to just usize
) to make sure that values loaded / stored in memory are indeed correct for the given pointer across the FFI boundary.
I've seen #1228, and, in particular the Pointer experiment reference there (https://github.com/AssemblyScript/assemblyscript/blob/master/tests/compiler/std/pointer.ts#L3) and I think it's a nice high-level API, but perhaps unnecessarily high-level for majority of cases.
On the other hand, the current primitives (load
/ store
) are too low-level - they don't provide any typechecking whatsoever, and allow storing arbitrary data to arbitrary pointers.
I propose a solution somewhere in between these two that I've come to use myself - a primitive for opaque pointers:
@final //@ts-ignore: decorators class ptr<T> { deref: T; }
This doesn't provide nice high-level APIs for pointer arithmetic, but in many cases it's not necessary. Often enough, as a user, you simply want to accept an opaque typechecked pointer (which is represented as usize
under the hood), and read or write data to it, and be done with it. This is what such class provides.
class
is already represented by AssemblyScript as a pointer to the actual data, and in this case data is whatever the T
is, so you can read and write data via such helper by simply:
export function doSomethingWithFloat(f: ptr<f32>): void { // read float let float = f.deref; // ...do something // write float f.deref = float * float; }
Compare this to a "raw" solution:
export function doSomethingWithFloat2(f: usize): void { let float = load<f32>(f); // ...do something // write float store<f32>(f, float * float); }
Both compile to precisely same code (in fact, they get merged by Binaryen if put in the same file), but in the latter case it's too easy for different invocations on the same pointer to accidentally get out of sync in terms of types, as well as public API is less clear on what f
is supposed to contain.
Anyway, just thought I'd post this and would love to hear your thoughts.