Skip to content

Commit be8af85

Browse files
authored
Parse the boot index of each module the first time a path in it is read (#31)
1 parent 46500d8 commit be8af85

3 files changed

Lines changed: 119 additions & 29 deletions

File tree

‎scripts/build-web.ts‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ const inJavacPack = new Set(javacFiles);
129129
// says where each file is, so the worker can stat and list offline. Files of a
130130
// package sit together, so one block read serves several classes.
131131
const lines: string[] = [];
132+
// a module's file lines, which a start parses only once it reads that module
133+
const moduleLines = new Map<string, string[]>();
132134
// jdk.localedata's lines go in jdk/jdk.localedata.txt, which a page fetches only with localeData on
133135
const localeLines: string[] = [];
134136
const images = new Map<string, { parts: Uint8Array[]; size: number }>();
@@ -147,7 +149,13 @@ const walk = (dir: string) => {
147149
const name = imageOf(rel);
148150
let image = images.get(name);
149151
if (!image) images.set(name, (image = { parts: [], size: 0 }));
150-
out.push(`f ${rel} ${st.size} ${name}:${image.size}${inJavacPack.has(rel) ? " javac" : ""}`);
152+
const module = out === lines ? /^\/modules\/([^/]+)\//.exec(rel)?.[1] : undefined;
153+
let fileLines = out;
154+
if (module) {
155+
fileLines = moduleLines.get(module) ?? [];
156+
moduleLines.set(module, fileLines);
157+
}
158+
fileLines.push(`f ${rel} ${st.size} ${name}:${image.size}${inJavacPack.has(rel) ? " javac" : ""}`);
151159
image.parts.push(readFileSync(p));
152160
image.size += st.size;
153161
}
@@ -181,18 +189,21 @@ function writePack(file: string, entries: [string, Uint8Array][]) {
181189
return `${(size / 1024).toFixed(0)} KB, ${entries.length} files`;
182190
}
183191

184-
let previous = "";
185-
const compactIndex = lines.map((line) => {
186-
let n = 0;
187-
while (n < line.length && line[n] === previous[n]) n++;
188-
// Keep surrogate pairs together when encoding the suffix as UTF-8.
189-
if (n > 0 && line.charCodeAt(n - 1) >= 0xd800 && line.charCodeAt(n - 1) <= 0xdbff) n--;
190-
const result = `${n} ${line.slice(n)}`;
191-
previous = line;
192-
return result;
193-
}).join("\n");
192+
// Each line as the length it shares with the line before, then the rest.
193+
function prefixCode(lines: string[]) {
194+
let previous = "";
195+
return enc.encode(lines.map((line) => {
196+
let n = 0;
197+
while (n < line.length && line[n] === previous[n]) n++;
198+
// Keep surrogate pairs together when encoding the suffix as UTF-8.
199+
if (n > 0 && line.charCodeAt(n - 1) >= 0xd800 && line.charCodeAt(n - 1) <= 0xdbff) n--;
200+
previous = line;
201+
return `${n} ${line.slice(n)}`;
202+
}).join("\n"));
203+
}
194204
const boot = writePack(join(dist, "boot.pack"), [
195-
["/index.prefix", enc.encode(compactIndex)],
205+
["/index.prefix", prefixCode(lines)],
206+
...[...moduleLines].map(([m, l]): [string, Uint8Array] => [`/index/${m}.prefix`, prefixCode(l)]),
196207
...[...recorder.seen].sort().map((p): [string, Uint8Array] => [p, recorder.read(p)!]),
197208
]);
198209
const javacPack = writePack(join(dist, "jdk", "javac.pack"), javacFiles.map((p) => [p, javacRecorder.read(p)!]));

‎src/browser/http.ts‎

Lines changed: 78 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type { Backend, Stat } from "../fs.ts";
77
export interface Pack {
88
files: Map<string, Uint8Array>;
99
// path -> size, or -1 for directories
10-
index: Map<string, number> | null;
10+
index: PackIndex | null;
1111
// path -> name of the lazily fetched pack that holds it
1212
lazy: Map<string, string>;
1313
// path -> the image file holding it and its offset there
@@ -37,33 +37,91 @@ export function parsePack(buf: ArrayBuffer): Pack {
3737
const pack: Pack = { files, index: null, lazy: new Map(), offsets: new Map() };
3838
const raw = files.get("/index.prefix") ?? files.get("/index.txt");
3939
if (raw) {
40-
pack.index = new Map([["/", -1]]);
40+
pack.index = new PackIndex(pack);
4141
addIndex(pack, dec.decode(raw), files.has("/index.prefix"));
4242
files.delete("/index.txt");
4343
files.delete("/index.prefix");
44+
for (const [p, data] of files) {
45+
if (!p.startsWith("/index/")) continue;
46+
pack.index.modules.set(p.slice(7, -7), data);
47+
files.delete(p);
48+
}
4449
}
4550
return pack;
4651
}
4752

48-
// Adds index lines to a pack that has an index.
53+
// A pack's index. A module's file lines ("/index/<module>.prefix") are parsed
54+
// the first time a path in that module is looked up, since a start reads few
55+
// of the image's modules.
56+
export class PackIndex extends Map<string, number> {
57+
readonly modules = new Map<string, Uint8Array>();
58+
private readonly pack: Pack;
59+
60+
constructor(pack: Pack) {
61+
super([["/", -1]]);
62+
this.pack = pack;
63+
}
64+
65+
override get(path: string) {
66+
this.load(path);
67+
return super.get(path);
68+
}
69+
70+
override has(path: string) {
71+
this.load(path);
72+
return super.has(path);
73+
}
74+
75+
// Parses the lines of the module path is in. The module directories
76+
// themselves are in the main index.
77+
load(path: string) {
78+
if (this.modules.size === 0 || !path.startsWith("/modules/")) return;
79+
const end = path.indexOf("/", 9);
80+
if (end < 0) return;
81+
const module = path.slice(9, end);
82+
const raw = this.modules.get(module);
83+
if (!raw) return;
84+
this.modules.delete(module);
85+
addIndex(this.pack, new TextDecoder().decode(raw), true);
86+
}
87+
}
88+
89+
// Adds index lines to a pack that has an index. Runs on every start, so it
90+
// scans with indexOf rather than split and regexes.
4991
export function addIndex(pack: Pack, text: string, prefix = false) {
92+
const index = pack.index!;
93+
const images = new Map<string, string>();
5094
let previous = "";
51-
for (let line of text.split("\n")) {
95+
for (let s = 0; s < text.length;) {
96+
let e = text.indexOf("\n", s);
97+
if (e < 0) e = text.length;
98+
let line = text.slice(s, e);
99+
s = e + 1;
52100
if (prefix) {
53101
const space = line.indexOf(" ");
54-
line = previous.slice(0, Number(line.slice(0, space))) + line.slice(space + 1);
102+
line = previous.slice(0, +line.slice(0, space)) + line.slice(space + 1);
55103
previous = line;
56104
}
57-
const [kind, path, size, ...rest] = line.split(" ");
58-
if (kind === "d") pack.index!.set(path, -1);
59-
else if (kind === "f") {
60-
pack.index!.set(path, Number(size));
61-
const at = rest[0] === undefined ? null : /^([^:]+):(\d+)$/.exec(rest[0]);
62-
if (at) {
63-
pack.offsets.set(path, { image: `/${at[1]}.jar`, at: Number(at[2]) });
64-
rest.shift();
105+
const a = line.indexOf(" ", 2);
106+
const path = a < 0 ? line.slice(2) : line.slice(2, a);
107+
if (line[0] === "d") index.set(path, -1);
108+
else if (line[0] === "f") {
109+
let b = line.indexOf(" ", a + 1);
110+
if (b < 0) b = line.length;
111+
index.set(path, +line.slice(a + 1, b));
112+
if (b === line.length) continue;
113+
let c = line.indexOf(" ", b + 1);
114+
if (c < 0) c = line.length;
115+
const colon = line.lastIndexOf(":", c);
116+
if (colon > b) {
117+
const module = line.slice(b + 1, colon);
118+
let image = images.get(module);
119+
if (image === undefined) images.set(module, (image = `/${module}.jar`));
120+
pack.offsets.set(path, { image, at: +line.slice(colon + 1, c) });
121+
if (c === line.length) continue;
122+
b = c;
65123
}
66-
if (rest[0]) pack.lazy.set(path, rest[0]);
124+
pack.lazy.set(path, line.slice(b + 1));
67125
}
68126
}
69127
}
@@ -151,6 +209,8 @@ export class HttpBackend implements Backend {
151209
read(path: string): Uint8Array | null {
152210
const packed = this.pack.files.get(path);
153211
if (packed) return packed;
212+
// before lazy: a module's lazy entries appear once its index is parsed
213+
if (this.pack.index && !this.pack.index.has(path)) return null;
154214
const name = this.pack.lazy.get(path);
155215
if (name !== undefined && !this.fetchedPacks.has(name)) {
156216
this.fetchedPacks.add(name);
@@ -159,7 +219,6 @@ export class HttpBackend implements Backend {
159219
return this.read(path);
160220
}
161221
if (this.cache.has(path)) return this.cache.get(path)!;
162-
if (this.pack.index && !this.pack.index.has(path)) return null;
163222
const at = this.pack.offsets.get(path);
164223
if (at !== undefined) return this.readRange(path, 0, this.pack.index!.get(path)!);
165224
const xhr = this.request("GET", path);
@@ -174,7 +233,8 @@ export class HttpBackend implements Backend {
174233
const whole = this.pack.files.get(path) ?? this.cache.get(path);
175234
if (whole) return whole.subarray(off, off + len);
176235
if (len === 0) return new Uint8Array(0);
177-
const at = this.pack.offsets.get(path);
236+
// has() parses the path's module first; image files themselves are not indexed
237+
const at = this.pack.index?.has(path) ? this.pack.offsets.get(path) : undefined;
178238
if (at !== undefined) return this.readRange(at.image, at.at + off, len);
179239
let blocks = this.blocks.get(path);
180240
if (!blocks) this.blocks.set(path, (blocks = new Map()));
@@ -233,9 +293,10 @@ export class HttpBackend implements Backend {
233293
}
234294

235295
// The names in a directory of a pack index, or null if path is not one.
236-
export function listIndex(idx: Map<string, number>, path: string): string[] | null {
296+
export function listIndex(idx: PackIndex, path: string): string[] | null {
237297
if (idx.get(path) !== -1) return null;
238298
const prefix = path === "/" ? "/" : path + "/";
299+
idx.load(prefix);
239300
const out: string[] = [];
240301
for (const p of idx.keys()) {
241302
if (p.startsWith(prefix) && p.length > prefix.length && !p.slice(prefix.length).includes("/")) out.push(p.slice(prefix.length));

‎test/image.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,24 @@ test("compact index keeps paths, sizes, offsets, and directory order", () => {
7474
assert.equal(image.lazy.get("/lib/two"), "javac");
7575
});
7676

77+
test("a module's index lines are parsed when a path in it is first looked up", () => {
78+
const buf = pack([
79+
["/index.prefix", "0 d /modules\n0 d /modules/a\n0 d /modules/a/p\n0 d /modules/b"],
80+
["/index/a.prefix", "0 f /modules/a/p/X.class 5 a:0\n15 Y.class 6 a:5 javac"],
81+
["/index/b.prefix", "0 f /modules/b/Z.class 7 b:0"],
82+
]);
83+
const image = parsePack(buf.buffer as ArrayBuffer);
84+
assert.equal(image.files.size, 0);
85+
assert.equal(image.offsets.size, 0);
86+
assert.deepEqual(listIndex(image.index!, "/modules/a/p"), ["X.class", "Y.class"]);
87+
assert.equal(image.index!.get("/modules/a/p/Y.class"), 6);
88+
assert.deepEqual(image.offsets.get("/modules/a/p/Y.class"), { image: "/a.jar", at: 5 });
89+
assert.equal(image.lazy.get("/modules/a/p/Y.class"), "javac");
90+
assert.equal(image.offsets.has("/modules/b/Z.class"), false);
91+
assert.equal(image.index!.has("/modules/b/Z.class"), true);
92+
assert.deepEqual(listIndex(image.index!, "/modules"), ["a", "b"]);
93+
});
94+
7795
const node = join(root, "dist", "node.js");
7896
const skip = existsSync(node) ? false : "run `pnpm build` first";
7997
const out = join(root, "build", "test-image");

0 commit comments

Comments
 (0)