/
HdtDocument.cc
654 lines (551 loc) · 23.7 KB
/
HdtDocument.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
#include <node.h>
#include <nan.h>
#include <assert.h>
#include <set>
#include <vector>
#include <HDTEnums.hpp>
#include <HDTManager.hpp>
#include <HDTVocabulary.hpp>
#include <LiteralDictionary.hpp>
#include "HdtDocument.h"
#include "../deps/libhdt/src/util/fileUtil.hpp"
using namespace v8;
using namespace hdt;
const uint32_t SELF = 0;
/******** Construction and destruction ********/
// Creates a new HDT document.
HdtDocument::HdtDocument(const Local<Object>& handle, HDT* hdt) : hdt(hdt), features(0) {
this->Wrap(handle);
// Determine supported features
if (hdt->getDictionary()->getType() == HDTVocabulary::DICTIONARY_TYPE_LITERAL)
features |= LiteralSearch;
}
// Deletes the HDT document.
HdtDocument::~HdtDocument() { Destroy(); }
// Destroys the document, disabling all further operations.
void HdtDocument::Destroy() {
if (hdt) {
delete hdt;
hdt = NULL;
}
}
// Constructs a JavaScript wrapper for an HDT document.
NAN_METHOD(HdtDocument::New) {
assert(info.IsConstructCall());
info.GetReturnValue().Set(info.This());
}
// Returns the constructor of HdtDocument.
Nan::Persistent<Function> constructor;
const Nan::Persistent<Function>& HdtDocument::GetConstructor() {
if (constructor.IsEmpty()) {
// Create constructor template
Local<FunctionTemplate> constructorTemplate = Nan::New<FunctionTemplate>(New);
constructorTemplate->SetClassName(Nan::New("HdtDocument").ToLocalChecked());
constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
// Create prototype
Nan::SetPrototypeMethod(constructorTemplate, "_searchTriples", SearchTriples);
Nan::SetPrototypeMethod(constructorTemplate, "_searchLiterals", SearchLiterals);
Nan::SetPrototypeMethod(constructorTemplate, "_searchTerms", SearchTerms);
Nan::SetPrototypeMethod(constructorTemplate, "_fetchDistinctTerms", FetchDistinctTerms);
Nan::SetPrototypeMethod(constructorTemplate, "_readHeader", ReadHeader);
Nan::SetPrototypeMethod(constructorTemplate, "_changeHeader", ChangeHeader);
Nan::SetPrototypeMethod(constructorTemplate, "_close", Close);
Nan::SetAccessor(constructorTemplate->PrototypeTemplate(),
Nan::New("_features").ToLocalChecked(), Features);
Nan::SetAccessor(constructorTemplate->PrototypeTemplate(),
Nan::New("closed").ToLocalChecked(), Closed);
// Set constructor
constructor.Reset(Nan::GetFunction(constructorTemplate).ToLocalChecked());
}
return constructor;
}
/******** createHdtDocument ********/
class CreateWorker : public Nan::AsyncWorker {
string filename;
HDT* hdt;
public:
CreateWorker(const char* filename, Nan::Callback *callback)
: Nan::AsyncWorker(callback), filename(filename), hdt(NULL) { };
void Execute() {
try { hdt = HDTManager::mapIndexedHDT(filename.c_str()); }
catch (const runtime_error error) { SetErrorMessage(error.what()); }
}
void HandleOKCallback() {
Nan::HandleScope scope;
// Create a new HdtDocument
Local<Object> newDocument = Nan::NewInstance(Nan::New(HdtDocument::GetConstructor())).ToLocalChecked();
new HdtDocument(newDocument, hdt);
// Send the new HdtDocument through the callback
const unsigned argc = 2;
Local<Value> argv[argc] = { Nan::Null(), newDocument };
callback->Call(argc, argv, async_resource);
}
};
// Creates a new instance of HdtDocument.
// JavaScript signature: createHdtDocument(filename, callback)
NAN_METHOD(HdtDocument::Create) {
assert(info.Length() == 2);
Nan::AsyncQueueWorker(new CreateWorker(*Nan::Utf8String(info[0]),
new Nan::Callback(info[1].As<Function>())));
}
/******** HdtDocument#_searchTriples ********/
class SearchTriplesWorker : public Nan::AsyncWorker {
HdtDocument* document;
// JavaScript function arguments
string subject, predicate, object;
uint32_t offset, limit;
// Callback return values
vector<TripleID> triples;
map<unsigned int, string> subjects, predicates, objects;
uint32_t totalCount;
bool hasExactCount;
public:
SearchTriplesWorker(HdtDocument* document, char* subject, char* predicate, char* object,
uint32_t offset, uint32_t limit, Nan::Callback* callback, Local<Object> self)
: Nan::AsyncWorker(callback),
document(document), subject(subject), predicate(predicate), object(object),
offset(offset), limit(limit), totalCount(0) {
SaveToPersistent(SELF, self);
};
void Execute() {
IteratorTripleID* it = NULL;
try {
// Prepare the triple pattern
Dictionary* dict = document->GetHDT()->getDictionary();
TripleString triple(subject, predicate, toHdtLiteral(object));
TripleID tripleId;
dict->tripleStringtoTripleID(triple, tripleId);
// If any of the components does not exist, there are no matches
if ((subject[0] && !tripleId.getSubject()) ||
(predicate[0] && !tripleId.getPredicate()) ||
(object[0] && !tripleId.getObject())) {
hasExactCount = true;
return;
}
// Estimate the total number of triples
it = document->GetHDT()->getTriples()->search(tripleId);
totalCount = it->estimatedNumResults();
hasExactCount = it->numResultEstimation() == EXACT;
// Go to the right offset
if (it->canGoTo())
try { it->skip(offset), offset = 0; }
catch (const runtime_error error) { /* invalid offset */ }
else
while (offset && it->hasNext()) it->next(), offset--;
// Add matching triples to the result vector
if (!offset) {
while (it->hasNext() && triples.size() < limit) {
TripleID& triple = *it->next();
triples.push_back(triple);
if (!subjects.count(triple.getSubject())) {
subjects[triple.getSubject()] = dict->idToString(triple.getSubject(), SUBJECT);
}
if (!predicates.count(triple.getPredicate())) {
predicates[triple.getPredicate()] = dict->idToString(triple.getPredicate(), PREDICATE);
}
if (!objects.count(triple.getObject())) {
string object(dict->idToString(triple.getObject(), OBJECT));
objects[triple.getObject()] = fromHdtLiteral(object);
}
}
}
}
catch (const runtime_error error) { SetErrorMessage(error.what()); }
if (it)
delete it;
}
void HandleOKCallback() {
Nan::HandleScope scope;
// Convert the triple components into strings
map<unsigned int, string>::const_iterator it;
map<unsigned int, Local<String> > subjectStrings, predicateStrings, objectStrings;
for (it = subjects.begin(); it != subjects.end(); it++)
subjectStrings[it->first] = Nan::New(it->second.c_str()).ToLocalChecked();
for (it = predicates.begin(); it != predicates.end(); it++)
predicateStrings[it->first] = Nan::New(it->second.c_str()).ToLocalChecked();
for (it = objects.begin(); it != objects.end(); it++)
objectStrings[it->first] = Nan::New(it->second.c_str()).ToLocalChecked();
// Convert the triples into a JavaScript object array
uint32_t count = 0;
Local<Array> triplesArray = Nan::New<Array>(triples.size());
const Local<String> SUBJECT = Nan::New("subject").ToLocalChecked();
const Local<String> PREDICATE = Nan::New("predicate").ToLocalChecked();
const Local<String> OBJECT = Nan::New("object").ToLocalChecked();
for (vector<TripleID>::const_iterator it = triples.begin(); it != triples.end(); it++) {
Local<Object> tripleObject = Nan::New<Object>();
Nan::Set(tripleObject, SUBJECT, subjectStrings[it->getSubject()]);
Nan::Set(tripleObject, PREDICATE, predicateStrings[it->getPredicate()]);
Nan::Set(tripleObject, OBJECT, objectStrings[it->getObject()]);
Nan::Set(triplesArray, count++, tripleObject);
}
// Send the JavaScript array and estimated total count through the callback
const unsigned argc = 4;
Local<Value> argv[argc] = { Nan::Null(), triplesArray,
Nan::New<Integer>((uint32_t)totalCount),
Nan::New<Boolean>((bool)hasExactCount) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), argc, argv, async_resource);
}
void HandleErrorCallback() {
Nan::HandleScope scope;
Local<Value> argv[] = { Exception::Error(Nan::New(ErrorMessage()).ToLocalChecked()) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
};
// Searches for a triple pattern in the document.
// JavaScript signature: HdtDocument#_searchTriples(subject, predicate, object, offset, limit, callback)
NAN_METHOD(HdtDocument::SearchTriples) {
assert(info.Length() == 6);
Nan::AsyncQueueWorker(new SearchTriplesWorker(Unwrap<HdtDocument>(info.This()),
*Nan::Utf8String(info[0]), *Nan::Utf8String(info[1]), *Nan::Utf8String(info[2]),
Nan::To<uint32_t>(info[3]).FromJust(), Nan::To<uint32_t>(info[4]).FromJust(),
new Nan::Callback(info[5].As<Function>()), info.This()));
}
/******** HdtDocument#_searchLiterals ********/
class SearchLiteralsWorker : public Nan::AsyncWorker {
HdtDocument* document;
// JavaScript function arguments
string substring;
uint32_t offset, limit;
// Callback return values
vector<string> literals;
uint32_t totalCount;
public:
SearchLiteralsWorker(HdtDocument* document, char* substring, uint32_t offset, uint32_t limit,
Nan::Callback* callback, Local<Object> self)
: Nan::AsyncWorker(callback), document(document),
substring(substring), offset(offset), limit(limit), totalCount(0) {
SaveToPersistent(SELF, self);
};
void Execute() {
if (!document->Supports(LiteralSearch)) {
SetErrorMessage("The HDT document does not support literal search");
return;
}
uint32_t* literalIds = NULL;
try {
// Find matching literal IDs
LiteralDictionary *dict = (LiteralDictionary*)(document->GetHDT()->getDictionary());
uint32_t literalCount = 0;
totalCount = dict->substringToId((unsigned char*)substring.c_str(), substring.length(),
offset, limit, false, &literalIds, &literalCount);
// Convert the literal IDs to strings
for (uint32_t *id = literalIds, *end = literalIds + literalCount; id != end; id++) {
string literal(dict->idToString(*id, OBJECT));
literals.push_back(fromHdtLiteral(literal));
}
}
catch (const runtime_error error) { SetErrorMessage(error.what()); }
if (literalIds)
delete[] literalIds;
}
void HandleOKCallback() {
Nan::HandleScope scope;
// Convert the literals into a JavaScript array
uint32_t count = 0;
Local<Array> literalsArray = Nan::New<Array>(literals.size());
for (vector<string>::const_iterator it = literals.begin(); it != literals.end(); it++)
Nan::Set(literalsArray, count++, Nan::New(*it).ToLocalChecked());
// Send the JavaScript array and estimated total count through the callback
const unsigned argc = 4;
Local<Value> argv[argc] = { Nan::Null(), literalsArray,
Nan::New<Integer>((uint32_t)totalCount),
Nan::New<Boolean>(true) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), argc, argv, async_resource);
}
void HandleErrorCallback() {
Nan::HandleScope scope;
Local<Value> argv[] = { Exception::Error(Nan::New(ErrorMessage()).ToLocalChecked()) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
};
// Searches for a triple pattern in the document.
// JavaScript signature: HdtDocument#_searchLiterals(substring, offset, limit, callback)
NAN_METHOD(HdtDocument::SearchLiterals) {
assert(info.Length() == 4);
Nan::AsyncQueueWorker(new SearchLiteralsWorker(Unwrap<HdtDocument>(info.This()),
*Nan::Utf8String(info[0]),
Nan::To<uint32_t>(info[1]).FromJust(), Nan::To<uint32_t>(info[2]).FromJust(),
new Nan::Callback(info[3].As<Function>()), info.This()));
}
/******** HdtDocument#_searchTerms ********/
class SearchTermsWorker : public Nan::AsyncWorker {
HdtDocument* document;
// JavaScript function arguments
string base;
uint32_t limit;
hdt::TripleComponentRole position;
// Callback return values
vector<string> suggestions;
public:
SearchTermsWorker(HdtDocument* document, char* base, uint32_t limit, uint32_t posId,
Nan::Callback* callback, Local<Object> self)
: Nan::AsyncWorker(callback),
document(document), base(base), limit(limit), position((TripleComponentRole) posId) {
SaveToPersistent(SELF, self);
};
void Execute() {
try {
Dictionary* dict = document->GetHDT()->getDictionary();
dict->getSuggestions(base.c_str(), position, suggestions, limit);
}
catch (const runtime_error error) { SetErrorMessage(error.what()); }
}
void HandleOKCallback() {
Nan::HandleScope scope;
// Convert the suggestions into a JavaScript array
uint32_t count = 0;
Local<Array> suggestionsArray = Nan::New<Array>(suggestions.size());
for (vector<string>::const_iterator it = suggestions.begin(); it != suggestions.end(); it++)
Nan::Set(suggestionsArray, count++, Nan::New(*it).ToLocalChecked());
// Send the JavaScript array and estimated total count through the callback
const unsigned argc = 2;
Local<Value> argv[argc] = { Nan::Null(), suggestionsArray};
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), argc, argv, async_resource);
}
void HandleErrorCallback() {
Nan::HandleScope scope;
Local<Value> argv[] = { Exception::Error(Nan::New(ErrorMessage()).ToLocalChecked()) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
};
// Searches terms based on a given string over a specific position.
// JavaScript signature: HdtDocument#_searchTerms(prefix, limit, position, callback)
NAN_METHOD(HdtDocument::SearchTerms) {
assert(info.Length() == 4);
Nan::AsyncQueueWorker(new SearchTermsWorker(Unwrap<HdtDocument>(info.This()),
*Nan::Utf8String(info[0]), Nan::To<uint32_t>(info[1]).FromJust(), Nan::To<uint32_t>(info[2]).FromJust(),
new Nan::Callback(info[3].As<Function>()), info.This()));
}
/******** HdtDocument#_readHeader ********/
class ReadHeaderWorker : public Nan::AsyncWorker {
HdtDocument* document;
// Callback return values
string headerString;
public:
ReadHeaderWorker(HdtDocument* document, Nan::Callback* callback, Local<Object> self)
: Nan::AsyncWorker(callback), document(document), headerString("") {
SaveToPersistent(SELF, self);
};
void Execute() {
IteratorTripleString *it = NULL;
try {
Header *header = document->GetHDT()->getHeader();
IteratorTripleString *it = header->search("","","");
// Create header string.
while (it->hasNext()) {
TripleString *ts = it->next();
headerString += ts->getSubject();
headerString += " ";
headerString += ts->getPredicate();
headerString += " ";
headerString += ts->getObject();
headerString += " .\n";
}
}
catch (const runtime_error error) { SetErrorMessage(error.what()); }
if (it)
delete it;
}
void HandleOKCallback() {
Nan::HandleScope scope;
// Convert header string to Local<String>.
Local<String> nanHeader = Nan::New(headerString).ToLocalChecked();
// Send the header string through the callback.
const unsigned argc = 2;
Local<Value> argv[argc] = { Nan::Null(), nanHeader };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), argc, argv, async_resource);
}
void HandleErrorCallback() {
Nan::HandleScope scope;
Local<Value> argv[] = { Exception::Error(Nan::New(ErrorMessage()).ToLocalChecked()) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
};
// Returns the header of the hdt document as a string.
// JavaScript signature: HdtDocument#_readHeader(callback)
NAN_METHOD(HdtDocument::ReadHeader) {
assert(info.Length() == 1);
Nan::AsyncQueueWorker(new ReadHeaderWorker(Unwrap<HdtDocument>(info.This()),
new Nan::Callback(info[0].As<Function>()), info.This()));
}
/******** HdtDocument#_changeHeader ********/
class ChangeHeaderWorker : public Nan::AsyncWorker {
HdtDocument* document;
// JavaScript function arguments
string headerString;
string outputFile;
public:
ChangeHeaderWorker(HdtDocument* document, string headerString, string outputFile,
Nan::Callback* callback, Local<Object> self)
: Nan::AsyncWorker(callback), document(document),
headerString(headerString), outputFile(outputFile) {
SaveToPersistent(SELF, self);
};
void Execute() {
try {
// Get and clear current header.
Header *header = document->GetHDT()->getHeader();
header->clear();
// Replace header.
istringstream in(headerString, ios::binary);
ControlInformation ci;
ci.setFormat(HDTVocabulary::HEADER_NTRIPLES);
ci.setUint("length", fileUtil::getSize(in));
header->load(in, ci);
// Save
document->GetHDT()->saveToHDT(outputFile.c_str());
}
catch (const runtime_error error) { SetErrorMessage(error.what()); }
}
void HandleOKCallback() {
Nan::HandleScope scope;
const unsigned argc = 1;
Local<Value> argv[argc] = { Nan::Null() };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
void HandleErrorCallback() {
Nan::HandleScope scope;
Local<Value> argv[] = { Exception::Error(Nan::New(ErrorMessage()).ToLocalChecked()) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
};
// Replaces the current header with a new one and saves result to a new file.
// JavaScript signature: HdtDocument#_changeHeader(header, outputFile, callback)
NAN_METHOD(HdtDocument::ChangeHeader) {
assert(info.Length() == 3);
Nan::AsyncQueueWorker(new ChangeHeaderWorker(Unwrap<HdtDocument>(info.This()),
*Nan::Utf8String(info[0]), *Nan::Utf8String(info[1]),
new Nan::Callback(info[2].As<Function>()), info.This()));
}
/******** HdtDocument#_fetchDistinctTerms ********/
class FetchDistinctTermsWorker : public Nan::AsyncWorker {
HdtDocument* document;
// JavaScript function arguments
string subject;
string object;
uint32_t limit;
// Callback return values
vector<string> distinctTerms;
public:
FetchDistinctTermsWorker(HdtDocument* document, char* subject, char* object, uint32_t limit,
uint32_t posId, Nan::Callback* callback, Local<Object> self)
: Nan::AsyncWorker(callback), document(document), subject(subject), object(object), limit(limit) {
assert(posId == hdt::PREDICATE); // only predicate is supported currently
SaveToPersistent(SELF, self);
};
void Execute() {
hdt::IteratorUCharString *terms = NULL;
try {
Dictionary* dict = document->GetHDT()->getDictionary();
terms = dict->getPredicates();
// Iterate over all predicates
while (distinctTerms.size() < limit && terms->hasNext()) {
const char* predicate = reinterpret_cast<char*>(terms->next());
// Check whether a triple with this predicate and subject or object exists
hdt::IteratorTripleString *it = document->GetHDT()->search(subject.c_str(), predicate, object.c_str());
if (it->hasNext())
distinctTerms.push_back(predicate);
delete it;
delete[] predicate;
}
}
catch (const runtime_error error) { SetErrorMessage(error.what()); }
if (terms)
delete terms;
}
void HandleOKCallback() {
Nan::HandleScope scope;
// Convert the distinctTerms into a JavaScript array
uint32_t count = 0;
Local<Array> distinctTermsArray = Nan::New<Array>(distinctTerms.size());
for (vector<string>::const_iterator it = distinctTerms.begin(); it != distinctTerms.end(); it++)
Nan::Set(distinctTermsArray, count++, Nan::New(*it).ToLocalChecked());
// Send the JavaScript array through the callback
const unsigned argc = 2;
Local<Value> argv[argc] = { Nan::Null(), distinctTermsArray};
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), argc, argv, async_resource);
}
void HandleErrorCallback() {
Nan::HandleScope scope;
Local<Value> argv[] = { Exception::Error(Nan::New(ErrorMessage()).ToLocalChecked()) };
callback->Call(Nan::To<v8::Object>(GetFromPersistent(SELF)).ToLocalChecked(), 1, argv, async_resource);
}
};
// Fetches distinct list of predicates given an object.
// JavaScript signature: HdtDocument#_fetchDistinctTerms(object, limit, position, callback)
NAN_METHOD(HdtDocument::FetchDistinctTerms) {
assert(info.Length() == 5);
Nan::AsyncQueueWorker(new FetchDistinctTermsWorker(Unwrap<HdtDocument>(info.This()),
*Nan::Utf8String(info[0]), *Nan::Utf8String(info[1]), Nan::To<uint32_t>(info[2]).FromJust(), Nan::To<uint32_t>(info[3]).FromJust(),
new Nan::Callback(info[4].As<Function>()), info.This()));
}
/******** HdtDocument#features ********/
// Gets a bitvector indicating the supported features.
NAN_PROPERTY_GETTER(HdtDocument::Features) {
HdtDocument* hdtDocument = Unwrap<HdtDocument>(info.This());
info.GetReturnValue().Set(Nan::New<Integer>(hdtDocument->features));
}
/******** HdtDocument#close ********/
// Closes the document, disabling all further operations.
// JavaScript signature: HdtDocument#close(callback)
NAN_METHOD(HdtDocument::Close) {
assert(info.Length() == 1);
// Destroy the current document
HdtDocument* hdtDocument = Unwrap<HdtDocument>(info.This());
hdtDocument->Destroy();
// Call the callback
const Local<Function> callback = info[0].As<Function>();
const unsigned argc = 1;
Local<Value> argv[argc] = { Nan::Null() };
Nan::Call(callback, Nan::GetCurrentContext()->Global(), argc, argv);
}
/******** HdtDocument#closed ********/
// Gets a boolean indicating whether the document is closed.
NAN_PROPERTY_GETTER(HdtDocument::Closed) {
HdtDocument* hdtDocument = Unwrap<HdtDocument>(info.This());
info.GetReturnValue().Set(Nan::New<Boolean>(!hdtDocument->hdt));
}
/******** Utility functions ********/
// The JavaScript representation for a literal with a datatype is
// "literal"^^http://example.org/datatype
// whereas the HDT representation is
// "literal"^^<http://example.org/datatype>
// The functions below convert when needed.
// Converts a JavaScript literal to an HDT literal
string& toHdtLiteral(string& literal) {
// Check if the object is a literal with a datatype, which needs conversion
string::const_iterator obj;
string::iterator objLast;
if (*(obj = literal.begin()) == '"' && *(objLast = literal.end() - 1) != '"') {
// If the start of a datatype was found, surround it with angular brackets
string::const_iterator datatype = objLast;
while (obj != --datatype && *datatype != '"' && *datatype != '^');
if (*datatype == '^') {
// Allocate space for brackets, and update iterators
literal.resize(literal.length() + 2);
datatype += (literal.begin() - obj) + 1;
objLast = literal.end() - 1;
// Add brackets
*objLast = '>';
while (--objLast != datatype)
*objLast = *(objLast - 1);
*objLast = '<';
}
}
return literal;
}
// Converts an HDT literal to a JavaScript literal
string& fromHdtLiteral(string& literal) {
// Check if the literal has a datatype, which needs conversion
string::const_iterator obj;
string::iterator objLast;
if (*(obj = literal.begin()) == '"' && *(objLast = literal.end() - 1) == '>') {
// Find the start of the datatype
string::iterator datatype = objLast;
while (obj != --datatype && *datatype != '<');
// Change the datatype representation by removing angular brackets
if (*datatype == '<')
literal.erase(datatype), literal.erase(objLast - 1);
}
return literal;
}