nan.h 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952
  1. /*********************************************************************
  2. * NAN - Native Abstractions for Node.js
  3. *
  4. * Copyright (c) 2018 NAN contributors:
  5. * - Rod Vagg <https://github.com/rvagg>
  6. * - Benjamin Byholm <https://github.com/kkoopa>
  7. * - Trevor Norris <https://github.com/trevnorris>
  8. * - Nathan Rajlich <https://github.com/TooTallNate>
  9. * - Brett Lawson <https://github.com/brett19>
  10. * - Ben Noordhuis <https://github.com/bnoordhuis>
  11. * - David Siegel <https://github.com/agnat>
  12. * - Michael Ira Krufky <https://github.com/mkrufky>
  13. *
  14. * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
  15. *
  16. * Version 2.17.0: current Node 18.10.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1
  17. *
  18. * See https://github.com/nodejs/nan for the latest update to this file
  19. **********************************************************************************/
  20. #ifndef NAN_H_
  21. #define NAN_H_
  22. #include <node_version.h>
  23. #define NODE_0_10_MODULE_VERSION 11
  24. #define NODE_0_12_MODULE_VERSION 14
  25. #define ATOM_0_21_MODULE_VERSION 41
  26. #define IOJS_1_0_MODULE_VERSION 42
  27. #define IOJS_1_1_MODULE_VERSION 43
  28. #define IOJS_2_0_MODULE_VERSION 44
  29. #define IOJS_3_0_MODULE_VERSION 45
  30. #define NODE_4_0_MODULE_VERSION 46
  31. #define NODE_5_0_MODULE_VERSION 47
  32. #define NODE_6_0_MODULE_VERSION 48
  33. #define NODE_7_0_MODULE_VERSION 51
  34. #define NODE_8_0_MODULE_VERSION 57
  35. #define NODE_9_0_MODULE_VERSION 59
  36. #define NODE_10_0_MODULE_VERSION 64
  37. #define NODE_11_0_MODULE_VERSION 67
  38. #define NODE_12_0_MODULE_VERSION 72
  39. #define NODE_13_0_MODULE_VERSION 79
  40. #define NODE_14_0_MODULE_VERSION 83
  41. #define NODE_15_0_MODULE_VERSION 88
  42. #define NODE_16_0_MODULE_VERSION 93
  43. #define NODE_17_0_MODULE_VERSION 102
  44. #define NODE_18_0_MODULE_VERSION 108
  45. #ifdef _MSC_VER
  46. # define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800)
  47. #else
  48. # define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L)
  49. #endif
  50. #if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11
  51. # error This version of node/NAN/v8 requires a C++11 compiler
  52. #endif
  53. #include <uv.h>
  54. #include <node.h>
  55. #include <node_buffer.h>
  56. #include <node_object_wrap.h>
  57. #include <algorithm>
  58. #include <cstring>
  59. #include <climits>
  60. #include <cstdlib>
  61. #include <utility>
  62. #if defined(_MSC_VER)
  63. # pragma warning( push )
  64. # pragma warning( disable : 4530 )
  65. # include <queue>
  66. # include <string>
  67. # include <vector>
  68. # pragma warning( pop )
  69. #else
  70. # include <queue>
  71. # include <string>
  72. # include <vector>
  73. #endif
  74. // uv helpers
  75. #ifdef UV_VERSION_MAJOR
  76. # ifndef UV_VERSION_PATCH
  77. # define UV_VERSION_PATCH 0
  78. # endif
  79. # define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \
  80. (UV_VERSION_MINOR << 8) | \
  81. (UV_VERSION_PATCH))
  82. #else
  83. # define NAUV_UVVERSION 0x000b00
  84. #endif
  85. #if NAUV_UVVERSION < 0x000b0b
  86. # ifdef WIN32
  87. # include <windows.h>
  88. # else
  89. # include <pthread.h>
  90. # endif
  91. #endif
  92. namespace Nan {
  93. #define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b)
  94. #define NAN_CONCAT_HELPER(a, b) a##b
  95. #define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0.
  96. #if defined(__GNUC__) && \
  97. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  98. # define NAN_DEPRECATED __attribute__((deprecated))
  99. #elif defined(_MSC_VER) && \
  100. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  101. # define NAN_DEPRECATED __declspec(deprecated)
  102. #else
  103. # define NAN_DEPRECATED
  104. #endif
  105. #if NAN_HAS_CPLUSPLUS_11
  106. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
  107. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
  108. # define NAN_DISALLOW_MOVE(CLASS) \
  109. CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \
  110. void operator=(CLASS&&) = delete;
  111. #else
  112. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&);
  113. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&);
  114. # define NAN_DISALLOW_MOVE(CLASS)
  115. #endif
  116. #define NAN_DISALLOW_ASSIGN_COPY(CLASS) \
  117. NAN_DISALLOW_ASSIGN(CLASS) \
  118. NAN_DISALLOW_COPY(CLASS)
  119. #define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \
  120. NAN_DISALLOW_ASSIGN(CLASS) \
  121. NAN_DISALLOW_MOVE(CLASS)
  122. #define NAN_DISALLOW_COPY_MOVE(CLASS) \
  123. NAN_DISALLOW_COPY(CLASS) \
  124. NAN_DISALLOW_MOVE(CLASS)
  125. #define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \
  126. NAN_DISALLOW_ASSIGN(CLASS) \
  127. NAN_DISALLOW_COPY(CLASS) \
  128. NAN_DISALLOW_MOVE(CLASS)
  129. #define TYPE_CHECK(T, S) \
  130. while (false) { \
  131. *(static_cast<T *volatile *>(0)) = static_cast<S*>(0); \
  132. }
  133. //=== RegistrationFunction =====================================================
  134. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  135. typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  136. #else
  137. typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  138. #endif
  139. #define NAN_MODULE_INIT(name) \
  140. void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target)
  141. #if NODE_MAJOR_VERSION >= 10 || \
  142. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3
  143. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  144. extern "C" NODE_MODULE_EXPORT void \
  145. NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)( \
  146. v8::Local<v8::Object> exports, v8::Local<v8::Value> module, \
  147. v8::Local<v8::Context> context) \
  148. { \
  149. registration(exports); \
  150. }
  151. #else
  152. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  153. NODE_MODULE(module_name, registration)
  154. #endif
  155. //=== CallbackInfo =============================================================
  156. #include "nan_callbacks.h" // NOLINT(build/include)
  157. //==============================================================================
  158. #if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION)
  159. typedef v8::Script UnboundScript;
  160. typedef v8::Script BoundScript;
  161. #else
  162. typedef v8::UnboundScript UnboundScript;
  163. typedef v8::Script BoundScript;
  164. #endif
  165. #if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION)
  166. typedef v8::String::ExternalAsciiStringResource
  167. ExternalOneByteStringResource;
  168. #else
  169. typedef v8::String::ExternalOneByteStringResource
  170. ExternalOneByteStringResource;
  171. #endif
  172. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  173. template<typename T>
  174. class NonCopyablePersistentTraits :
  175. public v8::NonCopyablePersistentTraits<T> {};
  176. template<typename T>
  177. class CopyablePersistentTraits :
  178. public v8::CopyablePersistentTraits<T> {};
  179. template<typename T>
  180. class PersistentBase :
  181. public v8::PersistentBase<T> {};
  182. template<typename T, typename M = v8::NonCopyablePersistentTraits<T> >
  183. class Persistent;
  184. #else
  185. template<typename T> class NonCopyablePersistentTraits;
  186. template<typename T> class PersistentBase;
  187. template<typename T, typename P> class WeakCallbackData;
  188. template<typename T, typename M = NonCopyablePersistentTraits<T> >
  189. class Persistent;
  190. #endif // NODE_MODULE_VERSION
  191. template<typename T>
  192. class Maybe {
  193. public:
  194. inline bool IsNothing() const { return !has_value_; }
  195. inline bool IsJust() const { return has_value_; }
  196. inline T ToChecked() const { return FromJust(); }
  197. inline void Check() const { FromJust(); }
  198. inline bool To(T* out) const {
  199. if (IsJust()) *out = value_;
  200. return IsJust();
  201. }
  202. inline T FromJust() const {
  203. #if defined(V8_ENABLE_CHECKS)
  204. assert(IsJust() && "FromJust is Nothing");
  205. #endif // V8_ENABLE_CHECKS
  206. return value_;
  207. }
  208. inline T FromMaybe(const T& default_value) const {
  209. return has_value_ ? value_ : default_value;
  210. }
  211. inline bool operator==(const Maybe &other) const {
  212. return (IsJust() == other.IsJust()) &&
  213. (!IsJust() || FromJust() == other.FromJust());
  214. }
  215. inline bool operator!=(const Maybe &other) const {
  216. return !operator==(other);
  217. }
  218. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  219. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  220. // Allow implicit conversions from v8::Maybe<T> to Nan::Maybe<T>.
  221. Maybe(const v8::Maybe<T>& that) // NOLINT(runtime/explicit)
  222. : has_value_(that.IsJust())
  223. , value_(that.FromMaybe(T())) {}
  224. #endif
  225. private:
  226. Maybe() : has_value_(false) {}
  227. explicit Maybe(const T& t) : has_value_(true), value_(t) {}
  228. bool has_value_;
  229. T value_;
  230. template<typename U>
  231. friend Maybe<U> Nothing();
  232. template<typename U>
  233. friend Maybe<U> Just(const U& u);
  234. };
  235. template<typename T>
  236. inline Maybe<T> Nothing() {
  237. return Maybe<T>();
  238. }
  239. template<typename T>
  240. inline Maybe<T> Just(const T& t) {
  241. return Maybe<T>(t);
  242. }
  243. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  244. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  245. # include "nan_maybe_43_inl.h" // NOLINT(build/include)
  246. #else
  247. # include "nan_maybe_pre_43_inl.h" // NOLINT(build/include)
  248. #endif
  249. #include "nan_converters.h" // NOLINT(build/include)
  250. #include "nan_new.h" // NOLINT(build/include)
  251. #if NAUV_UVVERSION < 0x000b17
  252. #define NAUV_WORK_CB(func) \
  253. void func(uv_async_t *async, int)
  254. #else
  255. #define NAUV_WORK_CB(func) \
  256. void func(uv_async_t *async)
  257. #endif
  258. #if NAUV_UVVERSION >= 0x000b0b
  259. typedef uv_key_t nauv_key_t;
  260. inline int nauv_key_create(nauv_key_t *key) {
  261. return uv_key_create(key);
  262. }
  263. inline void nauv_key_delete(nauv_key_t *key) {
  264. uv_key_delete(key);
  265. }
  266. inline void* nauv_key_get(nauv_key_t *key) {
  267. return uv_key_get(key);
  268. }
  269. inline void nauv_key_set(nauv_key_t *key, void *value) {
  270. uv_key_set(key, value);
  271. }
  272. #else
  273. /* Implement thread local storage for older versions of libuv.
  274. * This is essentially a backport of libuv commit 5d2434bf
  275. * written by Ben Noordhuis, adjusted for names and inline.
  276. */
  277. #ifndef WIN32
  278. typedef pthread_key_t nauv_key_t;
  279. inline int nauv_key_create(nauv_key_t* key) {
  280. return -pthread_key_create(key, NULL);
  281. }
  282. inline void nauv_key_delete(nauv_key_t* key) {
  283. if (pthread_key_delete(*key))
  284. abort();
  285. }
  286. inline void* nauv_key_get(nauv_key_t* key) {
  287. return pthread_getspecific(*key);
  288. }
  289. inline void nauv_key_set(nauv_key_t* key, void* value) {
  290. if (pthread_setspecific(*key, value))
  291. abort();
  292. }
  293. #else
  294. typedef struct {
  295. DWORD tls_index;
  296. } nauv_key_t;
  297. inline int nauv_key_create(nauv_key_t* key) {
  298. key->tls_index = TlsAlloc();
  299. if (key->tls_index == TLS_OUT_OF_INDEXES)
  300. return UV_ENOMEM;
  301. return 0;
  302. }
  303. inline void nauv_key_delete(nauv_key_t* key) {
  304. if (TlsFree(key->tls_index) == FALSE)
  305. abort();
  306. key->tls_index = TLS_OUT_OF_INDEXES;
  307. }
  308. inline void* nauv_key_get(nauv_key_t* key) {
  309. void* value = TlsGetValue(key->tls_index);
  310. if (value == NULL)
  311. if (GetLastError() != ERROR_SUCCESS)
  312. abort();
  313. return value;
  314. }
  315. inline void nauv_key_set(nauv_key_t* key, void* value) {
  316. if (TlsSetValue(key->tls_index, value) == FALSE)
  317. abort();
  318. }
  319. #endif
  320. #endif
  321. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  322. template<typename T>
  323. v8::Local<T> New(v8::Handle<T>);
  324. #endif
  325. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  326. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  327. typedef v8::WeakCallbackType WeakCallbackType;
  328. #else
  329. struct WeakCallbackType {
  330. enum E {kParameter, kInternalFields};
  331. E type;
  332. WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit)
  333. inline bool operator==(E other) { return other == this->type; }
  334. inline bool operator!=(E other) { return !operator==(other); }
  335. };
  336. #endif
  337. template<typename P> class WeakCallbackInfo;
  338. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  339. # include "nan_persistent_12_inl.h" // NOLINT(build/include)
  340. #else
  341. # include "nan_persistent_pre_12_inl.h" // NOLINT(build/include)
  342. #endif
  343. namespace imp {
  344. static const size_t kMaxLength = 0x3fffffff;
  345. // v8::String::REPLACE_INVALID_UTF8 was introduced
  346. // in node.js v0.10.29 and v0.8.27.
  347. #if NODE_MAJOR_VERSION > 0 || \
  348. NODE_MINOR_VERSION > 10 || \
  349. NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \
  350. NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27
  351. static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
  352. #else
  353. static const unsigned kReplaceInvalidUtf8 = 0;
  354. #endif
  355. } // end of namespace imp
  356. //=== HandleScope ==============================================================
  357. class HandleScope {
  358. v8::HandleScope scope;
  359. public:
  360. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  361. inline HandleScope() : scope(v8::Isolate::GetCurrent()) {}
  362. inline static int NumberOfHandles() {
  363. return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  364. }
  365. #else
  366. inline HandleScope() : scope() {}
  367. inline static int NumberOfHandles() {
  368. return v8::HandleScope::NumberOfHandles();
  369. }
  370. #endif
  371. private:
  372. // Make it hard to create heap-allocated or illegal handle scopes by
  373. // disallowing certain operations.
  374. HandleScope(const HandleScope &);
  375. void operator=(const HandleScope &);
  376. void *operator new(size_t size);
  377. void operator delete(void *, size_t) {
  378. abort();
  379. }
  380. };
  381. class EscapableHandleScope {
  382. public:
  383. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  384. inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {}
  385. inline static int NumberOfHandles() {
  386. return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  387. }
  388. template<typename T>
  389. inline v8::Local<T> Escape(v8::Local<T> value) {
  390. return scope.Escape(value);
  391. }
  392. private:
  393. v8::EscapableHandleScope scope;
  394. #else
  395. inline EscapableHandleScope() : scope() {}
  396. inline static int NumberOfHandles() {
  397. return v8::HandleScope::NumberOfHandles();
  398. }
  399. template<typename T>
  400. inline v8::Local<T> Escape(v8::Local<T> value) {
  401. return scope.Close(value);
  402. }
  403. private:
  404. v8::HandleScope scope;
  405. #endif
  406. private:
  407. // Make it hard to create heap-allocated or illegal handle scopes by
  408. // disallowing certain operations.
  409. EscapableHandleScope(const EscapableHandleScope &);
  410. void operator=(const EscapableHandleScope &);
  411. void *operator new(size_t size);
  412. void operator delete(void *, size_t) {
  413. abort();
  414. }
  415. };
  416. //=== TryCatch =================================================================
  417. class TryCatch {
  418. v8::TryCatch try_catch_;
  419. friend void FatalException(const TryCatch&);
  420. public:
  421. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  422. TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {}
  423. #endif
  424. inline bool HasCaught() const { return try_catch_.HasCaught(); }
  425. inline bool CanContinue() const { return try_catch_.CanContinue(); }
  426. inline v8::Local<v8::Value> ReThrow() {
  427. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  428. return New(try_catch_.ReThrow());
  429. #else
  430. return try_catch_.ReThrow();
  431. #endif
  432. }
  433. inline v8::Local<v8::Value> Exception() const {
  434. return try_catch_.Exception();
  435. }
  436. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  437. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  438. inline v8::MaybeLocal<v8::Value> StackTrace() const {
  439. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  440. v8::EscapableHandleScope scope(isolate);
  441. return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext())
  442. .FromMaybe(v8::Local<v8::Value>()));
  443. }
  444. #else
  445. inline MaybeLocal<v8::Value> StackTrace() const {
  446. return try_catch_.StackTrace();
  447. }
  448. #endif
  449. inline v8::Local<v8::Message> Message() const {
  450. return try_catch_.Message();
  451. }
  452. inline void Reset() { try_catch_.Reset(); }
  453. inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); }
  454. inline void SetCaptureMessage(bool value) {
  455. try_catch_.SetCaptureMessage(value);
  456. }
  457. };
  458. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  459. v8::Local<v8::Function> func,
  460. int argc,
  461. v8::Local<v8::Value>* argv);
  462. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  463. v8::Local<v8::String> symbol,
  464. int argc,
  465. v8::Local<v8::Value>* argv);
  466. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  467. const char* method,
  468. int argc,
  469. v8::Local<v8::Value>* argv);
  470. // === AsyncResource ===========================================================
  471. class AsyncResource {
  472. public:
  473. AsyncResource(
  474. v8::Local<v8::String> name
  475. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  476. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  477. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  478. if (resource.IsEmpty()) {
  479. resource = New<v8::Object>();
  480. }
  481. context = node::EmitAsyncInit(isolate, resource, name);
  482. #endif
  483. }
  484. AsyncResource(
  485. const char* name
  486. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  487. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  488. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  489. if (resource.IsEmpty()) {
  490. resource = New<v8::Object>();
  491. }
  492. v8::Local<v8::String> name_string =
  493. New<v8::String>(name).ToLocalChecked();
  494. context = node::EmitAsyncInit(isolate, resource, name_string);
  495. #endif
  496. }
  497. ~AsyncResource() {
  498. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  499. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  500. node::EmitAsyncDestroy(isolate, context);
  501. #endif
  502. }
  503. inline MaybeLocal<v8::Value> runInAsyncScope(
  504. v8::Local<v8::Object> target
  505. , v8::Local<v8::Function> func
  506. , int argc
  507. , v8::Local<v8::Value>* argv) {
  508. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  509. return MakeCallback(target, func, argc, argv);
  510. #else
  511. return node::MakeCallback(
  512. v8::Isolate::GetCurrent(), target, func, argc, argv, context);
  513. #endif
  514. }
  515. inline MaybeLocal<v8::Value> runInAsyncScope(
  516. v8::Local<v8::Object> target
  517. , v8::Local<v8::String> symbol
  518. , int argc
  519. , v8::Local<v8::Value>* argv) {
  520. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  521. return MakeCallback(target, symbol, argc, argv);
  522. #else
  523. return node::MakeCallback(
  524. v8::Isolate::GetCurrent(), target, symbol, argc, argv, context);
  525. #endif
  526. }
  527. inline MaybeLocal<v8::Value> runInAsyncScope(
  528. v8::Local<v8::Object> target
  529. , const char* method
  530. , int argc
  531. , v8::Local<v8::Value>* argv) {
  532. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  533. return MakeCallback(target, method, argc, argv);
  534. #else
  535. return node::MakeCallback(
  536. v8::Isolate::GetCurrent(), target, method, argc, argv, context);
  537. #endif
  538. }
  539. private:
  540. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource)
  541. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  542. node::async_context context;
  543. #endif
  544. };
  545. inline uv_loop_t* GetCurrentEventLoop() {
  546. #if NODE_MAJOR_VERSION >= 10 || \
  547. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \
  548. NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10
  549. return node::GetCurrentEventLoop(v8::Isolate::GetCurrent());
  550. #else
  551. return uv_default_loop();
  552. #endif
  553. }
  554. //============ =================================================================
  555. /* node 0.12 */
  556. #if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
  557. inline
  558. void SetCounterFunction(v8::CounterLookupCallback cb) {
  559. v8::Isolate::GetCurrent()->SetCounterFunction(cb);
  560. }
  561. inline
  562. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  563. v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb);
  564. }
  565. inline
  566. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  567. v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb);
  568. }
  569. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  570. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  571. inline bool IdleNotification(int idle_time_in_ms) {
  572. return v8::Isolate::GetCurrent()->IdleNotificationDeadline(
  573. idle_time_in_ms * 0.001);
  574. }
  575. # else
  576. inline bool IdleNotification(int idle_time_in_ms) {
  577. return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms);
  578. }
  579. #endif
  580. inline void LowMemoryNotification() {
  581. v8::Isolate::GetCurrent()->LowMemoryNotification();
  582. }
  583. inline void ContextDisposedNotification() {
  584. v8::Isolate::GetCurrent()->ContextDisposedNotification();
  585. }
  586. #else
  587. inline
  588. void SetCounterFunction(v8::CounterLookupCallback cb) {
  589. v8::V8::SetCounterFunction(cb);
  590. }
  591. inline
  592. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  593. v8::V8::SetCreateHistogramFunction(cb);
  594. }
  595. inline
  596. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  597. v8::V8::SetAddHistogramSampleFunction(cb);
  598. }
  599. inline bool IdleNotification(int idle_time_in_ms) {
  600. return v8::V8::IdleNotification(idle_time_in_ms);
  601. }
  602. inline void LowMemoryNotification() {
  603. v8::V8::LowMemoryNotification();
  604. }
  605. inline void ContextDisposedNotification() {
  606. v8::V8::ContextDisposedNotification();
  607. }
  608. #endif
  609. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12
  610. inline v8::Local<v8::Primitive> Undefined() {
  611. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  612. EscapableHandleScope scope;
  613. return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent())));
  614. # else
  615. return v8::Undefined(v8::Isolate::GetCurrent());
  616. # endif
  617. }
  618. inline v8::Local<v8::Primitive> Null() {
  619. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  620. EscapableHandleScope scope;
  621. return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent())));
  622. # else
  623. return v8::Null(v8::Isolate::GetCurrent());
  624. # endif
  625. }
  626. inline v8::Local<v8::Boolean> True() {
  627. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  628. EscapableHandleScope scope;
  629. return scope.Escape(New(v8::True(v8::Isolate::GetCurrent())));
  630. # else
  631. return v8::True(v8::Isolate::GetCurrent());
  632. # endif
  633. }
  634. inline v8::Local<v8::Boolean> False() {
  635. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  636. EscapableHandleScope scope;
  637. return scope.Escape(New(v8::False(v8::Isolate::GetCurrent())));
  638. # else
  639. return v8::False(v8::Isolate::GetCurrent());
  640. # endif
  641. }
  642. inline v8::Local<v8::String> EmptyString() {
  643. return v8::String::Empty(v8::Isolate::GetCurrent());
  644. }
  645. inline int AdjustExternalMemory(int bc) {
  646. return static_cast<int>(
  647. v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc));
  648. }
  649. inline void SetTemplate(
  650. v8::Local<v8::Template> templ
  651. , const char *name
  652. , v8::Local<v8::Data> value) {
  653. templ->Set(v8::Isolate::GetCurrent(), name, value);
  654. }
  655. inline void SetTemplate(
  656. v8::Local<v8::Template> templ
  657. , v8::Local<v8::String> name
  658. , v8::Local<v8::Data> value
  659. , v8::PropertyAttribute attributes) {
  660. templ->Set(name, value, attributes);
  661. }
  662. inline v8::Local<v8::Context> GetCurrentContext() {
  663. return v8::Isolate::GetCurrent()->GetCurrentContext();
  664. }
  665. inline void* GetInternalFieldPointer(
  666. v8::Local<v8::Object> object
  667. , int index) {
  668. return object->GetAlignedPointerFromInternalField(index);
  669. }
  670. inline void SetInternalFieldPointer(
  671. v8::Local<v8::Object> object
  672. , int index
  673. , void* value) {
  674. object->SetAlignedPointerInInternalField(index, value);
  675. }
  676. # define NAN_GC_CALLBACK(name) \
  677. void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags)
  678. #if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION
  679. typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback;
  680. typedef v8::Isolate::GCPrologueCallback GCPrologueCallback;
  681. #else
  682. typedef v8::Isolate::GCCallback GCEpilogueCallback;
  683. typedef v8::Isolate::GCCallback GCPrologueCallback;
  684. #endif
  685. inline void AddGCEpilogueCallback(
  686. GCEpilogueCallback callback
  687. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  688. v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter);
  689. }
  690. inline void RemoveGCEpilogueCallback(
  691. GCEpilogueCallback callback) {
  692. v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback);
  693. }
  694. inline void AddGCPrologueCallback(
  695. GCPrologueCallback callback
  696. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  697. v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter);
  698. }
  699. inline void RemoveGCPrologueCallback(
  700. GCPrologueCallback callback) {
  701. v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback);
  702. }
  703. inline void GetHeapStatistics(
  704. v8::HeapStatistics *heap_statistics) {
  705. v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics);
  706. }
  707. # define X(NAME) \
  708. inline v8::Local<v8::Value> NAME(const char *msg) { \
  709. EscapableHandleScope scope; \
  710. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  711. } \
  712. \
  713. inline \
  714. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  715. return v8::Exception::NAME(msg); \
  716. } \
  717. \
  718. inline void Throw ## NAME(const char *msg) { \
  719. HandleScope scope; \
  720. v8::Isolate::GetCurrent()->ThrowException( \
  721. v8::Exception::NAME(New(msg).ToLocalChecked())); \
  722. } \
  723. \
  724. inline void Throw ## NAME(v8::Local<v8::String> msg) { \
  725. HandleScope scope; \
  726. v8::Isolate::GetCurrent()->ThrowException( \
  727. v8::Exception::NAME(msg)); \
  728. }
  729. X(Error)
  730. X(RangeError)
  731. X(ReferenceError)
  732. X(SyntaxError)
  733. X(TypeError)
  734. # undef X
  735. inline void ThrowError(v8::Local<v8::Value> error) {
  736. v8::Isolate::GetCurrent()->ThrowException(error);
  737. }
  738. inline MaybeLocal<v8::Object> NewBuffer(
  739. char *data
  740. , size_t length
  741. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  742. , node::Buffer::FreeCallback callback
  743. #else
  744. , node::smalloc::FreeCallback callback
  745. #endif
  746. , void *hint
  747. ) {
  748. // arbitrary buffer lengths requires
  749. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  750. assert(length <= imp::kMaxLength && "too large buffer");
  751. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  752. return node::Buffer::New(
  753. v8::Isolate::GetCurrent(), data, length, callback, hint);
  754. #else
  755. return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback,
  756. hint);
  757. #endif
  758. }
  759. inline MaybeLocal<v8::Object> CopyBuffer(
  760. const char *data
  761. , uint32_t size
  762. ) {
  763. // arbitrary buffer lengths requires
  764. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  765. assert(size <= imp::kMaxLength && "too large buffer");
  766. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  767. return node::Buffer::Copy(
  768. v8::Isolate::GetCurrent(), data, size);
  769. #else
  770. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  771. #endif
  772. }
  773. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  774. // arbitrary buffer lengths requires
  775. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  776. assert(size <= imp::kMaxLength && "too large buffer");
  777. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  778. return node::Buffer::New(
  779. v8::Isolate::GetCurrent(), size);
  780. #else
  781. return node::Buffer::New(v8::Isolate::GetCurrent(), size);
  782. #endif
  783. }
  784. inline MaybeLocal<v8::Object> NewBuffer(
  785. char* data
  786. , uint32_t size
  787. ) {
  788. // arbitrary buffer lengths requires
  789. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  790. assert(size <= imp::kMaxLength && "too large buffer");
  791. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  792. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  793. #else
  794. return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
  795. #endif
  796. }
  797. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  798. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  799. inline MaybeLocal<v8::String>
  800. NewOneByteString(const uint8_t * value, int length = -1) {
  801. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  802. v8::NewStringType::kNormal, length);
  803. }
  804. inline MaybeLocal<BoundScript> CompileScript(
  805. v8::Local<v8::String> s
  806. , const v8::ScriptOrigin& origin
  807. ) {
  808. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  809. v8::EscapableHandleScope scope(isolate);
  810. v8::ScriptCompiler::Source source(s, origin);
  811. return scope.Escape(
  812. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  813. .FromMaybe(v8::Local<BoundScript>()));
  814. }
  815. inline MaybeLocal<BoundScript> CompileScript(
  816. v8::Local<v8::String> s
  817. ) {
  818. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  819. v8::EscapableHandleScope scope(isolate);
  820. v8::ScriptCompiler::Source source(s);
  821. return scope.Escape(
  822. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  823. .FromMaybe(v8::Local<BoundScript>()));
  824. }
  825. inline MaybeLocal<v8::Value> RunScript(
  826. v8::Local<UnboundScript> script
  827. ) {
  828. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  829. v8::EscapableHandleScope scope(isolate);
  830. return scope.Escape(script->BindToCurrentContext()
  831. ->Run(isolate->GetCurrentContext())
  832. .FromMaybe(v8::Local<v8::Value>()));
  833. }
  834. inline MaybeLocal<v8::Value> RunScript(
  835. v8::Local<BoundScript> script
  836. ) {
  837. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  838. v8::EscapableHandleScope scope(isolate);
  839. return scope.Escape(script->Run(isolate->GetCurrentContext())
  840. .FromMaybe(v8::Local<v8::Value>()));
  841. }
  842. #else
  843. inline MaybeLocal<v8::String>
  844. NewOneByteString(const uint8_t * value, int length = -1) {
  845. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  846. v8::String::kNormalString, length);
  847. }
  848. inline MaybeLocal<BoundScript> CompileScript(
  849. v8::Local<v8::String> s
  850. , const v8::ScriptOrigin& origin
  851. ) {
  852. v8::ScriptCompiler::Source source(s, origin);
  853. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  854. }
  855. inline MaybeLocal<BoundScript> CompileScript(
  856. v8::Local<v8::String> s
  857. ) {
  858. v8::ScriptCompiler::Source source(s);
  859. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  860. }
  861. inline MaybeLocal<v8::Value> RunScript(
  862. v8::Local<UnboundScript> script
  863. ) {
  864. EscapableHandleScope scope;
  865. return scope.Escape(script->BindToCurrentContext()->Run());
  866. }
  867. inline MaybeLocal<v8::Value> RunScript(
  868. v8::Local<BoundScript> script
  869. ) {
  870. return script->Run();
  871. }
  872. #endif
  873. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  874. v8::Local<v8::Object> target
  875. , v8::Local<v8::Function> func
  876. , int argc
  877. , v8::Local<v8::Value>* argv) {
  878. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  879. EscapableHandleScope scope;
  880. return scope.Escape(New(node::MakeCallback(
  881. v8::Isolate::GetCurrent(), target, func, argc, argv)));
  882. #else
  883. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  884. AsyncResource res("nan:makeCallback");
  885. return res.runInAsyncScope(target, func, argc, argv)
  886. .FromMaybe(v8::Local<v8::Value>());
  887. # else
  888. return node::MakeCallback(
  889. v8::Isolate::GetCurrent(), target, func, argc, argv);
  890. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  891. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  892. }
  893. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  894. v8::Local<v8::Object> target
  895. , v8::Local<v8::String> symbol
  896. , int argc
  897. , v8::Local<v8::Value>* argv) {
  898. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  899. EscapableHandleScope scope;
  900. return scope.Escape(New(node::MakeCallback(
  901. v8::Isolate::GetCurrent(), target, symbol, argc, argv)));
  902. #else
  903. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  904. AsyncResource res("nan:makeCallback");
  905. return res.runInAsyncScope(target, symbol, argc, argv)
  906. .FromMaybe(v8::Local<v8::Value>());
  907. # else
  908. return node::MakeCallback(
  909. v8::Isolate::GetCurrent(), target, symbol, argc, argv);
  910. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  911. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  912. }
  913. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  914. v8::Local<v8::Object> target
  915. , const char* method
  916. , int argc
  917. , v8::Local<v8::Value>* argv) {
  918. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  919. EscapableHandleScope scope;
  920. return scope.Escape(New(node::MakeCallback(
  921. v8::Isolate::GetCurrent(), target, method, argc, argv)));
  922. #else
  923. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  924. AsyncResource res("nan:makeCallback");
  925. return res.runInAsyncScope(target, method, argc, argv)
  926. .FromMaybe(v8::Local<v8::Value>());
  927. # else
  928. return node::MakeCallback(
  929. v8::Isolate::GetCurrent(), target, method, argc, argv);
  930. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  931. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  932. }
  933. inline void FatalException(const TryCatch& try_catch) {
  934. node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_);
  935. }
  936. inline v8::Local<v8::Value> ErrnoException(
  937. int errorno
  938. , const char* syscall = NULL
  939. , const char* message = NULL
  940. , const char* path = NULL) {
  941. return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall,
  942. message, path);
  943. }
  944. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  945. int errorno
  946. , const char* syscall = NULL
  947. , const char* message = NULL
  948. , const char* path = NULL) {
  949. return ErrnoException(errorno, syscall, message, path);
  950. }
  951. template<typename T>
  952. inline void SetIsolateData(
  953. v8::Isolate *isolate
  954. , T *data
  955. ) {
  956. isolate->SetData(0, data);
  957. }
  958. template<typename T>
  959. inline T *GetIsolateData(
  960. v8::Isolate *isolate
  961. ) {
  962. return static_cast<T*>(isolate->GetData(0));
  963. }
  964. class Utf8String {
  965. public:
  966. inline explicit Utf8String(v8::Local<v8::Value> from) :
  967. length_(0), str_(str_st_) {
  968. HandleScope scope;
  969. if (!from.IsEmpty()) {
  970. #if NODE_MAJOR_VERSION >= 10
  971. v8::Local<v8::Context> context = GetCurrentContext();
  972. v8::Local<v8::String> string =
  973. from->ToString(context).FromMaybe(v8::Local<v8::String>());
  974. #else
  975. v8::Local<v8::String> string = from->ToString();
  976. #endif
  977. if (!string.IsEmpty()) {
  978. size_t len = 3 * string->Length() + 1;
  979. assert(len <= INT_MAX);
  980. if (len > sizeof (str_st_)) {
  981. str_ = static_cast<char*>(malloc(len));
  982. assert(str_ != 0);
  983. }
  984. const int flags =
  985. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  986. #if NODE_MAJOR_VERSION >= 11
  987. length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_,
  988. static_cast<int>(len), 0, flags);
  989. #else
  990. // See https://github.com/nodejs/nan/issues/832.
  991. // Disable the warning as there is no way around it.
  992. #ifdef _MSC_VER
  993. #pragma warning(push)
  994. #pragma warning(disable : 4996)
  995. #endif
  996. #ifdef __GNUC__
  997. #pragma GCC diagnostic push
  998. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  999. #endif
  1000. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  1001. #ifdef __GNUC__
  1002. #pragma GCC diagnostic pop
  1003. #endif
  1004. #ifdef _MSC_VER
  1005. #pragma warning(pop)
  1006. #endif
  1007. #endif // NODE_MAJOR_VERSION < 11
  1008. str_[length_] = '\0';
  1009. }
  1010. }
  1011. }
  1012. inline int length() const {
  1013. return length_;
  1014. }
  1015. inline char* operator*() { return str_; }
  1016. inline const char* operator*() const { return str_; }
  1017. inline ~Utf8String() {
  1018. if (str_ != str_st_) {
  1019. free(str_);
  1020. }
  1021. }
  1022. private:
  1023. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1024. int length_;
  1025. char *str_;
  1026. char str_st_[1024];
  1027. };
  1028. #else // Node 0.8 and 0.10
  1029. inline v8::Local<v8::Primitive> Undefined() {
  1030. EscapableHandleScope scope;
  1031. return scope.Escape(New(v8::Undefined()));
  1032. }
  1033. inline v8::Local<v8::Primitive> Null() {
  1034. EscapableHandleScope scope;
  1035. return scope.Escape(New(v8::Null()));
  1036. }
  1037. inline v8::Local<v8::Boolean> True() {
  1038. EscapableHandleScope scope;
  1039. return scope.Escape(New(v8::True()));
  1040. }
  1041. inline v8::Local<v8::Boolean> False() {
  1042. EscapableHandleScope scope;
  1043. return scope.Escape(New(v8::False()));
  1044. }
  1045. inline v8::Local<v8::String> EmptyString() {
  1046. return v8::String::Empty();
  1047. }
  1048. inline int AdjustExternalMemory(int bc) {
  1049. return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc));
  1050. }
  1051. inline void SetTemplate(
  1052. v8::Local<v8::Template> templ
  1053. , const char *name
  1054. , v8::Local<v8::Data> value) {
  1055. templ->Set(name, value);
  1056. }
  1057. inline void SetTemplate(
  1058. v8::Local<v8::Template> templ
  1059. , v8::Local<v8::String> name
  1060. , v8::Local<v8::Data> value
  1061. , v8::PropertyAttribute attributes) {
  1062. templ->Set(name, value, attributes);
  1063. }
  1064. inline v8::Local<v8::Context> GetCurrentContext() {
  1065. return v8::Context::GetCurrent();
  1066. }
  1067. inline void* GetInternalFieldPointer(
  1068. v8::Local<v8::Object> object
  1069. , int index) {
  1070. return object->GetPointerFromInternalField(index);
  1071. }
  1072. inline void SetInternalFieldPointer(
  1073. v8::Local<v8::Object> object
  1074. , int index
  1075. , void* value) {
  1076. object->SetPointerInInternalField(index, value);
  1077. }
  1078. # define NAN_GC_CALLBACK(name) \
  1079. void name(v8::GCType type, v8::GCCallbackFlags flags)
  1080. inline void AddGCEpilogueCallback(
  1081. v8::GCEpilogueCallback callback
  1082. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1083. v8::V8::AddGCEpilogueCallback(callback, gc_type_filter);
  1084. }
  1085. inline void RemoveGCEpilogueCallback(
  1086. v8::GCEpilogueCallback callback) {
  1087. v8::V8::RemoveGCEpilogueCallback(callback);
  1088. }
  1089. inline void AddGCPrologueCallback(
  1090. v8::GCPrologueCallback callback
  1091. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1092. v8::V8::AddGCPrologueCallback(callback, gc_type_filter);
  1093. }
  1094. inline void RemoveGCPrologueCallback(
  1095. v8::GCPrologueCallback callback) {
  1096. v8::V8::RemoveGCPrologueCallback(callback);
  1097. }
  1098. inline void GetHeapStatistics(
  1099. v8::HeapStatistics *heap_statistics) {
  1100. v8::V8::GetHeapStatistics(heap_statistics);
  1101. }
  1102. # define X(NAME) \
  1103. inline v8::Local<v8::Value> NAME(const char *msg) { \
  1104. EscapableHandleScope scope; \
  1105. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1106. } \
  1107. \
  1108. inline \
  1109. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  1110. return v8::Exception::NAME(msg); \
  1111. } \
  1112. \
  1113. inline void Throw ## NAME(const char *msg) { \
  1114. HandleScope scope; \
  1115. v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1116. } \
  1117. \
  1118. inline \
  1119. void Throw ## NAME(v8::Local<v8::String> errmsg) { \
  1120. HandleScope scope; \
  1121. v8::ThrowException(v8::Exception::NAME(errmsg)); \
  1122. }
  1123. X(Error)
  1124. X(RangeError)
  1125. X(ReferenceError)
  1126. X(SyntaxError)
  1127. X(TypeError)
  1128. # undef X
  1129. inline void ThrowError(v8::Local<v8::Value> error) {
  1130. v8::ThrowException(error);
  1131. }
  1132. inline MaybeLocal<v8::Object> NewBuffer(
  1133. char *data
  1134. , size_t length
  1135. , node::Buffer::free_callback callback
  1136. , void *hint
  1137. ) {
  1138. EscapableHandleScope scope;
  1139. // arbitrary buffer lengths requires
  1140. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1141. assert(length <= imp::kMaxLength && "too large buffer");
  1142. return scope.Escape(
  1143. New(node::Buffer::New(data, length, callback, hint)->handle_));
  1144. }
  1145. inline MaybeLocal<v8::Object> CopyBuffer(
  1146. const char *data
  1147. , uint32_t size
  1148. ) {
  1149. EscapableHandleScope scope;
  1150. // arbitrary buffer lengths requires
  1151. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1152. assert(size <= imp::kMaxLength && "too large buffer");
  1153. #if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  1154. return scope.Escape(New(node::Buffer::New(data, size)->handle_));
  1155. #else
  1156. return scope.Escape(
  1157. New(node::Buffer::New(const_cast<char *>(data), size)->handle_));
  1158. #endif
  1159. }
  1160. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  1161. // arbitrary buffer lengths requires
  1162. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1163. EscapableHandleScope scope;
  1164. assert(size <= imp::kMaxLength && "too large buffer");
  1165. return scope.Escape(New(node::Buffer::New(size)->handle_));
  1166. }
  1167. inline void FreeData(char *data, void *hint) {
  1168. (void) hint; // unused
  1169. delete[] data;
  1170. }
  1171. inline MaybeLocal<v8::Object> NewBuffer(
  1172. char* data
  1173. , uint32_t size
  1174. ) {
  1175. EscapableHandleScope scope;
  1176. // arbitrary buffer lengths requires
  1177. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1178. assert(size <= imp::kMaxLength && "too large buffer");
  1179. return scope.Escape(
  1180. New(node::Buffer::New(data, size, FreeData, NULL)->handle_));
  1181. }
  1182. namespace imp {
  1183. inline void
  1184. widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) {
  1185. size_t len = static_cast<size_t>(l);
  1186. if (l < 0) {
  1187. len = strlen(reinterpret_cast<const char*>(s));
  1188. }
  1189. assert(len <= INT_MAX && "string too long");
  1190. ws->resize(len);
  1191. std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use)
  1192. }
  1193. } // end of namespace imp
  1194. inline MaybeLocal<v8::String>
  1195. NewOneByteString(const uint8_t * value, int length = -1) {
  1196. std::vector<uint16_t> wideString; // NOLINT(build/include_what_you_use)
  1197. imp::widenString(&wideString, value, length);
  1198. return v8::String::New(wideString.data(),
  1199. static_cast<int>(wideString.size()));
  1200. }
  1201. inline MaybeLocal<BoundScript> CompileScript(
  1202. v8::Local<v8::String> s
  1203. , const v8::ScriptOrigin& origin
  1204. ) {
  1205. return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin));
  1206. }
  1207. inline MaybeLocal<BoundScript> CompileScript(
  1208. v8::Local<v8::String> s
  1209. ) {
  1210. return v8::Script::Compile(s);
  1211. }
  1212. inline
  1213. MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) {
  1214. return script->Run();
  1215. }
  1216. inline v8::Local<v8::Value> MakeCallback(
  1217. v8::Local<v8::Object> target
  1218. , v8::Local<v8::Function> func
  1219. , int argc
  1220. , v8::Local<v8::Value>* argv) {
  1221. v8::HandleScope scope;
  1222. return scope.Close(New(node::MakeCallback(target, func, argc, argv)));
  1223. }
  1224. inline v8::Local<v8::Value> MakeCallback(
  1225. v8::Local<v8::Object> target
  1226. , v8::Local<v8::String> symbol
  1227. , int argc
  1228. , v8::Local<v8::Value>* argv) {
  1229. v8::HandleScope scope;
  1230. return scope.Close(New(node::MakeCallback(target, symbol, argc, argv)));
  1231. }
  1232. inline v8::Local<v8::Value> MakeCallback(
  1233. v8::Local<v8::Object> target
  1234. , const char* method
  1235. , int argc
  1236. , v8::Local<v8::Value>* argv) {
  1237. v8::HandleScope scope;
  1238. return scope.Close(New(node::MakeCallback(target, method, argc, argv)));
  1239. }
  1240. inline void FatalException(const TryCatch& try_catch) {
  1241. node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_));
  1242. }
  1243. inline v8::Local<v8::Value> ErrnoException(
  1244. int errorno
  1245. , const char* syscall = NULL
  1246. , const char* message = NULL
  1247. , const char* path = NULL) {
  1248. return node::ErrnoException(errorno, syscall, message, path);
  1249. }
  1250. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  1251. int errorno
  1252. , const char* syscall = NULL
  1253. , const char* message = NULL
  1254. , const char* path = NULL) {
  1255. return ErrnoException(errorno, syscall, message, path);
  1256. }
  1257. template<typename T>
  1258. inline void SetIsolateData(
  1259. v8::Isolate *isolate
  1260. , T *data
  1261. ) {
  1262. isolate->SetData(data);
  1263. }
  1264. template<typename T>
  1265. inline T *GetIsolateData(
  1266. v8::Isolate *isolate
  1267. ) {
  1268. return static_cast<T*>(isolate->GetData());
  1269. }
  1270. class Utf8String {
  1271. public:
  1272. inline explicit Utf8String(v8::Local<v8::Value> from) :
  1273. length_(0), str_(str_st_) {
  1274. v8::HandleScope scope;
  1275. if (!from.IsEmpty()) {
  1276. v8::Local<v8::String> string = from->ToString();
  1277. if (!string.IsEmpty()) {
  1278. size_t len = 3 * string->Length() + 1;
  1279. assert(len <= INT_MAX);
  1280. if (len > sizeof (str_st_)) {
  1281. str_ = static_cast<char*>(malloc(len));
  1282. assert(str_ != 0);
  1283. }
  1284. const int flags =
  1285. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  1286. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  1287. str_[length_] = '\0';
  1288. }
  1289. }
  1290. }
  1291. inline int length() const {
  1292. return length_;
  1293. }
  1294. inline char* operator*() { return str_; }
  1295. inline const char* operator*() const { return str_; }
  1296. inline ~Utf8String() {
  1297. if (str_ != str_st_) {
  1298. free(str_);
  1299. }
  1300. }
  1301. private:
  1302. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1303. int length_;
  1304. char *str_;
  1305. char str_st_[1024];
  1306. };
  1307. #endif // NODE_MODULE_VERSION
  1308. typedef void (*FreeCallback)(char *data, void *hint);
  1309. typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE;
  1310. typedef void NAN_METHOD_RETURN_TYPE;
  1311. typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE;
  1312. typedef void NAN_GETTER_RETURN_TYPE;
  1313. typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE;
  1314. typedef void NAN_SETTER_RETURN_TYPE;
  1315. typedef const PropertyCallbackInfo<v8::Value>&
  1316. NAN_PROPERTY_GETTER_ARGS_TYPE;
  1317. typedef void NAN_PROPERTY_GETTER_RETURN_TYPE;
  1318. typedef const PropertyCallbackInfo<v8::Value>&
  1319. NAN_PROPERTY_SETTER_ARGS_TYPE;
  1320. typedef void NAN_PROPERTY_SETTER_RETURN_TYPE;
  1321. typedef const PropertyCallbackInfo<v8::Array>&
  1322. NAN_PROPERTY_ENUMERATOR_ARGS_TYPE;
  1323. typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE;
  1324. typedef const PropertyCallbackInfo<v8::Boolean>&
  1325. NAN_PROPERTY_DELETER_ARGS_TYPE;
  1326. typedef void NAN_PROPERTY_DELETER_RETURN_TYPE;
  1327. typedef const PropertyCallbackInfo<v8::Integer>&
  1328. NAN_PROPERTY_QUERY_ARGS_TYPE;
  1329. typedef void NAN_PROPERTY_QUERY_RETURN_TYPE;
  1330. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE;
  1331. typedef void NAN_INDEX_GETTER_RETURN_TYPE;
  1332. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE;
  1333. typedef void NAN_INDEX_SETTER_RETURN_TYPE;
  1334. typedef const PropertyCallbackInfo<v8::Array>&
  1335. NAN_INDEX_ENUMERATOR_ARGS_TYPE;
  1336. typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE;
  1337. typedef const PropertyCallbackInfo<v8::Boolean>&
  1338. NAN_INDEX_DELETER_ARGS_TYPE;
  1339. typedef void NAN_INDEX_DELETER_RETURN_TYPE;
  1340. typedef const PropertyCallbackInfo<v8::Integer>&
  1341. NAN_INDEX_QUERY_ARGS_TYPE;
  1342. typedef void NAN_INDEX_QUERY_RETURN_TYPE;
  1343. #define NAN_METHOD(name) \
  1344. Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info)
  1345. #define NAN_GETTER(name) \
  1346. Nan::NAN_GETTER_RETURN_TYPE name( \
  1347. v8::Local<v8::String> property \
  1348. , Nan::NAN_GETTER_ARGS_TYPE info)
  1349. #define NAN_SETTER(name) \
  1350. Nan::NAN_SETTER_RETURN_TYPE name( \
  1351. v8::Local<v8::String> property \
  1352. , v8::Local<v8::Value> value \
  1353. , Nan::NAN_SETTER_ARGS_TYPE info)
  1354. #define NAN_PROPERTY_GETTER(name) \
  1355. Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \
  1356. v8::Local<v8::String> property \
  1357. , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info)
  1358. #define NAN_PROPERTY_SETTER(name) \
  1359. Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \
  1360. v8::Local<v8::String> property \
  1361. , v8::Local<v8::Value> value \
  1362. , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info)
  1363. #define NAN_PROPERTY_ENUMERATOR(name) \
  1364. Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \
  1365. Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info)
  1366. #define NAN_PROPERTY_DELETER(name) \
  1367. Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \
  1368. v8::Local<v8::String> property \
  1369. , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info)
  1370. #define NAN_PROPERTY_QUERY(name) \
  1371. Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \
  1372. v8::Local<v8::String> property \
  1373. , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info)
  1374. # define NAN_INDEX_GETTER(name) \
  1375. Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \
  1376. uint32_t index \
  1377. , Nan::NAN_INDEX_GETTER_ARGS_TYPE info)
  1378. #define NAN_INDEX_SETTER(name) \
  1379. Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \
  1380. uint32_t index \
  1381. , v8::Local<v8::Value> value \
  1382. , Nan::NAN_INDEX_SETTER_ARGS_TYPE info)
  1383. #define NAN_INDEX_ENUMERATOR(name) \
  1384. Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \
  1385. name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info)
  1386. #define NAN_INDEX_DELETER(name) \
  1387. Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \
  1388. uint32_t index \
  1389. , Nan::NAN_INDEX_DELETER_ARGS_TYPE info)
  1390. #define NAN_INDEX_QUERY(name) \
  1391. Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \
  1392. uint32_t index \
  1393. , Nan::NAN_INDEX_QUERY_ARGS_TYPE info)
  1394. class Callback {
  1395. public:
  1396. Callback() {}
  1397. explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {}
  1398. ~Callback() {
  1399. handle_.Reset();
  1400. }
  1401. bool operator==(const Callback &other) const {
  1402. return handle_ == other.handle_;
  1403. }
  1404. bool operator!=(const Callback &other) const {
  1405. return !operator==(other);
  1406. }
  1407. inline
  1408. v8::Local<v8::Function> operator*() const { return GetFunction(); }
  1409. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1410. v8::Local<v8::Object> target
  1411. , int argc = 0
  1412. , v8::Local<v8::Value> argv[] = 0) const {
  1413. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1414. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1415. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1416. AsyncResource async("nan:Callback:operator()");
  1417. return Call_(isolate, target, argc, argv, &async)
  1418. .FromMaybe(v8::Local<v8::Value>());
  1419. # else
  1420. return Call_(isolate, target, argc, argv);
  1421. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1422. #else
  1423. return Call_(target, argc, argv);
  1424. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1425. }
  1426. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1427. int argc = 0
  1428. , v8::Local<v8::Value> argv[] = 0) const {
  1429. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1430. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1431. v8::EscapableHandleScope scope(isolate);
  1432. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1433. AsyncResource async("nan:Callback:operator()");
  1434. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1435. argc, argv, &async)
  1436. .FromMaybe(v8::Local<v8::Value>()));
  1437. # else
  1438. return scope.Escape(
  1439. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1440. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1441. #else
  1442. v8::HandleScope scope;
  1443. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1444. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1445. }
  1446. inline MaybeLocal<v8::Value> operator()(
  1447. AsyncResource* resource
  1448. , int argc = 0
  1449. , v8::Local<v8::Value> argv[] = 0) const {
  1450. return this->Call(argc, argv, resource);
  1451. }
  1452. inline MaybeLocal<v8::Value> operator()(
  1453. AsyncResource* resource
  1454. , v8::Local<v8::Object> target
  1455. , int argc = 0
  1456. , v8::Local<v8::Value> argv[] = 0) const {
  1457. return this->Call(target, argc, argv, resource);
  1458. }
  1459. // TODO(kkoopa): remove
  1460. inline void SetFunction(const v8::Local<v8::Function> &fn) {
  1461. Reset(fn);
  1462. }
  1463. inline void Reset(const v8::Local<v8::Function> &fn) {
  1464. handle_.Reset(fn);
  1465. }
  1466. inline void Reset() {
  1467. handle_.Reset();
  1468. }
  1469. inline v8::Local<v8::Function> GetFunction() const {
  1470. return New(handle_);
  1471. }
  1472. inline bool IsEmpty() const {
  1473. return handle_.IsEmpty();
  1474. }
  1475. // Deprecated: For async callbacks Use the versions that accept an
  1476. // AsyncResource. If this callback does not correspond to an async resource,
  1477. // that is, it is a synchronous function call on a non-empty JS stack, you
  1478. // should Nan::Call instead.
  1479. NAN_DEPRECATED inline v8::Local<v8::Value>
  1480. Call(v8::Local<v8::Object> target
  1481. , int argc
  1482. , v8::Local<v8::Value> argv[]) const {
  1483. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1484. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1485. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1486. AsyncResource async("nan:Callback:Call");
  1487. return Call_(isolate, target, argc, argv, &async)
  1488. .FromMaybe(v8::Local<v8::Value>());
  1489. # else
  1490. return Call_(isolate, target, argc, argv);
  1491. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1492. #else
  1493. return Call_(target, argc, argv);
  1494. #endif
  1495. }
  1496. // Deprecated: For async callbacks Use the versions that accept an
  1497. // AsyncResource. If this callback does not correspond to an async resource,
  1498. // that is, it is a synchronous function call on a non-empty JS stack, you
  1499. // should Nan::Call instead.
  1500. NAN_DEPRECATED inline v8::Local<v8::Value>
  1501. Call(int argc, v8::Local<v8::Value> argv[]) const {
  1502. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1503. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1504. v8::EscapableHandleScope scope(isolate);
  1505. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1506. AsyncResource async("nan:Callback:Call");
  1507. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1508. argc, argv, &async)
  1509. .FromMaybe(v8::Local<v8::Value>()));
  1510. # else
  1511. return scope.Escape(
  1512. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1513. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1514. #else
  1515. v8::HandleScope scope;
  1516. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1517. #endif
  1518. }
  1519. inline MaybeLocal<v8::Value>
  1520. Call(v8::Local<v8::Object> target
  1521. , int argc
  1522. , v8::Local<v8::Value> argv[]
  1523. , AsyncResource* resource) const {
  1524. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1525. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1526. return Call_(isolate, target, argc, argv, resource);
  1527. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1528. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1529. return Call_(isolate, target, argc, argv);
  1530. #else
  1531. return Call_(target, argc, argv);
  1532. #endif
  1533. }
  1534. inline MaybeLocal<v8::Value>
  1535. Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const {
  1536. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1537. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1538. return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource);
  1539. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1540. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1541. v8::EscapableHandleScope scope(isolate);
  1542. return scope.Escape(
  1543. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1544. #else
  1545. v8::HandleScope scope;
  1546. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1547. #endif
  1548. }
  1549. private:
  1550. NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback)
  1551. Persistent<v8::Function> handle_;
  1552. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1553. MaybeLocal<v8::Value> Call_(v8::Isolate *isolate
  1554. , v8::Local<v8::Object> target
  1555. , int argc
  1556. , v8::Local<v8::Value> argv[]
  1557. , AsyncResource* resource) const {
  1558. EscapableHandleScope scope;
  1559. v8::Local<v8::Function> func = New(handle_);
  1560. auto maybe = resource->runInAsyncScope(target, func, argc, argv);
  1561. v8::Local<v8::Value> local;
  1562. if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>();
  1563. return scope.Escape(local);
  1564. }
  1565. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1566. v8::Local<v8::Value> Call_(v8::Isolate *isolate
  1567. , v8::Local<v8::Object> target
  1568. , int argc
  1569. , v8::Local<v8::Value> argv[]) const {
  1570. EscapableHandleScope scope;
  1571. v8::Local<v8::Function> callback = New(handle_);
  1572. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  1573. return scope.Escape(New(node::MakeCallback(
  1574. isolate
  1575. , target
  1576. , callback
  1577. , argc
  1578. , argv
  1579. )));
  1580. # else
  1581. return scope.Escape(node::MakeCallback(
  1582. isolate
  1583. , target
  1584. , callback
  1585. , argc
  1586. , argv
  1587. ));
  1588. # endif
  1589. }
  1590. #else
  1591. v8::Local<v8::Value> Call_(v8::Local<v8::Object> target
  1592. , int argc
  1593. , v8::Local<v8::Value> argv[]) const {
  1594. EscapableHandleScope scope;
  1595. v8::Local<v8::Function> callback = New(handle_);
  1596. return scope.Escape(New(node::MakeCallback(
  1597. target
  1598. , callback
  1599. , argc
  1600. , argv
  1601. )));
  1602. }
  1603. #endif
  1604. };
  1605. inline MaybeLocal<v8::Value> Call(
  1606. const Nan::Callback& callback
  1607. , v8::Local<v8::Object> recv
  1608. , int argc
  1609. , v8::Local<v8::Value> argv[]) {
  1610. return Call(*callback, recv, argc, argv);
  1611. }
  1612. inline MaybeLocal<v8::Value> Call(
  1613. const Nan::Callback& callback
  1614. , int argc
  1615. , v8::Local<v8::Value> argv[]) {
  1616. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1617. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1618. v8::EscapableHandleScope scope(isolate);
  1619. return scope.Escape(
  1620. Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv)
  1621. .FromMaybe(v8::Local<v8::Value>()));
  1622. #else
  1623. EscapableHandleScope scope;
  1624. return scope.Escape(
  1625. Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv)
  1626. .FromMaybe(v8::Local<v8::Value>()));
  1627. #endif
  1628. }
  1629. inline MaybeLocal<v8::Value> Call(
  1630. v8::Local<v8::String> symbol
  1631. , v8::Local<v8::Object> recv
  1632. , int argc
  1633. , v8::Local<v8::Value> argv[]) {
  1634. EscapableHandleScope scope;
  1635. v8::Local<v8::Value> fn_v =
  1636. Get(recv, symbol).FromMaybe(v8::Local<v8::Value>());
  1637. if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>();
  1638. v8::Local<v8::Function> fn = fn_v.As<v8::Function>();
  1639. return scope.Escape(
  1640. Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1641. }
  1642. inline MaybeLocal<v8::Value> Call(
  1643. const char* method
  1644. , v8::Local<v8::Object> recv
  1645. , int argc
  1646. , v8::Local<v8::Value> argv[]) {
  1647. EscapableHandleScope scope;
  1648. v8::Local<v8::String> method_string =
  1649. New<v8::String>(method).ToLocalChecked();
  1650. return scope.Escape(
  1651. Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1652. }
  1653. /* abstract */ class AsyncWorker {
  1654. public:
  1655. explicit AsyncWorker(Callback *callback_,
  1656. const char* resource_name = "nan:AsyncWorker")
  1657. : callback(callback_), errmsg_(NULL) {
  1658. request.data = this;
  1659. HandleScope scope;
  1660. v8::Local<v8::Object> obj = New<v8::Object>();
  1661. persistentHandle.Reset(obj);
  1662. async_resource = new AsyncResource(resource_name, obj);
  1663. }
  1664. virtual ~AsyncWorker() {
  1665. HandleScope scope;
  1666. if (!persistentHandle.IsEmpty())
  1667. persistentHandle.Reset();
  1668. delete callback;
  1669. delete[] errmsg_;
  1670. delete async_resource;
  1671. }
  1672. virtual void WorkComplete() {
  1673. HandleScope scope;
  1674. if (errmsg_ == NULL)
  1675. HandleOKCallback();
  1676. else
  1677. HandleErrorCallback();
  1678. delete callback;
  1679. callback = NULL;
  1680. }
  1681. inline void SaveToPersistent(
  1682. const char *key, const v8::Local<v8::Value> &value) {
  1683. HandleScope scope;
  1684. Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust();
  1685. }
  1686. inline void SaveToPersistent(
  1687. const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) {
  1688. HandleScope scope;
  1689. Set(New(persistentHandle), key, value).FromJust();
  1690. }
  1691. inline void SaveToPersistent(
  1692. uint32_t index, const v8::Local<v8::Value> &value) {
  1693. HandleScope scope;
  1694. Set(New(persistentHandle), index, value).FromJust();
  1695. }
  1696. inline v8::Local<v8::Value> GetFromPersistent(const char *key) const {
  1697. EscapableHandleScope scope;
  1698. return scope.Escape(
  1699. Get(New(persistentHandle), New(key).ToLocalChecked())
  1700. .FromMaybe(v8::Local<v8::Value>()));
  1701. }
  1702. inline v8::Local<v8::Value>
  1703. GetFromPersistent(const v8::Local<v8::String> &key) const {
  1704. EscapableHandleScope scope;
  1705. return scope.Escape(
  1706. Get(New(persistentHandle), key)
  1707. .FromMaybe(v8::Local<v8::Value>()));
  1708. }
  1709. inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const {
  1710. EscapableHandleScope scope;
  1711. return scope.Escape(
  1712. Get(New(persistentHandle), index)
  1713. .FromMaybe(v8::Local<v8::Value>()));
  1714. }
  1715. virtual void Execute() = 0;
  1716. uv_work_t request;
  1717. virtual void Destroy() {
  1718. delete this;
  1719. }
  1720. protected:
  1721. Persistent<v8::Object> persistentHandle;
  1722. Callback *callback;
  1723. AsyncResource *async_resource;
  1724. virtual void HandleOKCallback() {
  1725. HandleScope scope;
  1726. callback->Call(0, NULL, async_resource);
  1727. }
  1728. virtual void HandleErrorCallback() {
  1729. HandleScope scope;
  1730. v8::Local<v8::Value> argv[] = {
  1731. v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked())
  1732. };
  1733. callback->Call(1, argv, async_resource);
  1734. }
  1735. void SetErrorMessage(const char *msg) {
  1736. delete[] errmsg_;
  1737. size_t size = strlen(msg) + 1;
  1738. errmsg_ = new char[size];
  1739. memcpy(errmsg_, msg, size);
  1740. }
  1741. const char* ErrorMessage() const {
  1742. return errmsg_;
  1743. }
  1744. private:
  1745. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker)
  1746. char *errmsg_;
  1747. };
  1748. /* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker {
  1749. public:
  1750. explicit AsyncBareProgressWorkerBase(
  1751. Callback *callback_,
  1752. const char* resource_name = "nan:AsyncBareProgressWorkerBase")
  1753. : AsyncWorker(callback_, resource_name) {
  1754. uv_async_init(
  1755. GetCurrentEventLoop()
  1756. , &async
  1757. , AsyncProgress_
  1758. );
  1759. async.data = this;
  1760. }
  1761. virtual ~AsyncBareProgressWorkerBase() {
  1762. }
  1763. virtual void WorkProgress() = 0;
  1764. virtual void Destroy() {
  1765. uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_);
  1766. }
  1767. private:
  1768. inline static NAUV_WORK_CB(AsyncProgress_) {
  1769. AsyncBareProgressWorkerBase *worker =
  1770. static_cast<AsyncBareProgressWorkerBase*>(async->data);
  1771. worker->WorkProgress();
  1772. }
  1773. inline static void AsyncClose_(uv_handle_t* handle) {
  1774. AsyncBareProgressWorkerBase *worker =
  1775. static_cast<AsyncBareProgressWorkerBase*>(handle->data);
  1776. delete worker;
  1777. }
  1778. protected:
  1779. uv_async_t async;
  1780. };
  1781. template<class T>
  1782. /* abstract */
  1783. class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase {
  1784. public:
  1785. explicit AsyncBareProgressWorker(
  1786. Callback *callback_,
  1787. const char* resource_name = "nan:AsyncBareProgressWorker")
  1788. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1789. uv_mutex_init(&async_lock);
  1790. }
  1791. virtual ~AsyncBareProgressWorker() {
  1792. uv_mutex_destroy(&async_lock);
  1793. }
  1794. class ExecutionProgress {
  1795. friend class AsyncBareProgressWorker;
  1796. public:
  1797. void Signal() const {
  1798. uv_mutex_lock(&that_->async_lock);
  1799. uv_async_send(&that_->async);
  1800. uv_mutex_unlock(&that_->async_lock);
  1801. }
  1802. void Send(const T* data, size_t count) const {
  1803. that_->SendProgress_(data, count);
  1804. }
  1805. private:
  1806. explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {}
  1807. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1808. AsyncBareProgressWorker* const that_;
  1809. };
  1810. virtual void Execute(const ExecutionProgress& progress) = 0;
  1811. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1812. protected:
  1813. uv_mutex_t async_lock;
  1814. private:
  1815. void Execute() /*final override*/ {
  1816. ExecutionProgress progress(this);
  1817. Execute(progress);
  1818. }
  1819. virtual void SendProgress_(const T *data, size_t count) = 0;
  1820. };
  1821. template<class T>
  1822. /* abstract */
  1823. class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> {
  1824. public:
  1825. explicit AsyncProgressWorkerBase(
  1826. Callback *callback_,
  1827. const char* resource_name = "nan:AsyncProgressWorkerBase")
  1828. : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL),
  1829. asyncsize_(0) {
  1830. }
  1831. virtual ~AsyncProgressWorkerBase() {
  1832. delete[] asyncdata_;
  1833. }
  1834. void WorkProgress() {
  1835. uv_mutex_lock(&this->async_lock);
  1836. T *data = asyncdata_;
  1837. size_t size = asyncsize_;
  1838. asyncdata_ = NULL;
  1839. asyncsize_ = 0;
  1840. uv_mutex_unlock(&this->async_lock);
  1841. // Don't send progress events after we've already completed.
  1842. if (this->callback) {
  1843. this->HandleProgressCallback(data, size);
  1844. }
  1845. delete[] data;
  1846. }
  1847. private:
  1848. void SendProgress_(const T *data, size_t count) {
  1849. T *new_data = new T[count];
  1850. std::copy(data, data + count, new_data);
  1851. uv_mutex_lock(&this->async_lock);
  1852. T *old_data = asyncdata_;
  1853. asyncdata_ = new_data;
  1854. asyncsize_ = count;
  1855. uv_async_send(&this->async);
  1856. uv_mutex_unlock(&this->async_lock);
  1857. delete[] old_data;
  1858. }
  1859. T *asyncdata_;
  1860. size_t asyncsize_;
  1861. };
  1862. // This ensures compatibility to the previous un-templated AsyncProgressWorker
  1863. // class definition.
  1864. typedef AsyncProgressWorkerBase<char> AsyncProgressWorker;
  1865. template<class T>
  1866. /* abstract */
  1867. class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase {
  1868. public:
  1869. explicit AsyncBareProgressQueueWorker(
  1870. Callback *callback_,
  1871. const char* resource_name = "nan:AsyncBareProgressQueueWorker")
  1872. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1873. }
  1874. virtual ~AsyncBareProgressQueueWorker() {
  1875. }
  1876. class ExecutionProgress {
  1877. friend class AsyncBareProgressQueueWorker;
  1878. public:
  1879. void Send(const T* data, size_t count) const {
  1880. that_->SendProgress_(data, count);
  1881. }
  1882. private:
  1883. explicit ExecutionProgress(AsyncBareProgressQueueWorker *that)
  1884. : that_(that) {}
  1885. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1886. AsyncBareProgressQueueWorker* const that_;
  1887. };
  1888. virtual void Execute(const ExecutionProgress& progress) = 0;
  1889. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1890. private:
  1891. void Execute() /*final override*/ {
  1892. ExecutionProgress progress(this);
  1893. Execute(progress);
  1894. }
  1895. virtual void SendProgress_(const T *data, size_t count) = 0;
  1896. };
  1897. template<class T>
  1898. /* abstract */
  1899. class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> {
  1900. public:
  1901. explicit AsyncProgressQueueWorker(
  1902. Callback *callback_,
  1903. const char* resource_name = "nan:AsyncProgressQueueWorker")
  1904. : AsyncBareProgressQueueWorker<T>(callback_) {
  1905. uv_mutex_init(&async_lock);
  1906. }
  1907. virtual ~AsyncProgressQueueWorker() {
  1908. uv_mutex_lock(&async_lock);
  1909. while (!asyncdata_.empty()) {
  1910. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1911. T *data = datapair.first;
  1912. asyncdata_.pop();
  1913. delete[] data;
  1914. }
  1915. uv_mutex_unlock(&async_lock);
  1916. uv_mutex_destroy(&async_lock);
  1917. }
  1918. void WorkComplete() {
  1919. WorkProgress();
  1920. AsyncWorker::WorkComplete();
  1921. }
  1922. void WorkProgress() {
  1923. uv_mutex_lock(&async_lock);
  1924. while (!asyncdata_.empty()) {
  1925. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1926. T *data = datapair.first;
  1927. size_t size = datapair.second;
  1928. asyncdata_.pop();
  1929. uv_mutex_unlock(&async_lock);
  1930. // Don't send progress events after we've already completed.
  1931. if (this->callback) {
  1932. this->HandleProgressCallback(data, size);
  1933. }
  1934. delete[] data;
  1935. uv_mutex_lock(&async_lock);
  1936. }
  1937. uv_mutex_unlock(&async_lock);
  1938. }
  1939. private:
  1940. void SendProgress_(const T *data, size_t count) {
  1941. T *new_data = new T[count];
  1942. std::copy(data, data + count, new_data);
  1943. uv_mutex_lock(&async_lock);
  1944. asyncdata_.push(std::pair<T*, size_t>(new_data, count));
  1945. uv_mutex_unlock(&async_lock);
  1946. uv_async_send(&this->async);
  1947. }
  1948. uv_mutex_t async_lock;
  1949. std::queue<std::pair<T*, size_t> > asyncdata_;
  1950. };
  1951. inline void AsyncExecute (uv_work_t* req) {
  1952. AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
  1953. worker->Execute();
  1954. }
  1955. /* uv_after_work_cb has 1 argument before node-v0.9.4 and
  1956. * 2 arguments since node-v0.9.4
  1957. * https://github.com/libuv/libuv/commit/92fb84b751e18f032c02609467f44bfe927b80c5
  1958. */
  1959. inline void AsyncExecuteComplete(uv_work_t *req) {
  1960. AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
  1961. worker->WorkComplete();
  1962. worker->Destroy();
  1963. }
  1964. inline void AsyncExecuteComplete (uv_work_t* req, int status) {
  1965. AsyncExecuteComplete(req);
  1966. }
  1967. inline void AsyncQueueWorker (AsyncWorker* worker) {
  1968. uv_queue_work(
  1969. GetCurrentEventLoop()
  1970. , &worker->request
  1971. , AsyncExecute
  1972. , AsyncExecuteComplete
  1973. );
  1974. }
  1975. namespace imp {
  1976. inline
  1977. ExternalOneByteStringResource const*
  1978. GetExternalResource(v8::Local<v8::String> str) {
  1979. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  1980. return str->GetExternalAsciiStringResource();
  1981. #else
  1982. return str->GetExternalOneByteStringResource();
  1983. #endif
  1984. }
  1985. inline
  1986. bool
  1987. IsExternal(v8::Local<v8::String> str) {
  1988. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  1989. return str->IsExternalAscii();
  1990. #else
  1991. return str->IsExternalOneByte();
  1992. #endif
  1993. }
  1994. } // end of namespace imp
  1995. enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
  1996. #if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION
  1997. # include "nan_string_bytes.h" // NOLINT(build/include)
  1998. #endif
  1999. inline v8::Local<v8::Value> Encode(
  2000. const void *buf, size_t len, enum Encoding encoding = BINARY) {
  2001. #if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION)
  2002. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  2003. node::encoding node_enc = static_cast<node::encoding>(encoding);
  2004. if (encoding == UCS2) {
  2005. return node::Encode(
  2006. isolate
  2007. , reinterpret_cast<const uint16_t *>(buf)
  2008. , len / 2);
  2009. } else {
  2010. return node::Encode(
  2011. isolate
  2012. , reinterpret_cast<const char *>(buf)
  2013. , len
  2014. , node_enc);
  2015. }
  2016. #elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2017. return node::Encode(
  2018. v8::Isolate::GetCurrent()
  2019. , buf, len
  2020. , static_cast<node::encoding>(encoding));
  2021. #else
  2022. # if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  2023. return node::Encode(buf, len, static_cast<node::encoding>(encoding));
  2024. # else
  2025. return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding);
  2026. # endif
  2027. #endif
  2028. }
  2029. inline ssize_t DecodeBytes(
  2030. v8::Local<v8::Value> val, enum Encoding encoding = BINARY) {
  2031. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2032. return node::DecodeBytes(
  2033. v8::Isolate::GetCurrent()
  2034. , val
  2035. , static_cast<node::encoding>(encoding));
  2036. #else
  2037. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  2038. if (encoding == BUFFER) {
  2039. return node::DecodeBytes(val, node::BINARY);
  2040. }
  2041. # endif
  2042. return node::DecodeBytes(val, static_cast<node::encoding>(encoding));
  2043. #endif
  2044. }
  2045. inline ssize_t DecodeWrite(
  2046. char *buf
  2047. , size_t len
  2048. , v8::Local<v8::Value> val
  2049. , enum Encoding encoding = BINARY) {
  2050. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2051. return node::DecodeWrite(
  2052. v8::Isolate::GetCurrent()
  2053. , buf
  2054. , len
  2055. , val
  2056. , static_cast<node::encoding>(encoding));
  2057. #else
  2058. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  2059. if (encoding == BUFFER) {
  2060. return node::DecodeWrite(buf, len, val, node::BINARY);
  2061. }
  2062. # endif
  2063. return node::DecodeWrite(
  2064. buf
  2065. , len
  2066. , val
  2067. , static_cast<node::encoding>(encoding));
  2068. #endif
  2069. }
  2070. inline void SetPrototypeTemplate(
  2071. v8::Local<v8::FunctionTemplate> templ
  2072. , const char *name
  2073. , v8::Local<v8::Data> value
  2074. ) {
  2075. HandleScope scope;
  2076. SetTemplate(templ->PrototypeTemplate(), name, value);
  2077. }
  2078. inline void SetPrototypeTemplate(
  2079. v8::Local<v8::FunctionTemplate> templ
  2080. , v8::Local<v8::String> name
  2081. , v8::Local<v8::Data> value
  2082. , v8::PropertyAttribute attributes
  2083. ) {
  2084. HandleScope scope;
  2085. SetTemplate(templ->PrototypeTemplate(), name, value, attributes);
  2086. }
  2087. inline void SetInstanceTemplate(
  2088. v8::Local<v8::FunctionTemplate> templ
  2089. , const char *name
  2090. , v8::Local<v8::Data> value
  2091. ) {
  2092. HandleScope scope;
  2093. SetTemplate(templ->InstanceTemplate(), name, value);
  2094. }
  2095. inline void SetInstanceTemplate(
  2096. v8::Local<v8::FunctionTemplate> templ
  2097. , v8::Local<v8::String> name
  2098. , v8::Local<v8::Data> value
  2099. , v8::PropertyAttribute attributes
  2100. ) {
  2101. HandleScope scope;
  2102. SetTemplate(templ->InstanceTemplate(), name, value, attributes);
  2103. }
  2104. namespace imp {
  2105. // Note(@agnat): Helper to distinguish different receiver types. The first
  2106. // version deals with receivers derived from v8::Template. The second version
  2107. // handles everything else. The final argument only serves as discriminator and
  2108. // is unused.
  2109. template <typename T>
  2110. inline
  2111. void
  2112. SetMethodAux(T recv,
  2113. v8::Local<v8::String> name,
  2114. v8::Local<v8::FunctionTemplate> tpl,
  2115. v8::Template *) {
  2116. recv->Set(name, tpl);
  2117. }
  2118. template <typename T>
  2119. inline
  2120. void
  2121. SetMethodAux(T recv,
  2122. v8::Local<v8::String> name,
  2123. v8::Local<v8::FunctionTemplate> tpl,
  2124. ...) {
  2125. Set(recv, name, GetFunction(tpl).ToLocalChecked());
  2126. }
  2127. } // end of namespace imp
  2128. template <typename T, template <typename> class HandleType>
  2129. inline void SetMethod(
  2130. HandleType<T> recv
  2131. , const char *name
  2132. , FunctionCallback callback
  2133. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2134. HandleScope scope;
  2135. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback, data);
  2136. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2137. t->SetClassName(fn_name);
  2138. // Note(@agnat): Pass an empty T* as discriminator. See note on
  2139. // SetMethodAux(...) above
  2140. imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0));
  2141. }
  2142. inline void SetPrototypeMethod(
  2143. v8::Local<v8::FunctionTemplate> recv
  2144. , const char* name
  2145. , FunctionCallback callback
  2146. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2147. HandleScope scope;
  2148. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(
  2149. callback
  2150. , data
  2151. , New<v8::Signature>(recv));
  2152. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2153. recv->PrototypeTemplate()->Set(fn_name, t);
  2154. t->SetClassName(fn_name);
  2155. }
  2156. //=== Accessors and Such =======================================================
  2157. NAN_DEPRECATED inline void SetAccessor(
  2158. v8::Local<v8::ObjectTemplate> tpl
  2159. , v8::Local<v8::String> name
  2160. , GetterCallback getter
  2161. , SetterCallback setter
  2162. , v8::Local<v8::Value> data
  2163. , v8::AccessControl settings
  2164. , v8::PropertyAttribute attribute
  2165. , imp::Sig signature) {
  2166. HandleScope scope;
  2167. imp::NativeGetter getter_ =
  2168. imp::GetterCallbackWrapper;
  2169. imp::NativeSetter setter_ =
  2170. setter ? imp::SetterCallbackWrapper : 0;
  2171. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2172. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2173. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2174. obj->SetInternalField(
  2175. imp::kGetterIndex
  2176. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2177. if (setter != 0) {
  2178. obj->SetInternalField(
  2179. imp::kSetterIndex
  2180. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2181. }
  2182. if (!data.IsEmpty()) {
  2183. obj->SetInternalField(imp::kDataIndex, data);
  2184. }
  2185. tpl->SetAccessor(
  2186. name
  2187. , getter_
  2188. , setter_
  2189. , obj
  2190. , settings
  2191. , attribute
  2192. #if (NODE_MODULE_VERSION < NODE_16_0_MODULE_VERSION)
  2193. , signature
  2194. #endif
  2195. );
  2196. }
  2197. inline void SetAccessor(
  2198. v8::Local<v8::ObjectTemplate> tpl
  2199. , v8::Local<v8::String> name
  2200. , GetterCallback getter
  2201. , SetterCallback setter = 0
  2202. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2203. , v8::AccessControl settings = v8::DEFAULT
  2204. , v8::PropertyAttribute attribute = v8::None) {
  2205. HandleScope scope;
  2206. imp::NativeGetter getter_ =
  2207. imp::GetterCallbackWrapper;
  2208. imp::NativeSetter setter_ =
  2209. setter ? imp::SetterCallbackWrapper : 0;
  2210. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2211. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2212. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2213. obj->SetInternalField(
  2214. imp::kGetterIndex
  2215. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2216. if (setter != 0) {
  2217. obj->SetInternalField(
  2218. imp::kSetterIndex
  2219. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2220. }
  2221. if (!data.IsEmpty()) {
  2222. obj->SetInternalField(imp::kDataIndex, data);
  2223. }
  2224. tpl->SetAccessor(
  2225. name
  2226. , getter_
  2227. , setter_
  2228. , obj
  2229. , settings
  2230. , attribute
  2231. );
  2232. }
  2233. inline bool SetAccessor(
  2234. v8::Local<v8::Object> obj
  2235. , v8::Local<v8::String> name
  2236. , GetterCallback getter
  2237. , SetterCallback setter = 0
  2238. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2239. , v8::AccessControl settings = v8::DEFAULT
  2240. , v8::PropertyAttribute attribute = v8::None) {
  2241. HandleScope scope;
  2242. imp::NativeGetter getter_ =
  2243. imp::GetterCallbackWrapper;
  2244. imp::NativeSetter setter_ =
  2245. setter ? imp::SetterCallbackWrapper : 0;
  2246. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2247. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2248. v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked();
  2249. dataobj->SetInternalField(
  2250. imp::kGetterIndex
  2251. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2252. if (!data.IsEmpty()) {
  2253. dataobj->SetInternalField(imp::kDataIndex, data);
  2254. }
  2255. if (setter) {
  2256. dataobj->SetInternalField(
  2257. imp::kSetterIndex
  2258. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2259. }
  2260. #if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
  2261. return obj->SetAccessor(
  2262. GetCurrentContext()
  2263. , name
  2264. , getter_
  2265. , setter_
  2266. , dataobj
  2267. , settings
  2268. , attribute).FromMaybe(false);
  2269. #else
  2270. return obj->SetAccessor(
  2271. name
  2272. , getter_
  2273. , setter_
  2274. , dataobj
  2275. , settings
  2276. , attribute);
  2277. #endif
  2278. }
  2279. inline void SetNamedPropertyHandler(
  2280. v8::Local<v8::ObjectTemplate> tpl
  2281. , PropertyGetterCallback getter
  2282. , PropertySetterCallback setter = 0
  2283. , PropertyQueryCallback query = 0
  2284. , PropertyDeleterCallback deleter = 0
  2285. , PropertyEnumeratorCallback enumerator = 0
  2286. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2287. HandleScope scope;
  2288. imp::NativePropertyGetter getter_ =
  2289. imp::PropertyGetterCallbackWrapper;
  2290. imp::NativePropertySetter setter_ =
  2291. setter ? imp::PropertySetterCallbackWrapper : 0;
  2292. imp::NativePropertyQuery query_ =
  2293. query ? imp::PropertyQueryCallbackWrapper : 0;
  2294. imp::NativePropertyDeleter *deleter_ =
  2295. deleter ? imp::PropertyDeleterCallbackWrapper : 0;
  2296. imp::NativePropertyEnumerator enumerator_ =
  2297. enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0;
  2298. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2299. otpl->SetInternalFieldCount(imp::kPropertyFieldCount);
  2300. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2301. obj->SetInternalField(
  2302. imp::kPropertyGetterIndex
  2303. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2304. if (setter) {
  2305. obj->SetInternalField(
  2306. imp::kPropertySetterIndex
  2307. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2308. }
  2309. if (query) {
  2310. obj->SetInternalField(
  2311. imp::kPropertyQueryIndex
  2312. , New<v8::External>(reinterpret_cast<void *>(query)));
  2313. }
  2314. if (deleter) {
  2315. obj->SetInternalField(
  2316. imp::kPropertyDeleterIndex
  2317. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2318. }
  2319. if (enumerator) {
  2320. obj->SetInternalField(
  2321. imp::kPropertyEnumeratorIndex
  2322. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2323. }
  2324. if (!data.IsEmpty()) {
  2325. obj->SetInternalField(imp::kDataIndex, data);
  2326. }
  2327. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2328. tpl->SetHandler(v8::NamedPropertyHandlerConfiguration(
  2329. getter_, setter_, query_, deleter_, enumerator_, obj));
  2330. #else
  2331. tpl->SetNamedPropertyHandler(
  2332. getter_
  2333. , setter_
  2334. , query_
  2335. , deleter_
  2336. , enumerator_
  2337. , obj);
  2338. #endif
  2339. }
  2340. inline void SetIndexedPropertyHandler(
  2341. v8::Local<v8::ObjectTemplate> tpl
  2342. , IndexGetterCallback getter
  2343. , IndexSetterCallback setter = 0
  2344. , IndexQueryCallback query = 0
  2345. , IndexDeleterCallback deleter = 0
  2346. , IndexEnumeratorCallback enumerator = 0
  2347. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2348. HandleScope scope;
  2349. imp::NativeIndexGetter getter_ =
  2350. imp::IndexGetterCallbackWrapper;
  2351. imp::NativeIndexSetter setter_ =
  2352. setter ? imp::IndexSetterCallbackWrapper : 0;
  2353. imp::NativeIndexQuery query_ =
  2354. query ? imp::IndexQueryCallbackWrapper : 0;
  2355. imp::NativeIndexDeleter deleter_ =
  2356. deleter ? imp::IndexDeleterCallbackWrapper : 0;
  2357. imp::NativeIndexEnumerator enumerator_ =
  2358. enumerator ? imp::IndexEnumeratorCallbackWrapper : 0;
  2359. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2360. otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount);
  2361. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2362. obj->SetInternalField(
  2363. imp::kIndexPropertyGetterIndex
  2364. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2365. if (setter) {
  2366. obj->SetInternalField(
  2367. imp::kIndexPropertySetterIndex
  2368. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2369. }
  2370. if (query) {
  2371. obj->SetInternalField(
  2372. imp::kIndexPropertyQueryIndex
  2373. , New<v8::External>(reinterpret_cast<void *>(query)));
  2374. }
  2375. if (deleter) {
  2376. obj->SetInternalField(
  2377. imp::kIndexPropertyDeleterIndex
  2378. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2379. }
  2380. if (enumerator) {
  2381. obj->SetInternalField(
  2382. imp::kIndexPropertyEnumeratorIndex
  2383. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2384. }
  2385. if (!data.IsEmpty()) {
  2386. obj->SetInternalField(imp::kDataIndex, data);
  2387. }
  2388. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2389. tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration(
  2390. getter_, setter_, query_, deleter_, enumerator_, obj));
  2391. #else
  2392. tpl->SetIndexedPropertyHandler(
  2393. getter_
  2394. , setter_
  2395. , query_
  2396. , deleter_
  2397. , enumerator_
  2398. , obj);
  2399. #endif
  2400. }
  2401. inline void SetCallHandler(
  2402. v8::Local<v8::FunctionTemplate> tpl
  2403. , FunctionCallback callback
  2404. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2405. HandleScope scope;
  2406. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2407. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2408. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2409. obj->SetInternalField(
  2410. imp::kFunctionIndex
  2411. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2412. if (!data.IsEmpty()) {
  2413. obj->SetInternalField(imp::kDataIndex, data);
  2414. }
  2415. tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj);
  2416. }
  2417. inline void SetCallAsFunctionHandler(
  2418. v8::Local<v8::ObjectTemplate> tpl,
  2419. FunctionCallback callback,
  2420. v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2421. HandleScope scope;
  2422. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2423. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2424. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2425. obj->SetInternalField(
  2426. imp::kFunctionIndex
  2427. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2428. if (!data.IsEmpty()) {
  2429. obj->SetInternalField(imp::kDataIndex, data);
  2430. }
  2431. tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj);
  2432. }
  2433. //=== Weak Persistent Handling =================================================
  2434. #include "nan_weak.h" // NOLINT(build/include)
  2435. //=== ObjectWrap ===============================================================
  2436. #include "nan_object_wrap.h" // NOLINT(build/include)
  2437. //=== HiddenValue/Private ======================================================
  2438. #include "nan_private.h" // NOLINT(build/include)
  2439. //=== Export ==================================================================
  2440. inline
  2441. void
  2442. Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name,
  2443. FunctionCallback f) {
  2444. HandleScope scope;
  2445. Set(target, New<v8::String>(name).ToLocalChecked(),
  2446. GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked());
  2447. }
  2448. //=== Tap Reverse Binding =====================================================
  2449. struct Tap {
  2450. explicit Tap(v8::Local<v8::Value> t) : t_() {
  2451. HandleScope scope;
  2452. t_.Reset(To<v8::Object>(t).ToLocalChecked());
  2453. }
  2454. ~Tap() { t_.Reset(); } // not sure if necessary
  2455. inline void plan(int i) {
  2456. HandleScope scope;
  2457. v8::Local<v8::Value> arg = New(i);
  2458. Call("plan", New(t_), 1, &arg);
  2459. }
  2460. inline void ok(bool isOk, const char *msg = NULL) {
  2461. HandleScope scope;
  2462. v8::Local<v8::Value> args[2];
  2463. args[0] = New(isOk);
  2464. if (msg) args[1] = New(msg).ToLocalChecked();
  2465. Call("ok", New(t_), msg ? 2 : 1, args);
  2466. }
  2467. inline void pass(const char * msg = NULL) {
  2468. HandleScope scope;
  2469. v8::Local<v8::Value> hmsg;
  2470. if (msg) hmsg = New(msg).ToLocalChecked();
  2471. Call("pass", New(t_), msg ? 1 : 0, &hmsg);
  2472. }
  2473. inline void end() {
  2474. HandleScope scope;
  2475. Call("end", New(t_), 0, NULL);
  2476. }
  2477. private:
  2478. Persistent<v8::Object> t_;
  2479. };
  2480. #define NAN_STRINGIZE2(x) #x
  2481. #define NAN_STRINGIZE(x) NAN_STRINGIZE2(x)
  2482. #define NAN_TEST_EXPRESSION(expression) \
  2483. ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression
  2484. #define NAN_EXPORT(target, function) Export(target, #function, function)
  2485. #undef TYPE_CHECK
  2486. //=== Generic Maybefication ===================================================
  2487. namespace imp {
  2488. template <typename T> struct Maybefier;
  2489. template <typename T> struct Maybefier<v8::Local<T> > {
  2490. inline static MaybeLocal<T> convert(v8::Local<T> v) {
  2491. return v;
  2492. }
  2493. };
  2494. template <typename T> struct Maybefier<MaybeLocal<T> > {
  2495. inline static MaybeLocal<T> convert(MaybeLocal<T> v) {
  2496. return v;
  2497. }
  2498. };
  2499. } // end of namespace imp
  2500. template <typename T, template <typename> class MaybeMaybe>
  2501. inline MaybeLocal<T>
  2502. MakeMaybe(MaybeMaybe<T> v) {
  2503. return imp::Maybefier<MaybeMaybe<T> >::convert(v);
  2504. }
  2505. //=== TypedArrayContents =======================================================
  2506. #include "nan_typedarray_contents.h" // NOLINT(build/include)
  2507. //=== JSON =====================================================================
  2508. #include "nan_json.h" // NOLINT(build/include)
  2509. //=== ScriptOrigin =============================================================
  2510. #include "nan_scriptorigin.h" // NOLINT(build/include)
  2511. } // end of namespace Nan
  2512. #endif // NAN_H_