Skip to content

Instantly share code, notes, and snippets.

@jorangreef
Created March 9, 2019 15:13
Show Gist options
  • Save jorangreef/19956b854e7d5e245c8ecb9eb655f4cd to your computer and use it in GitHub Desktop.
Save jorangreef/19956b854e7d5e245c8ecb9eb655f4cd to your computer and use it in GitHub Desktop.
get_buffer()
#include <assert.h>
#include <limits.h>
#include <node_api.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static int arg_buf(
napi_env env,
napi_value value,
unsigned char** buffer,
int* length
) {
assert(*buffer == NULL);
assert(*length == 0);
bool is_buffer;
assert(napi_is_buffer(env, value, &is_buffer) == napi_ok);
assert(is_buffer);
size_t size = 0;
assert(napi_get_buffer_info(env, value, (void**) buffer, &size) == napi_ok);
assert(*buffer != NULL);
assert(size <= INT_MAX);
*length = (int) size;
assert(*length >= 0);
return 1;
}
static napi_value get_buffer(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv[1];
assert(napi_get_cb_info(env, info, &argc, argv, NULL, NULL) == napi_ok);
assert(argc == 1);
unsigned char* buffer = NULL;
int buffer_length = 0;
assert(arg_buf(env, argv[0], &buffer, &buffer_length));
assert(buffer != NULL);
printf("buffer_length=%i\n", buffer_length);
return NULL;
}
static napi_value Init(napi_env env, napi_value exports) {
napi_value fn_get_buffer;
assert(napi_create_function(env, NULL, 0, get_buffer, NULL, &fn_get_buffer) == napi_ok);
assert(napi_set_named_property(env, exports, "get_buffer", fn_get_buffer) == napi_ok);
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
{
"targets": [
{
"target_name": "binding",
"sources": [ "binding.c" ]
},
{
"target_name": "copy",
"type": "none",
"dependencies": [ "binding" ],
"copies": [
{
'destination': '<(module_root_dir)',
'files': ['<(module_root_dir)/build/Release/binding.node']
}
]
}
]
}
var binding = require('./binding.node');
var crypto = require('crypto');
console.log('process.version=' + process.version);
console.log('testing Buffer.alloc(0)...');
binding.get_buffer(Buffer.alloc(0));
console.log('testing cipher.update(Buffer.alloc(0))...');
var key = Buffer.alloc(32, 255);
var iv = Buffer.alloc(16);
var cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
binding.get_buffer(cipher.update(Buffer.alloc(0)));
{
"name": "get_buffer",
"version": "1.0.0",
"main": "index.js",
"files": [
"binding.c",
"index.js"
],
"author": "Joran Dirk Greef",
"license": "MIT",
"scripts": {
"postinstall": "node-gyp clean"
},
"engines": {
"node": ">=10.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment