Skip to content

Commit

Permalink
Extract write helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Mar 9, 2024
1 parent 8f800ca commit 906c7cf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
25 changes: 10 additions & 15 deletions src/sourcemap-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
posOut,
indexOf,
td,
maybeWrite,
} from './vlq';
// export { decodeOriginalScopes } from './scopes';

Expand Down Expand Up @@ -78,7 +79,9 @@ export function encode(decoded: SourceMapMappings): string;
export function encode(decoded: Readonly<SourceMapMappings>): string;
export function encode(decoded: Readonly<SourceMapMappings>): string {
const bufLength = 1024 * 16;
const subLength = bufLength - 36;
// We can push up to 5 ints, each int can take at most 7 chars, and we
// may push a comma.
const subLength = bufLength - (7 * 5 + 1);
const buf = new Uint8Array(bufLength);
const sub = buf.subarray(0, subLength);
let pos = 0;
Expand All @@ -91,26 +94,18 @@ export function encode(decoded: Readonly<SourceMapMappings>): string {

for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) {
if (pos === bufLength) {
out += td.decode(buf);
pos = 0;
}
buf[pos++] = semicolon;
}
out = maybeWrite(out, buf, pos, buf, bufLength);
pos = posOut;
if (i > 0) buf[pos++] = semicolon;

if (line.length === 0) continue;

genColumn = 0;

for (let j = 0; j < line.length; j++, pos = posOut) {
const segment = line[j];
// We can push up to 5 ints, each int can take at most 7 chars, and we
// may push a comma.
if (pos > subLength) {
out += td.decode(sub);
buf.copyWithin(0, subLength, pos);
pos -= subLength;
}
out = maybeWrite(out, sub, pos, buf, subLength);
pos = posOut;
if (j > 0) buf[pos++] = comma;

genColumn = encodeInteger(buf, pos, segment[0], genColumn);
Expand Down
17 changes: 17 additions & 0 deletions src/vlq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,23 @@ export function encodeInteger(buf: Uint8Array, pos: number, num: number, relativ
return num;
}

export function maybeWrite(
build: string,
buf: Uint8Array,
pos: number,
copy: Uint8Array,
length: number,
): string {
if (pos < length) {
posOut = pos;
return build;
}
const out = td.decode(buf);
copy.copyWithin(0, length, pos);
posOut = pos - length;
return build + out;
}

// Provide a fallback for older environments.
export const td =
typeof TextDecoder !== 'undefined'
Expand Down

0 comments on commit 906c7cf

Please sign in to comment.