summaryrefslogtreecommitdiff
path: root/cli/js/ops/io.ts
blob: b4ef837e014daedef5d0378fe167d340368af62b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import { sendAsyncMinimal, sendSyncMinimal } from "./dispatch_minimal.ts";
// TODO(bartlomieju): remove this import and maybe lazy-initialize
// OPS_CACHE that belongs only to this module
import { OPS_CACHE } from "../runtime.ts";

// This is done because read/write are extremely performance sensitive.
let OP_READ = -1;
let OP_WRITE = -1;

export function readSync(rid: number, buffer: Uint8Array): number | null {
  if (buffer.length == 0) {
    return 0;
  }
  if (OP_READ < 0) {
    OP_READ = OPS_CACHE["op_read"];
  }
  const nread = sendSyncMinimal(OP_READ, rid, buffer);
  if (nread < 0) {
    throw new Error("read error");
  } else if (nread == 0) {
    return null;
  } else {
    return nread;
  }
}

export async function read(
  rid: number,
  buffer: Uint8Array
): Promise<number | null> {
  if (buffer.length == 0) {
    return 0;
  }
  if (OP_READ < 0) {
    OP_READ = OPS_CACHE["op_read"];
  }
  const nread = await sendAsyncMinimal(OP_READ, rid, buffer);
  if (nread < 0) {
    throw new Error("read error");
  } else if (nread == 0) {
    return null;
  } else {
    return nread;
  }
}

export function writeSync(rid: number, data: Uint8Array): number {
  if (OP_WRITE < 0) {
    OP_WRITE = OPS_CACHE["op_write"];
  }
  const result = sendSyncMinimal(OP_WRITE, rid, data);
  if (result < 0) {
    throw new Error("write error");
  } else {
    return result;
  }
}

export async function write(rid: number, data: Uint8Array): Promise<number> {
  if (OP_WRITE < 0) {
    OP_WRITE = OPS_CACHE["op_write"];
  }
  const result = await sendAsyncMinimal(OP_WRITE, rid, data);
  if (result < 0) {
    throw new Error("write error");
  } else {
    return result;
  }
}