1
0
mirror of https://github.com/janet-lang/janet synced 2024-06-25 22:53:16 +00:00

Allow function that takes 1 argument to fiber/new.

This allows reuse of closures when creating many fibers.
This commit is contained in:
Calvin Rose 2020-02-23 14:47:29 -06:00
parent 6a13703e32
commit 738490e674
2 changed files with 24 additions and 4 deletions

View File

@ -65,7 +65,14 @@ JanetFiber *janet_fiber_reset(JanetFiber *fiber, JanetFunction *callee, int32_t
if (newstacktop >= fiber->capacity) {
janet_fiber_setcapacity(fiber, 2 * newstacktop);
}
safe_memcpy(fiber->data + fiber->stacktop, argv, argc * sizeof(Janet));
if (argv) {
memcpy(fiber->data + fiber->stacktop, argv, argc * sizeof(Janet));
} else {
/* If argv not given, fill with nil */
for (int32_t i = 0; i < argc; i++) {
fiber->data[fiber->stacktop + i] = janet_wrap_nil();
}
}
fiber->stacktop = newstacktop;
}
if (janet_fiber_funcframe(fiber, callee)) return NULL;
@ -362,10 +369,10 @@ static Janet cfun_fiber_new(int32_t argc, Janet *argv) {
janet_arity(argc, 1, 2);
JanetFunction *func = janet_getfunction(argv, 0);
JanetFiber *fiber;
if (func->def->min_arity != 0) {
janet_panic("expected nullary function in fiber constructor");
if (func->def->min_arity > 1) {
janet_panicf("fiber function must accept 0 or 1 arguments");
}
fiber = janet_fiber(func, 64, 0, NULL);
fiber = janet_fiber(func, 64, func->def->min_arity, NULL);
if (argc == 2) {
int32_t i;
JanetByteView view = janet_getbytes(argv, 1);

View File

@ -1270,6 +1270,19 @@ JanetSignal janet_continue(JanetFiber *fiber, Janet in, Janet *out) {
fiber->child = NULL;
}
/* Handle new fibers being resumed with a non-nil value */
if (old_status == JANET_STATUS_NEW && !janet_checktype(in, JANET_NIL)) {
Janet *stack = fiber->data + fiber->frame;
JanetFunction *func = janet_stack_frame(stack)->func;
if (func) {
if (func->def->arity > 0) {
stack[0] = in;
} else if (func->def->flags & JANET_FUNCDEF_FLAG_VARARG) {
stack[0] = janet_wrap_tuple(janet_tuple_n(&in, 1));
}
}
}
/* Save global state */
int32_t oldn = janet_vm_stackn++;
int handle = janet_vm_gc_suspend;