char/avril

(wip) why'd you have to go and make things so complicaaaaated?

git clone https://git.t4t.associates/char/avril

Charlotte Somport stdio extension to typescriptf20b64f

main
1.4 KiB49 linesraw
1import {
2  ObjectFreeze,
3  TypedArrayPrototypeGetByteLength as length,
4  TypedArrayPrototypeGetTag as tag,
5  TypeError,
6  Uint8Array,
7  Uint8ArrayPrototypeSet as setBytes,
8} from "ext:core/primordials";
9import { op_stdio_read_sync, op_stdio_write_sync } from "ext:core/ops";
10import { array } from "ext:web/idl.js";
11import { result } from "ext:file/errors.js";
12
13const empty = new Uint8Array();
14
15export const stdin = ObjectFreeze({
16  read(buffer: Uint8Array<ArrayBufferLike>): number | null {
17    if (tag(buffer) !== "Uint8Array") {
18      throw new TypeError("Stdin reads require a Uint8Array");
19    }
20    setBytes(buffer, empty);
21    const chunk = result(op_stdio_read_sync(length(buffer)));
22    setBytes(buffer, empty);
23    if (chunk === null) return null;
24    setBytes(buffer, chunk);
25    return length(chunk);
26  },
27});
28
29function write(stderr: boolean, bytes: Uint8Array<ArrayBufferLike>): number {
30  if (tag(bytes) !== "Uint8Array") {
31    throw new TypeError("Stdio writes require a Uint8Array");
32  }
33  const args = array() as [boolean, Uint8Array<ArrayBuffer>];
34  args[0] = stderr;
35  args[1] = new Uint8Array(bytes);
36  return result(op_stdio_write_sync(args));
37}
38
39export const stdout = ObjectFreeze({
40  write(bytes: Uint8Array<ArrayBufferLike>) {
41    return write(false, bytes);
42  },
43});
44
45export const stderr = ObjectFreeze({
46  write(bytes: Uint8Array<ArrayBufferLike>) {
47    return write(true, bytes);
48  },
49});