11cb0ef41Sopenharmony_ci#include <node.h>
21cb0ef41Sopenharmony_ci#include <node_buffer.h>
31cb0ef41Sopenharmony_ci#include <v8.h>
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci#include <assert.h>
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_cistatic int alive;
81cb0ef41Sopenharmony_cistatic char buf[1024];
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_cistatic void FreeCallback(char* data, void* hint) {
111cb0ef41Sopenharmony_ci  alive--;
121cb0ef41Sopenharmony_ci}
131cb0ef41Sopenharmony_ci
141cb0ef41Sopenharmony_civoid Alloc(const v8::FunctionCallbackInfo<v8::Value>& args) {
151cb0ef41Sopenharmony_ci  v8::Isolate* isolate = args.GetIsolate();
161cb0ef41Sopenharmony_ci  alive++;
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_ci  uintptr_t alignment = args[1].As<v8::Integer>()->Value();
191cb0ef41Sopenharmony_ci  uintptr_t offset = args[2].As<v8::Integer>()->Value();
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ci  uintptr_t static_offset = reinterpret_cast<uintptr_t>(buf) % alignment;
221cb0ef41Sopenharmony_ci  char* aligned = buf + (alignment - static_offset) + offset;
231cb0ef41Sopenharmony_ci
241cb0ef41Sopenharmony_ci  args.GetReturnValue().Set(node::Buffer::New(
251cb0ef41Sopenharmony_ci        isolate,
261cb0ef41Sopenharmony_ci        aligned,
271cb0ef41Sopenharmony_ci        args[0].As<v8::Integer>()->Value(),
281cb0ef41Sopenharmony_ci        FreeCallback,
291cb0ef41Sopenharmony_ci        nullptr).ToLocalChecked());
301cb0ef41Sopenharmony_ci}
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_civoid Check(const v8::FunctionCallbackInfo<v8::Value>& args) {
331cb0ef41Sopenharmony_ci  v8::Isolate* isolate = args.GetIsolate();
341cb0ef41Sopenharmony_ci  isolate->RequestGarbageCollectionForTesting(
351cb0ef41Sopenharmony_ci      v8::Isolate::kFullGarbageCollection);
361cb0ef41Sopenharmony_ci  assert(alive > 0);
371cb0ef41Sopenharmony_ci}
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_civoid init(v8::Local<v8::Object> exports) {
401cb0ef41Sopenharmony_ci  NODE_SET_METHOD(exports, "alloc", Alloc);
411cb0ef41Sopenharmony_ci  NODE_SET_METHOD(exports, "check", Check);
421cb0ef41Sopenharmony_ci}
431cb0ef41Sopenharmony_ci
441cb0ef41Sopenharmony_ciNODE_MODULE(NODE_GYP_MODULE_NAME, init)
45