forked from svaarala/duktape
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimecheck.c
More file actions
81 lines (67 loc) · 1.94 KB
/
primecheck.c
File metadata and controls
81 lines (67 loc) · 1.94 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* primecheck.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "duktape.h"
/* For brevity assumes a maximum file length of 16kB. */
static void push_file_as_string(duk_context *ctx, const char *filename) {
FILE *f;
size_t len;
char buf[16384];
f = fopen(filename, "rb");
if (f) {
len = fread((void *) buf, 1, sizeof(buf), f);
fclose(f);
duk_push_lstring(ctx, (const char *) buf, (duk_size_t) len);
} else {
duk_push_undefined(ctx);
}
}
static duk_ret_t native_print(duk_context *ctx) {
duk_push_string(ctx, " ");
duk_insert(ctx, 0);
duk_join(ctx, duk_get_top(ctx) - 1);
printf("%s\n", duk_to_string(ctx, -1));
return 0;
}
static duk_ret_t native_prime_check(duk_context *ctx) {
int val = duk_require_int(ctx, 0);
int lim = duk_require_int(ctx, 1);
int i;
for (i = 2; i <= lim; i++) {
if (val % i == 0) {
duk_push_false(ctx);
return 1;
}
}
duk_push_true(ctx);
return 1;
}
int main(int argc, const char *argv[]) {
duk_context *ctx = NULL;
(void) argc; (void) argv;
ctx = duk_create_heap_default();
if (!ctx) {
printf("Failed to create a Duktape heap.\n");
exit(1);
}
duk_push_global_object(ctx);
duk_push_c_function(ctx, native_print, DUK_VARARGS);
duk_put_prop_string(ctx, -2, "print");
duk_push_c_function(ctx, native_prime_check, 2 /*nargs*/);
duk_put_prop_string(ctx, -2, "primeCheckNative");
push_file_as_string(ctx, "prime.js");
if (duk_peval(ctx) != 0) {
printf("Error running: %s\n", duk_safe_to_string(ctx, -1));
goto finished;
}
duk_pop(ctx); /* ignore result */
duk_get_prop_string(ctx, -1, "primeTest");
if (duk_pcall(ctx, 0) != 0) {
printf("Error: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx); /* ignore result */
finished:
duk_destroy_heap(ctx);
exit(0);
}