perf: move Deno.writeTextFile and like functions to Rust (#14221)

Co-authored-by: Luca Casonato <hello@lcas.dev>
This commit is contained in:
David Sherret 2022-04-18 18:00:14 -04:00 committed by GitHub
parent ca3b20df3c
commit a64e63c361
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 222 additions and 138 deletions

View file

@ -1,12 +1,9 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const { stat, statSync, chmod, chmodSync } = window.__bootstrap.fs;
const { open, openSync } = window.__bootstrap.files;
const { build } = window.__bootstrap.build;
const {
TypedArrayPrototypeSubarray,
} = window.__bootstrap.primordials;
const core = window.__bootstrap.core;
const { abortSignal } = window.__bootstrap;
const { pathFromURL } = window.__bootstrap.util;
function writeFileSync(
path,
@ -14,33 +11,13 @@
options = {},
) {
options.signal?.throwIfAborted();
if (options.create !== undefined) {
const create = !!options.create;
if (!create) {
// verify that file exists
statSync(path);
}
}
const openOptions = options.append
? { write: true, create: true, append: true }
: { write: true, create: true, truncate: true };
const file = openSync(path, openOptions);
if (
options.mode !== undefined &&
options.mode !== null &&
build.os !== "windows"
) {
chmodSync(path, options.mode);
}
let nwritten = 0;
while (nwritten < data.length) {
nwritten += file.writeSync(TypedArrayPrototypeSubarray(data, nwritten));
}
file.close();
core.opSync("op_write_file_sync", {
path: pathFromURL(path),
data,
mode: options.mode,
append: options.append ?? false,
create: options.create ?? true,
});
}
async function writeFile(
@ -48,38 +25,30 @@
data,
options = {},
) {
if (options.create !== undefined) {
const create = !!options.create;
if (!create) {
// verify that file exists
await stat(path);
}
let cancelRid;
let abortHandler;
if (options.signal) {
options.signal.throwIfAborted();
cancelRid = core.opSync("op_cancel_handle");
abortHandler = () => core.tryClose(cancelRid);
options.signal[abortSignal.add](abortHandler);
}
const openOptions = options.append
? { write: true, create: true, append: true }
: { write: true, create: true, truncate: true };
const file = await open(path, openOptions);
if (
options.mode !== undefined &&
options.mode !== null &&
build.os !== "windows"
) {
await chmod(path, options.mode);
}
const signal = options?.signal ?? null;
let nwritten = 0;
try {
while (nwritten < data.length) {
signal?.throwIfAborted();
nwritten += await file.write(
TypedArrayPrototypeSubarray(data, nwritten),
);
}
await core.opAsync("op_write_file_async", {
path: pathFromURL(path),
data,
mode: options.mode,
append: options.append ?? false,
create: options.create ?? true,
cancelRid,
});
} finally {
file.close();
if (options.signal) {
options.signal[abortSignal.remove](abortHandler);
// always throw the abort error when aborted
options.signal.throwIfAborted();
}
}
}