1 /*!
2 * @file quickjs_addon_common.h
3 *
4 * Copyright (C) 2015-2021 Alibaba Group Holding Limited
5 */
6
7 #ifndef _AMP_QUICKJS_ADDON_COMMON_H_
8 #define _AMP_QUICKJS_ADDON_COMMON_H_
9
10 #include "stdint.h"
11 #include "stdbool.h"
12 #include "quickjs.h"
13
14 #ifndef countof
15 #define countof(x) (sizeof(x) / sizeof((x)[0]))
16 #endif
17
18 extern JSContext *js_get_context(void);
19
20 #ifdef JSE_ADVANCED_ADDON_AIOT_DEVICE
21 extern JSClassID js_aiot_device_class_id;
22 #endif
23
24 #define QUICKJS_GLOBAL_FUNC(name, func) \
25 do { \
26 JSValue global_func; \
27 global_func = JS_GetGlobalObject(ctx); \
28 JS_SetPropertyStr(ctx, global_func, name, \
29 JS_NewCFunction(ctx, func, name, 1)); \
30 JS_FreeValue(ctx, global_func); \
31 } while (0);
32
QUICKJS_GET_PROPERTY_STR(JSContext * ctx,JSValueConst argv,char * name)33 static inline char *QUICKJS_GET_PROPERTY_STR(JSContext *ctx, JSValueConst argv, char *name)
34 {
35 JSValue js_value = JS_GetPropertyStr(ctx, argv, name);
36 char *str = NULL;
37 if(!JS_IsString(js_value)){
38 amp_error("QUCIJS", "request %s is invalid", name);
39 JS_FreeValue(ctx, js_value);
40 return NULL;
41 }
42 str = (char *)JS_ToCString(ctx, js_value);
43 JS_FreeValue(ctx, js_value);
44 return str;
45 }
46
QUICKJS_GET_PROPERTY_INT32(JSContext * ctx,JSValueConst argv,char * name)47 static inline int QUICKJS_GET_PROPERTY_INT32(JSContext *ctx, JSValueConst argv, char *name)
48 {
49 JSValue js_value = JS_GetPropertyStr(ctx, argv, name);
50 int32_t val = 0;
51 if(!JS_IsNumber(js_value)){
52 amp_error("QUCIJS", "request %s is invalid", name);
53 JS_FreeValue(ctx, js_value);
54 return 0;
55 }
56 JS_ToInt32(ctx, &val, js_value);
57 JS_FreeValue(ctx, js_value);
58 return val;
59 }
60
QUICKJS_GET_PROPERTY_BOOL(JSContext * ctx,JSValueConst argv,char * name)61 static inline bool QUICKJS_GET_PROPERTY_BOOL(JSContext *ctx, JSValueConst argv, char *name)
62 {
63 JSValue js_value = JS_GetPropertyStr(ctx, argv, name);
64 bool val = false;
65 if(!JS_IsBool(js_value)){
66 amp_error("QUCIJS", "request %s is invalid", name);
67 JS_FreeValue(ctx, js_value);
68 return 0;
69 }
70 val = JS_ToBool(ctx, js_value);
71 JS_FreeValue(ctx, js_value);
72 return val;
73 }
74
75 #endif