summaryrefslogtreecommitdiffhomepage
path: root/lib.c
diff options
context:
space:
mode:
authorJo-Philipp Wich <jo@mein.io>2021-05-10 17:03:23 +0200
committerGitHub <noreply@github.com>2021-05-10 17:03:23 +0200
commitfbf3dfad950310a0a7c5ae29f25312733fa9063d (patch)
treefc7643b7fa5384b0abf8ff3780bca72f38ca1db1 /lib.c
parenteb8a64d461851756e65093edf923bd534e86aae5 (diff)
parente546bbaf6bbee16356beb675cc3e806d9793688e (diff)
Merge pull request #10 from jow-/introduce-render-fn
Introduce render() function
Diffstat (limited to 'lib.c')
-rw-r--r--lib.c54
1 files changed, 51 insertions, 3 deletions
diff --git a/lib.c b/lib.c
index c1583f9..453f976 100644
--- a/lib.c
+++ b/lib.c
@@ -292,7 +292,7 @@ uc_print_common(uc_vm *vm, size_t nargs, FILE *fh)
static uc_value_t *
uc_print(uc_vm *vm, size_t nargs)
{
- return uc_print_common(vm, nargs, stdout);
+ return uc_print_common(vm, nargs, vm->output);
}
static uc_value_t *
@@ -1495,7 +1495,7 @@ uc_printf(uc_vm *vm, size_t nargs)
uc_printf_common(vm, nargs, buf);
- len = fwrite(buf->buf, 1, printbuf_length(buf), stdout);
+ len = fwrite(buf->buf, 1, printbuf_length(buf), vm->output);
printbuf_free(buf);
@@ -2199,6 +2199,53 @@ uc_include(uc_vm *vm, size_t nargs)
}
static uc_value_t *
+uc_render(uc_vm *vm, size_t nargs)
+{
+ uc_string_t *ustr = NULL;
+ FILE *mem, *prev;
+ size_t len = 0;
+
+ mem = open_memstream((char **)&ustr, &len);
+
+ if (!mem)
+ goto out;
+
+ /* reserve space for uc_string_t header... */
+ if (fseek(mem, sizeof(*ustr), SEEK_SET))
+ goto out;
+
+ /* divert VM output to memory fd */
+ prev = vm->output;
+ vm->output = mem;
+
+ /* execute include */
+ (void) uc_include(vm, nargs);
+
+ /* restore previous VM output */
+ vm->output = prev;
+ fclose(mem);
+
+ /* update uc_string_t length */
+ ustr->header.type = UC_STRING;
+ ustr->header.refcount = 1;
+ ustr->length = len - sizeof(*ustr);
+
+ return &ustr->header;
+
+out:
+ uc_vm_raise_exception(vm, EXCEPTION_RUNTIME,
+ "Unable to initialize output memory: %s",
+ strerror(errno));
+
+ if (mem)
+ fclose(mem);
+
+ free(ustr);
+
+ return NULL;
+}
+
+static uc_value_t *
uc_warn(uc_vm *vm, size_t nargs)
{
return uc_print_common(vm, nargs, stderr);
@@ -2473,7 +2520,8 @@ static const uc_cfunction_list functions[] = {
{ "trace", uc_trace },
{ "proto", uc_proto },
{ "sleep", uc_sleep },
- { "assert", uc_assert }
+ { "assert", uc_assert },
+ { "render", uc_render }
};