-
Notifications
You must be signed in to change notification settings - Fork 4
/
addon.c
96 lines (80 loc) · 2.38 KB
/
addon.c
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#define NAPI_VERSION 3
#include <string.h>
#include <node_api.h>
static napi_status get_utf8_string(napi_env env, napi_value str, char **out_buff, size_t *buffsize) {
size_t len;
size_t len2;
char *buff;
napi_status res;
if (out_buff == NULL) {
return napi_invalid_arg;
}
res = napi_get_value_string_utf8(env, str, NULL, 0, &len);
if (res != napi_ok) {
return res;
}
/* +1 since napi_get_value_string_utf8 doesn't include NULL terminator
* c.f. https://nodejs.org/api/n-api.html#n_api_napi_get_value_string_utf8
*/
buff = (char *) malloc(len + 1);
if (!buff) {
return napi_generic_failure;
}
res = napi_get_value_string_utf8(env, str, buff, len + 1, &len2);
if (res != napi_ok) {
free(buff);
return napi_generic_failure;
}
*out_buff = buff;
if (buffsize) {
*buffsize = len;
}
return napi_ok;
}
napi_value get_string_length(napi_env env, napi_callback_info info) {
napi_value argv[1];
size_t argc = 1;
char *str = NULL;
size_t str_len = 0;
napi_status res;
res = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (res != napi_ok) {
napi_throw_error(env, "EINVAL", "Call to napi_get_cb_info failed");
return NULL;
}
if (argc < 1) {
napi_throw_error(env, "EINVAL", "get_string_length expect 1 argument");
return NULL;
}
res = get_utf8_string(env, argv[0], &str, &str_len);
if (res != napi_ok) {
goto err;
}
napi_value result;
res = napi_create_uint32(env, str_len, &result);
if (res != napi_ok) {
goto err;
}
free(str);
return result;
err:
napi_throw_error(env, "EINVAL", "Something went wrong.");
free(str);
return NULL;
}
napi_value init_all(napi_env env, napi_value exports) {
napi_value fn;
napi_status res;
res = napi_create_function(env, NULL, 0, get_string_length, NULL, &fn);
if (res != napi_ok) {
napi_throw_error(env, "EINVAL", "Cannot create function");
return NULL;
}
res = napi_set_named_property(env, exports, "get_string_length", fn);
if (res != napi_ok) {
napi_throw_error(env, "EINVAL", "Cannot set named property");
return NULL;
}
return exports;
}
NAPI_MODULE(libSqreen, init_all)