fix(eval): writestring() handling of null #39328

Problem:
- write_blob, write_string dereference args which may be NULL.
- `writefile(v:_null_blob, …)` fails.

Solution:
- Fix the annotation.
- Handle null blob.

Co-authored-by: zeertzjq <zeertzjq@outlook.com>
This commit is contained in:
Justin M. Keyes
2026-04-26 09:55:52 -04:00
committed by GitHub
parent 682067c46a
commit 6d0cdcd605
2 changed files with 11 additions and 4 deletions

View File

@@ -1733,13 +1733,13 @@ write_blob_error:
}
static bool write_blob(FileDescriptor *const fp, const blob_T *const blob)
FUNC_ATTR_NONNULL_ARG(1)
FUNC_ATTR_NONNULL_ALL
{
return write_data(fp, blob->bv_ga.ga_data, (size_t)tv_blob_len(blob));
}
static bool write_string(FileDescriptor *const fp, const char *const data)
FUNC_ATTR_NONNULL_ARG(1)
FUNC_ATTR_NONNULL_ALL
{
return write_data(fp, data, strlen(data));
}
@@ -1833,7 +1833,7 @@ void f_writefile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
bool write_ok;
if (argvars[0].v_type == VAR_BLOB) {
write_ok = write_blob(&fp, argvars[0].vval.v_blob);
write_ok = argvars[0].vval.v_blob == NULL || write_blob(&fp, argvars[0].vval.v_blob);
} else if (argvars[0].v_type == VAR_STRING) {
write_ok = write_string(&fp, argvars[0].vval.v_string);
} else {

View File

@@ -65,6 +65,13 @@ describe('writefile()', function()
eq('\n', read_file(fname))
end)
it('writes a null blob to a file', function()
eq(0, fn.writefile({ 'line1' }, fname, 'b'))
eq('line1', read_file(fname))
command(('call writefile(v:_null_blob, "%s")'):format(fname))
eq('', read_file(fname))
end)
it('appends to a file', function()
eq(nil, read_file(fname))
eq(0, fn.writefile({ 'abc', 'def', 'ghi' }, fname))
@@ -100,7 +107,7 @@ describe('writefile()', function()
eq('a\0', read_file(fname))
end)
it('writes Lua strings to a file', function()
it('writes Lua (binary) strings to a file', function()
eq(0, exec_lua([[return vim.fn.writefile('foo\0bar', ..., 'b')]], fname))
eq('foo\0bar', read_file(fname))
end)