nan.h 71 KB

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