|
| 1 | +#include <node_api.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +extern uint8_t async_rewrite_c( |
| 5 | + const uint8_t* input, |
| 6 | + uintptr_t input_len, |
| 7 | + uint8_t** output, |
| 8 | + uintptr_t* output_len, |
| 9 | + uint8_t debug_level); |
| 10 | +extern void async_rewrite_free_result( |
| 11 | + uint8_t* output); |
| 12 | + |
| 13 | +static napi_value async_rewrite_napi(napi_env env, napi_callback_info info) { |
| 14 | + napi_status status; |
| 15 | + napi_value argv[2]; |
| 16 | + size_t argc = sizeof(argv) / sizeof(argv[0]); |
| 17 | + |
| 18 | + status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL); |
| 19 | + if (status != napi_ok) { |
| 20 | + return NULL; |
| 21 | + } |
| 22 | + if (argc < 2) { |
| 23 | + napi_throw_error(env, NULL, "Wrong number of arguments"); |
| 24 | + return NULL; |
| 25 | + } |
| 26 | + |
| 27 | + size_t bufsize = 0; |
| 28 | + status = napi_get_value_string_utf8(env, argv[0], NULL, 0, &bufsize); |
| 29 | + if (status != napi_ok) { |
| 30 | + return NULL; |
| 31 | + } |
| 32 | + uint8_t* input = (uint8_t*)malloc(bufsize + 1); |
| 33 | + if (input == NULL) { |
| 34 | + napi_throw_error(env, NULL, "Memory allocation failed"); |
| 35 | + return NULL; |
| 36 | + } |
| 37 | + status = napi_get_value_string_utf8(env, argv[0], (char*)input, bufsize + 1, &bufsize); |
| 38 | + if (status != napi_ok) { |
| 39 | + free(input); |
| 40 | + return NULL; |
| 41 | + } |
| 42 | + input[bufsize] = '\0'; |
| 43 | + uint32_t debug_level = 0; |
| 44 | + status = napi_get_value_uint32(env, argv[1], &debug_level); |
| 45 | + if (status != napi_ok) { |
| 46 | + free(input); |
| 47 | + return NULL; |
| 48 | + } |
| 49 | + |
| 50 | + uint8_t* output = NULL; |
| 51 | + uintptr_t output_len = 0; |
| 52 | + uint8_t result = async_rewrite_c(input, bufsize, &output, &output_len, debug_level); |
| 53 | + free(input); |
| 54 | + |
| 55 | + if (result != 0) { |
| 56 | + napi_throw_error(env, NULL, "Error in async_rewrite_c"); |
| 57 | + return NULL; |
| 58 | + } |
| 59 | + |
| 60 | + napi_value result_value; |
| 61 | + status = napi_create_string_utf8(env, (const char*)output, output_len, &result_value); |
| 62 | + async_rewrite_free_result(output); |
| 63 | + if (status != napi_ok) { |
| 64 | + return NULL; |
| 65 | + } |
| 66 | + |
| 67 | + return result_value; |
| 68 | +} |
| 69 | + |
| 70 | +NAPI_MODULE_INIT() { |
| 71 | + napi_value exported_function; |
| 72 | + napi_status status; |
| 73 | + status = napi_create_function(env, |
| 74 | + "asyncRewrite", |
| 75 | + NAPI_AUTO_LENGTH, |
| 76 | + async_rewrite_napi, |
| 77 | + NULL, |
| 78 | + &exported_function); |
| 79 | + if (status != napi_ok) { |
| 80 | + return NULL; |
| 81 | + } |
| 82 | + status = napi_set_named_property(env, |
| 83 | + exports, |
| 84 | + "asyncRewrite", |
| 85 | + exported_function); |
| 86 | + if (status != napi_ok) { |
| 87 | + return NULL; |
| 88 | + } |
| 89 | + return exports; |
| 90 | +} |
0 commit comments