~emersion/mrsh

ref: fb1a6e2ce995f61ca8e41e8ac3f591bc50922592 mrsh/shell/task_if_clause.c -rw-r--r-- 1.2 KiB
fb1a6e2cemersion readme: add link to overall project status 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdlib.h>
#include "shell.h"

struct task_if_clause {
	struct task task;
	struct task *condition, *body, *else_part;
};

static void task_if_clause_destroy(struct task *task) {
	struct task_if_clause *tic = (struct task_if_clause *)task;
	task_destroy(tic->condition);
	task_destroy(tic->body);
	task_destroy(tic->else_part);
	free(tic);
}

static int task_if_clause_poll(struct task *task, struct context *ctx) {
	struct task_if_clause *tic = (struct task_if_clause *)task;

	int condition_status = task_poll(tic->condition, ctx);
	if (condition_status < 0) {
		return condition_status;
	}

	if (condition_status == 0) {
		return task_poll(tic->body, ctx);
	} else {
		if (tic->else_part == NULL) {
			return 0;
		}
		return task_poll(tic->else_part, ctx);
	}
}

static const struct task_interface task_if_clause_impl = {
	.destroy = task_if_clause_destroy,
	.poll = task_if_clause_poll,
};

struct task *task_if_clause_create(struct task *condition, struct task *body,
		struct task *else_part) {
	struct task_if_clause *tic = calloc(1, sizeof(struct task_if_clause));
	task_init(&tic->task, &task_if_clause_impl);
	tic->condition = condition;
	tic->body = body;
	tic->else_part = else_part;
	return &tic->task;
}