/
bun_compat.js
107 lines (92 loc) 路 2.35 KB
/
bun_compat.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { type } from "node:os";
if (!("Deno" in globalThis) && "Bun" in globalThis) {
const { dlopen, FFIType, CString, JSCallback, ptr } = await import("bun:ffi");
class Deno {
static env = {
get(name) {
return Bun.env[name];
},
};
static build = {
os: type().toLowerCase(),
};
static transformFFIType(type) {
switch (type) {
case "void":
return FFIType.void;
case "i32":
return FFIType.i64_fast;
case "i64":
return FFIType.i64;
case "f32":
return FFIType.f32;
case "f64":
return FFIType.f64;
case "pointer":
case "buffer":
return FFIType.ptr;
case "u32":
return FFIType.u64_fast;
default:
throw new Error("Type not supported: " + type);
}
}
static dlopen(path, symbols) {
const bunSymbols = {};
for (const name in symbols) {
const symbol = symbols[name];
if ("type" in symbol) {
throw new Error("Symbol type not supported");
} else {
bunSymbols[name] = {
args: symbol.parameters.map((type) => this.transformFFIType(type)),
returns: this.transformFFIType(symbol.result),
};
}
}
const lib = dlopen(path, bunSymbols);
return lib;
}
static UnsafeCallback = class UnsafeCallback {
constructor(def, fn) {
this.inner = new JSCallback(fn, {
args: def.parameters.map((type) => Deno.transformFFIType(type)),
returns: Deno.transformFFIType(def.result),
});
this.pointer = this.inner.ptr;
}
close() {
this.inner.close();
}
};
static UnsafePointerView = class UnsafePointerView {
static getCString(ptr) {
return new CString(ptr);
}
constructor(ptr) {
this.ptr = ptr;
}
getCString() {
return new CString(this.ptr);
}
};
static UnsafePointer = class UnsafePointer {
static equals(a, b) {
return a === b;
}
static create(a) {
return Number(a);
}
static of(buf) {
return ptr(buf);
}
static value(ptr) {
return ptr;
}
};
static test(name, fn) {
globalThis.DenoTestCompat(name, fn);
}
}
globalThis.Deno = Deno;
}