nan.h 66 KB

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