-
Notifications
You must be signed in to change notification settings - Fork 15
/
icuWrapper.cpp
76 lines (57 loc) · 2.02 KB
/
icuWrapper.cpp
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
#include <nan.h>
#include <node.h>
#include <unicode/ucsdet.h>
NAN_METHOD(DetectCharacterEncoding) {
Nan::HandleScope scope;
v8::Local<v8::Object> inputBuffer =
Nan::To<v8::Object>(info[0]).ToLocalChecked();
UCharsetDetector *charsetDetector;
const UCharsetMatch *charsetMatch;
UErrorCode errorCode = U_ZERO_ERROR;
charsetDetector = ucsdet_open(&errorCode);
if (U_FAILURE(errorCode)) {
Nan::ThrowError("Failed to open ICU charset detector.");
return;
}
ucsdet_setText(charsetDetector, node::Buffer::Data(inputBuffer),
node::Buffer::Length(inputBuffer), &errorCode);
if (U_FAILURE(errorCode)) {
Nan::ThrowError("Failed to set ICU charset detector’s text.");
ucsdet_close(charsetDetector);
return;
}
charsetMatch = ucsdet_detect(charsetDetector, &errorCode);
if (U_FAILURE(errorCode)) {
Nan::ThrowError("Failed to detect charset.");
ucsdet_close(charsetDetector);
return;
}
if (charsetMatch == NULL) {
info.GetReturnValue().Set(Nan::Null());
ucsdet_close(charsetDetector);
return;
}
const char *charsetName = ucsdet_getName(charsetMatch, &errorCode);
if (U_FAILURE(errorCode)) {
Nan::ThrowError("Failed to get name from charset match.");
ucsdet_close(charsetDetector);
return;
}
int32_t confidence = ucsdet_getConfidence(charsetMatch, &errorCode);
if (U_FAILURE(errorCode)) {
Nan::ThrowError("Failed to get confidence from charset match.");
ucsdet_close(charsetDetector);
return;
}
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
Nan::Set(obj, Nan::New<v8::String>("encoding").ToLocalChecked(),
Nan::New<v8::String>(charsetName).ToLocalChecked());
Nan::Set(obj, Nan::New<v8::String>("confidence").ToLocalChecked(),
Nan::New<v8::Number>(confidence));
info.GetReturnValue().Set(obj);
ucsdet_close(charsetDetector);
}
void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
Nan::SetMethod(module, "exports", DetectCharacterEncoding);
}
NODE_MODULE(icuWrapper, Init);