addon.c (2593B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 #include "stdlib/number/float64/base/get_low_word.h" 20 #include <node_api.h> 21 #include <stdint.h> 22 #include <stdbool.h> 23 #include <assert.h> 24 25 /** 26 * Receives JavaScript callback invocation data. 27 * 28 * @private 29 * @param env environment under which the function is invoked 30 * @param info callback data 31 * @return Node-API value 32 */ 33 static napi_value addon( napi_env env, napi_callback_info info ) { 34 napi_status status; 35 36 // Get callback arguments: 37 size_t argc = 1; 38 napi_value argv[ 1 ]; 39 status = napi_get_cb_info( env, info, &argc, argv, NULL, NULL ); 40 assert( status == napi_ok ); 41 42 // Check whether we were provided the correct number of arguments: 43 if ( argc < 1 ) { 44 status = napi_throw_error( env, NULL, "invalid invocation. Insufficient arguments." ); 45 assert( status == napi_ok ); 46 return NULL; 47 } 48 if ( argc > 1 ) { 49 status = napi_throw_error( env, NULL, "invalid invocation. Too many arguments." ); 50 assert( status == napi_ok ); 51 return NULL; 52 } 53 54 napi_valuetype vtype0; 55 status = napi_typeof( env, argv[ 0 ], &vtype0 ); 56 assert( status == napi_ok ); 57 if ( vtype0 != napi_number ) { 58 status = napi_throw_type_error( env, NULL, "invalid argument. First argument must be a number." ); 59 assert( status == napi_ok ); 60 return NULL; 61 } 62 63 double value; 64 status = napi_get_value_double( env, argv[ 0 ], &value ); 65 assert( status == napi_ok ); 66 67 uint32_t low; 68 stdlib_base_float64_get_low_word( value, &low ); 69 70 napi_value v; 71 status = napi_create_uint32( env, low, &v ); 72 assert( status == napi_ok ); 73 74 return v; 75 } 76 77 /** 78 * Initializes a Node-API module. 79 * 80 * @private 81 * @param env environment under which the function is invoked 82 * @param exports exports object 83 * @return main export 84 */ 85 static napi_value init( napi_env env, napi_value exports ) { 86 napi_value fcn; 87 napi_status status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, addon, NULL, &fcn ); 88 assert( status == napi_ok ); 89 return fcn; 90 } 91 92 NAPI_MODULE( NODE_GYP_MODULE_NAME, init )