1 | /* |
2 | * QuickJS: Example of C module |
3 | * |
4 | * Copyright (c) 2017-2018 Fabrice Bellard |
5 | * |
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy |
7 | * of this software and associated documentation files (the "Software"), to deal |
8 | * in the Software without restriction, including without limitation the rights |
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
10 | * copies of the Software, and to permit persons to whom the Software is |
11 | * furnished to do so, subject to the following conditions: |
12 | * |
13 | * The above copyright notice and this permission notice shall be included in |
14 | * all copies or substantial portions of the Software. |
15 | * |
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL |
19 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
22 | * THE SOFTWARE. |
23 | */ |
24 | #include "../quickjs.h" |
25 | |
26 | #define countof(x) (sizeof(x) / sizeof((x)[0])) |
27 | |
28 | static int fib(int n) |
29 | { |
30 | if (n <= 0) |
31 | return 0; |
32 | else if (n == 1) |
33 | return 1; |
34 | else |
35 | return fib(n - 1) + fib(n - 2); |
36 | } |
37 | |
38 | static JSValue js_fib(JSContext *ctx, JSValueConst this_val, |
39 | int argc, JSValueConst *argv) |
40 | { |
41 | int n, res; |
42 | if (JS_ToInt32(ctx, &n, argv[0])) |
43 | return JS_EXCEPTION; |
44 | res = fib(n); |
45 | return JS_NewInt32(ctx, res); |
46 | } |
47 | |
48 | static const JSCFunctionListEntry js_fib_funcs[] = { |
49 | JS_CFUNC_DEF("fib" , 1, js_fib ), |
50 | }; |
51 | |
52 | static int js_fib_init(JSContext *ctx, JSModuleDef *m) |
53 | { |
54 | return JS_SetModuleExportList(ctx, m, js_fib_funcs, |
55 | countof(js_fib_funcs)); |
56 | } |
57 | |
58 | #ifdef JS_SHARED_LIBRARY |
59 | #define JS_INIT_MODULE js_init_module |
60 | #else |
61 | #define JS_INIT_MODULE js_init_module_fib |
62 | #endif |
63 | |
64 | JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) |
65 | { |
66 | JSModuleDef *m; |
67 | m = JS_NewCModule(ctx, module_name, js_fib_init); |
68 | if (!m) |
69 | return NULL; |
70 | JS_AddModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs)); |
71 | return m; |
72 | } |
73 | |