~emersion/mrsh

ref: 9371d6094e78645f0ec0c85b6cd5b6c8ec9638fc mrsh/builtin/builtin.c -rw-r--r-- 1.1 KiB
9371d609Drew DeVault Implement times, : builtins 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 <assert.h>
#include <mrsh/builtin.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "builtin.h"

struct builtin_map {
	const char *name;
	mrsh_builtin_func_t func;
};

static struct builtin_map builtins[] = {
	// Keep alpha sorted
	{ ":", builtin_colon },
	{ "exit", builtin_exit },
	{ "times", builtin_times },
};

static int builtin_compare(const void *_a, const void *_b) {
	const struct builtin_map *a = _a;
	const struct builtin_map *b = _b;
	return strcmp(a->name, b->name);
}

mrsh_builtin_func_t get_builtin(const char *name) {
	struct builtin_map key = { .name = name };
	struct builtin_map *builtin = bsearch(&key, builtins,
			sizeof(builtins) / sizeof(builtins[0]),
			sizeof(builtins[0]), builtin_compare);
	return builtin ? builtin->func : NULL;
}

int mrsh_has_builtin(const char *name) {
	return get_builtin(name) != NULL;
}

int mrsh_run_builtin(struct mrsh_state *state, int argc, char *argv[]) {
	assert(argc > 0);

	const char *name = argv[0];
	mrsh_builtin_func_t builtin = get_builtin(name);
	if (builtin == NULL) {
		return -1;
	}

	return builtin(state, argc, argv);
}