forked from ably/xdelta-async-nodejs-addon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXdeltaEncodeAsyncWorker.cc
84 lines (70 loc) · 3.23 KB
/
XdeltaEncodeAsyncWorker.cc
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
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <map>
#include <napi.h>
#include <xdelta3.h>
#include <XdeltaEncodeAsyncWorker.h>
using namespace std;
using namespace Napi;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
#define JS_MAX_SAFE_INTEGER 0x1FFFFFFFFFFFFF
map<int64_t, XdeltaEncodeAsyncWorker *> XdeltaEncodeAsyncWorker::runningEncoders = map<int64_t, XdeltaEncodeAsyncWorker *>();
XdeltaEncodeAsyncWorker::XdeltaEncodeAsyncWorker(int64_t id,
Buffer<uint8_t> &dictionary,
Buffer<uint8_t> &target,
Buffer<uint8_t> &result,
int32_t stringMatcherType,
Function& callback) : BaseXdeltaAsyncWorker(dictionary,
target,
result,
callback),
id(id),
cancellationRequested(0),
stringMatcherType(stringMatcherType)
{
}
XdeltaEncodeAsyncWorker::~XdeltaEncodeAsyncWorker()
{
XdeltaEncodeAsyncWorker::runningEncoders.erase(id);
}
void XdeltaEncodeAsyncWorker::Execute()
{
res = xd3_encode_memory_enhanced(inputPtr,
inputLength,
dictionaryPtr,
dictionaryLength,
resultPtr,
&bytesWritten,
resultLength,
0,
&cancellationRequested,
(xd3_smatch_cfg)stringMatcherType);
}
void XdeltaEncodeAsyncWorker::RequestCancellation()
{
cancellationRequested = 1;
}
int64_t XdeltaEncodeAsyncWorker::GetNewEncoderId() {
static int64_t nextEncoderId = 0;
int64_t encoderId = nextEncoderId;
nextEncoderId = (encoderId + 1) % JS_MAX_SAFE_INTEGER;
return encoderId;
}
string XdeltaEncodeAsyncWorker::New(Buffer<uint8_t> &dictionary,
Buffer<uint8_t> &target,
Buffer<uint8_t> &result,
int32_t stringMatcherType,
Function& callback,
XdeltaEncodeAsyncWorker **encoder)
{
int64_t encoderId = GetNewEncoderId();
*encoder = new XdeltaEncodeAsyncWorker(encoderId, dictionary, target, result, stringMatcherType, callback);
XdeltaEncodeAsyncWorker::runningEncoders[encoderId] = *encoder;
return "";
}
string XdeltaEncodeAsyncWorker::RequestCancellation(int64_t id)
{
if (XdeltaEncodeAsyncWorker::runningEncoders.find(id) == XdeltaEncodeAsyncWorker::runningEncoders.end()) {
return "Encoder not found.";
}
XdeltaEncodeAsyncWorker::runningEncoders[id]->RequestCancellation();
return "";
}