Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: pointers #17

Merged
merged 4 commits into from
May 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/.vscode
31 changes: 31 additions & 0 deletions types/pointer/pointer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { AlignedType } from "../types.ts";
import { endianess } from "../../utils.ts";

export class Pointer<T> implements AlignedType<T> {
byteLength = 8;
byteAlign = 8;
JinWeiTan marked this conversation as resolved.
Show resolved Hide resolved
type;
endian;

constructor(type: AlignedType<T>, endian = endianess) {
this.type = type;
this.endian = endian;
}

read(dataView: DataView, byteOffset = 0): T {
const ptr = dataView.getBigUint64(byteOffset, this.endian);
const view = new Deno.UnsafePointerView(Deno.UnsafePointer.create(ptr)!);
const bufview = new DataView(view.getArrayBuffer(this.type.byteLength));
return this.type.read(bufview);
}

write(value: T, dataView: DataView, byteOffset = 0) {
const buffer = new ArrayBuffer(this.type.byteLength);
this.type.write(value, new DataView(buffer))
const ptr = Deno.UnsafePointer.value(Deno.UnsafePointer.of(buffer));
dataView.setBigUint64(byteOffset, BigInt(ptr), this.endian);
return dataView.buffer;
}
}

export const pointer = <T>(type: AlignedType<T>) => new Pointer(type);
JinWeiTan marked this conversation as resolved.
Show resolved Hide resolved