forked from freezer333/cppwebify-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddon.cpp
More file actions
71 lines (52 loc) · 1.65 KB
/
addon.cpp
File metadata and controls
71 lines (52 loc) · 1.65 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <nan.h>
#include <functional>
#include <iostream>
#include "exchange.h"
#include "prime_sieve.h"
using namespace Nan;
using namespace std;
using namespace v8;
class PrimeWorker : public AsyncWorker {
public:
PrimeWorker(Callback *callback, int under)
: AsyncWorker(callback), under(under), primes(0) {}
~PrimeWorker() {}
void Execute () {
Exchange x(
[&](void * data) {
primes.push_back(*((int *) data));
}
);
generate_primes(under, (void*)&x);
}
// We have the results, and we're back in the event loop.
void HandleOKCallback () {
Nan:: HandleScope scope;
v8::Local<v8::Array> results = New<v8::Array>(primes.size());
int i = 0;
for_each(primes.begin(), primes.end(),
[&](int value) {
Nan::Set(results, i, New<v8::Number>(value));
i++;
});
Local<Value> argv[] = {
Null(),
results
};
callback->Call(2, argv);
}
private:
int under;
vector<int> primes;
};
// Asynchronous access to the `getPrimes()` function
NAN_METHOD(CalculatePrimes) {
int under = To<int>(info[0]).FromJust();
Callback *callback = new Callback(info[1].As<Function>());
AsyncQueueWorker(new PrimeWorker(callback, under));
}
NAN_MODULE_INIT(Init) {
Nan::Set(target, New<String>("getPrimes").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(CalculatePrimes)).ToLocalChecked());
}
NODE_MODULE(addon, Init)