refactor(fileio): remove API shell layer encouraging unnecessary allocations

Functions like file_open_new() and file_open_fd_new() which just is a
wrapper around the real functions but with an extra xmalloc/xfree around
is an anti-pattern. If the caller really needs to allocate a
FileDescriptor as a heap object, it can do that directly.

FileDescriptor by itself is pretty much a pointer, or rather two:
the OS fd index and a pointer to a buffer. So most of the time an extra
pointer layer is just wasteful.

In the case of scriptin[curscript] in getchar.c, curscript used
to mean in practice:

N+1 open scripts           when curscript>0
zero or one open scripts   when curscript==0

Which means scriptin[0] had to be compared to NULL to disambiguate the
curscript=0 case.

Instead, use curscript==-1 to mean that are no script,
then all pointer comparisons dissappear and we can just use an array of
structs without extra pointers.
This commit is contained in:
bfredl
2024-02-24 10:17:20 +01:00
parent 0fcbda5987
commit 77e928fd3e
7 changed files with 86 additions and 198 deletions

View File

@@ -426,7 +426,19 @@ int main(int argc, char **argv)
params.edit_type = EDIT_STDIN;
}
open_script_files(&params);
if (params.scriptin) {
if (!open_scriptin(params.scriptin)) {
os_exit(2);
}
}
if (params.scriptout) {
scriptout = os_fopen(params.scriptout, params.scriptout_append ? APPENDBIN : WRITEBIN);
if (scriptout == NULL) {
fprintf(stderr, _("Cannot open for script output: \""));
fprintf(stderr, "%s\"\n", params.scriptout);
os_exit(2);
}
}
nlua_init_defaults();
@@ -1620,37 +1632,6 @@ static void read_stdin(void)
check_swap_exists_action();
}
static void open_script_files(mparm_T *parmp)
{
if (parmp->scriptin) {
int error;
if (strequal(parmp->scriptin, "-")) {
FileDescriptor *stdin_dup = file_open_stdin();
scriptin[0] = stdin_dup;
} else {
scriptin[0] = file_open_new(&error, parmp->scriptin,
kFileReadOnly|kFileNonBlocking, 0);
if (scriptin[0] == NULL) {
vim_snprintf(IObuff, IOSIZE,
_("Cannot open for reading: \"%s\": %s\n"),
parmp->scriptin, os_strerror(error));
fprintf(stderr, "%s", IObuff);
os_exit(2);
}
}
save_typebuf();
}
if (parmp->scriptout) {
scriptout = os_fopen(parmp->scriptout, parmp->scriptout_append ? APPENDBIN : WRITEBIN);
if (scriptout == NULL) {
fprintf(stderr, _("Cannot open for script output: \""));
fprintf(stderr, "%s\"\n", parmp->scriptout);
os_exit(2);
}
}
}
// Create the requested number of windows and edit buffers in them.
// Also does recovery if "recoverymode" set.
static void create_windows(mparm_T *parmp)