File: binding.cc

package info (click to toggle)
nodejs 22.14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 246,928 kB
  • sloc: cpp: 1,582,349; javascript: 582,017; ansic: 82,400; python: 60,561; sh: 4,009; makefile: 2,263; asm: 1,732; pascal: 1,565; perl: 248; lisp: 222; xml: 42
file content (58 lines) | stat: -rw-r--r-- 1,817 bytes parent folder | download | duplicates (6)
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
#include <node.h>
#include <node_buffer.h>
#include <zlib.h>
#include <assert.h>

namespace {

inline void CompressBytes(const v8::FunctionCallbackInfo<v8::Value>& info) {
  assert(info[0]->IsArrayBufferView());
  auto view = info[0].As<v8::ArrayBufferView>();
  auto byte_offset = view->ByteOffset();
  auto byte_length = view->ByteLength();
  assert(view->HasBuffer());
  auto buffer = view->Buffer();
  auto contents = buffer->GetBackingStore();
  auto data = static_cast<unsigned char*>(contents->Data()) + byte_offset;

  Bytef buf[1024];

  z_stream stream;
  stream.zalloc = nullptr;
  stream.zfree = nullptr;

  int err = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
                         -15, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  assert(err == Z_OK);

  stream.avail_in = byte_length;
  stream.next_in = data;
  stream.avail_out = sizeof(buf);
  stream.next_out = buf;
  err = deflate(&stream, Z_FINISH);
  assert(err == Z_STREAM_END);

  auto result = node::Buffer::Copy(info.GetIsolate(),
                                   reinterpret_cast<const char*>(buf),
                                   sizeof(buf) - stream.avail_out);

  deflateEnd(&stream);

  info.GetReturnValue().Set(result.ToLocalChecked());
}

inline void Initialize(v8::Local<v8::Object> exports,
                       v8::Local<v8::Value> module,
                       v8::Local<v8::Context> context) {
  auto isolate = context->GetIsolate();
  auto key = v8::String::NewFromUtf8(
      isolate, "compressBytes").ToLocalChecked();
  auto value = v8::FunctionTemplate::New(isolate, CompressBytes)
                   ->GetFunction(context)
                   .ToLocalChecked();
  assert(exports->Set(context, key, value).IsJust());
}

}  // anonymous namespace

NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize)