summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorFelix Fietkau <nbd@nbd.name>2024-06-17 11:12:43 +0200
committerFelix Fietkau <nbd@nbd.name>2024-06-17 12:52:18 +0200
commite0bab40c85780f765bed78bd2e67f376b6883594 (patch)
tree5224addd7371df200d934dcd9ae81c068c11dbbc
parent2a0240f349d2808a01ec3e006b6f0da9107b7a27 (diff)
fs: add truncate() file method
Trunates the file referenced by a file handle Signed-off-by: Felix Fietkau <nbd@nbd.name>
-rw-r--r--lib/fs.c38
-rw-r--r--tests/custom/03_stdlib/40_proto1
2 files changed, 39 insertions, 0 deletions
diff --git a/lib/fs.c b/lib/fs.c
index 4d9695e..f237102 100644
--- a/lib/fs.c
+++ b/lib/fs.c
@@ -739,6 +739,43 @@ uc_fs_seek(uc_vm_t *vm, size_t nargs)
}
/**
+ * Truncate file to a given size
+ *
+ * Returns `true` if the file was successfully truncated.
+ *
+ * Returns `null` if an error occurred.
+ *
+ * @function module:fs.file#truncate
+ *
+ * @param {number} [offset=0]
+ * The offset in bytes.
+ *
+ * @returns {?boolean}
+ */
+static uc_value_t *
+uc_fs_truncate(uc_vm_t *vm, size_t nargs)
+{
+ FILE *fp = uc_fn_thisval("fs.file");
+ uc_value_t *ofs = uc_fn_arg(0);
+ off_t offset;
+
+ if (!fp)
+ err_return(EBADF);
+
+ if (!ofs)
+ offset = 0;
+ else if (ucv_type(ofs) != UC_INTEGER)
+ err_return(EINVAL);
+ else
+ offset = (off_t)ucv_int64_get(ofs);
+
+ if (ftruncate(fileno(fp), offset) < 0)
+ err_return(errno);
+
+ return ucv_boolean_new(true);
+}
+
+/**
* Obtain current read position.
*
* Obtains the current, absolute read position of the open file.
@@ -2571,6 +2608,7 @@ static const uc_function_list_t file_fns[] = {
{ "fileno", uc_fs_fileno },
{ "error", uc_fs_error },
{ "isatty", uc_fs_isatty },
+ { "truncate", uc_fs_truncate },
};
static const uc_function_list_t dir_fns[] = {
diff --git a/tests/custom/03_stdlib/40_proto b/tests/custom/03_stdlib/40_proto
index 2a12966..6fed529 100644
--- a/tests/custom/03_stdlib/40_proto
+++ b/tests/custom/03_stdlib/40_proto
@@ -38,6 +38,7 @@ When invoked with two arguments, returns the given value.
Hello, World!
[
{
+ "truncate": "function truncate(...) { [native code] }",
"isatty": "function isatty(...) { [native code] }",
"error": "function error(...) { [native code] }",
"fileno": "function fileno(...) { [native code] }",