-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathStdLibs.cpp
More file actions
939 lines (790 loc) · 23.9 KB
/
StdLibs.cpp
File metadata and controls
939 lines (790 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
#include <hxcpp.h>
#include <hxMath.h>
#include <hx/Memory.h>
#include <hx/Thread.h>
#ifdef HX_WINDOWS
#include <windows.h>
#include <io.h>
#elif defined(__unix__) || defined(__APPLE__)
#include <sys/time.h>
#ifndef EMSCRIPTEN
typedef int64_t __int64;
#endif
#endif
#ifdef ANDROID
#include <android/log.h>
#endif
#ifdef WEBOS
#include <syslog.h>
#endif
#ifdef TIZEN
#include <dlog.h>
#endif
#if defined(BLACKBERRY) || defined(GCW0)
#include <unistd.h>
#endif
#include <string>
#include <map>
#include <stdio.h>
#include <time.h>
#include <clocale>
#include <mutex>
#ifdef HX_ANDROID
#define rand() lrand48()
#define srand(x) srand48(x)
#endif
#ifdef HX_WINRT
#define PRINTF WINRT_PRINTF
#elif defined(TIZEN)
#define PRINTF(fmt, ...) dlog_dprint(DLOG_INFO, "trace", fmt, __VA_ARGS__);
#elif defined(HX_ANDROID) && !defined(HXCPP_EXE_LINK)
#define PRINTF(fmt, ...) __android_log_print(ANDROID_LOG_INFO, "trace", fmt, __VA_ARGS__);
#elif defined(WEBOS)
#define PRINTF(fmt, ...) syslog(LOG_INFO, "trace", fmt, __VA_ARGS__);
#else
#define PRINTF printf
#endif
void __hx_stack_set_last_exception();
void __hx_stack_push_last_exception();
int _hxcpp_argc = 0;
char **_hxcpp_argv = 0;
namespace hx
{
Dynamic Throw(Dynamic inDynamic)
{
#ifdef HXCPP_STACK_TRACE
__hx_stack_set_last_exception();
#endif
throw inDynamic;
return null();
}
Dynamic Rethrow(Dynamic inDynamic)
{
#ifdef HXCPP_STACK_TRACE
__hx_stack_push_last_exception();
#endif
throw inDynamic;
return null();
}
null NullArithmetic(const char *inErr)
{
Throw( String::create(inErr) );
return null();
}
}
// -------- Resources ---------------------------------------
namespace hx
{
//typedef std::map<std::wstring,Resource> ResourceSet;
//static ResourceSet sgResources;
Resource *sgResources = 0;
Resource *sgSecondResources = 0;
void RegisterResources(Resource *inResources)
{
if (sgResources)
sgSecondResources = inResources;
else
sgResources = inResources;
}
}
using namespace hx;
Array<String> __hxcpp_resource_names()
{
Array<String> result(0,0);
if (sgResources)
for(Resource *reso = sgResources; reso->mData; reso++)
result->push( reso->mName );
if (sgSecondResources)
for(Resource *reso = sgSecondResources; reso->mData; reso++)
result->push( reso->mName );
return result;
}
String __hxcpp_resource_string(String inName)
{
if (sgResources)
for(Resource *reso = sgResources; reso->mData; reso++)
{
if (reso->mName == inName)
#if (HXCPP_API_LEVEL > 0)
{
#ifdef HX_SMART_STRINGS
const unsigned char *p = reso->mData;
for(int i=0;i<reso->mDataLength;i++)
if (p[i]>127)
return String::create((const char *)p, reso->mDataLength);
#endif
return String((const char *) reso->mData, reso->mDataLength );
}
#else
return String::create((const char *) reso->mData, reso->mDataLength );
#endif
}
if (sgSecondResources)
{
for(Resource *reso = sgSecondResources; reso->mData; reso++)
if (reso->mName == inName)
{
#ifdef HX_SMART_STRINGS
const unsigned char *p = reso->mData;
for(int i=0;i<reso->mDataLength;i++)
if (p[i]>127)
return _hx_utf8_to_utf16(p, reso->mDataLength,false);
#endif
return String((const char *) reso->mData, reso->mDataLength );
return String((const char *) reso->mData, reso->mDataLength );
}
}
return null();
}
Array<unsigned char> __hxcpp_resource_bytes(String inName)
{
if (sgResources)
for(Resource *reso = sgResources; reso->mData; reso++)
{
if (reso->mName == inName)
{
int len = reso->mDataLength;
Array<unsigned char> result( len, 0);
memcpy( result->GetBase() , reso->mData, len );
return result;
}
}
if (sgSecondResources)
for(Resource *reso = sgSecondResources; reso->mData; reso++)
{
if (reso->mName == inName)
{
int len = reso->mDataLength;
Array<unsigned char> result( len, 0);
memcpy( result->GetBase() , reso->mData, len );
return result;
}
}
return null();
}
// -- hx::Native -------
extern "C" void __hxcpp_lib_main();
namespace hx
{
static std::string initReturnBuffer;
const char *Init(bool stayAttached)
{
try
{
__hxcpp_lib_main();
if (!stayAttached)
SetTopOfStack(0,true);
return 0;
}
catch(Dynamic e)
{
HX_TOP_OF_STACK
if (!stayAttached)
{
initReturnBuffer = e->toString().utf8_str();
SetTopOfStack(0,true);
return initReturnBuffer.c_str();
}
return e->toString().utf8_str();
}
}
}
// --- System ---------------------------------------------------------------------
// --- Maths ---------------------------------------------------------
static double rand_scale = 1.0 / (1<<16) / (1<<16);
double __hxcpp_drand()
{
unsigned int lo = rand() & 0xfff;
unsigned int mid = rand() & 0xfff;
unsigned int hi = rand() & 0xff;
double result = (lo | (mid<<12) | (hi<<24) ) * rand_scale;
return result;
}
int __hxcpp_irand(int inMax)
{
unsigned int lo = rand() & 0xfff;
unsigned int mid = rand() & 0xfff;
unsigned int hi = rand() & 0xff;
return (lo | (mid<<12) | (hi<<24) ) % inMax;
}
#ifdef HX_WINDOWS
LARGE_INTEGER qpcFrequency;
#endif
void __hxcpp_stdlibs_boot()
{
#ifdef HX_WINDOWS
// MSDN states that QueryPerformanceFrequency will always succeed on XP and above, so I'm ignoring the result.
QueryPerformanceFrequency(&qpcFrequency);
#endif
#if defined(HX_WINDOWS) && !defined(HX_WINRT)
if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
} else if (GetConsoleWindow()) {
if (_fileno(stdout) < 0 || _get_osfhandle(fileno(stdout)) < 0)
freopen("CONOUT$", "w", stdout);
if (_fileno(stderr) < 0 || _get_osfhandle(fileno(stderr)) < 0)
freopen("CONOUT$", "w", stderr);
if (_fileno(stdin) < 0 || _get_osfhandle(fileno(stdin)) < 0)
freopen("CONIN$", "r", stdin);
}
//_setmode(_fileno(stdout), 0x00040000); // _O_U8TEXT
//_setmode(_fileno(stderr), 0x00040000); // _O_U8TEXT
//_setmode(_fileno(stdin), 0x00040000); // _O_U8TEXT
#endif
setlocale(LC_NUMERIC, "C");
// I think this does more harm than good.
// It does not cause fread to return immediately - as perhaps desired.
// But it does cause some new-line characters to be lost.
//setbuf(stdin, 0);
setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
setbuf(stderr, 0);
}
#ifdef HX_WINDOWS
void WriteConsoleAllW(HANDLE h, const wchar_t *str, DWORD length) {
DWORD total_written = 0;
DWORD remaining = length;
while (total_written < length) {
DWORD written;
if (!WriteConsoleW(h, str + total_written, remaining, &written, NULL))
{
return;
}
if (written == remaining) {
return;
}
total_written += written;
remaining -= written;
}
}
void WriteConsoleAllA(HANDLE h, const char *str, DWORD length) {
DWORD total_written = 0;
DWORD remaining = length;
while (total_written < length) {
DWORD written;
if (!WriteConsoleA(h, str + total_written, remaining, &written, NULL))
{
return;
}
if (written == remaining) {
return;
}
total_written += written;
remaining -= written;
}
}
#endif
void __trace(Dynamic inObj, Dynamic info)
{
String text;
if (inObj != null())
text = inObj->toString();
#ifdef HX_WINDOWS
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode;
if (GetConsoleMode(handle, &mode))
{
fflush(stdout);
String s;
if (info == null()) {
s = String("?? ") + text + String("\n");
} else {
String filename = Dynamic((info)->__Field(HX_CSTRING("fileName"), HX_PROP_DYNAMIC))->toString();
int line = Dynamic((info)->__Field(HX_CSTRING("lineNumber"), HX_PROP_DYNAMIC))->__ToInt();
s = filename + String(":") + line + String(": ") + text + String("\n");
}
if (s.isUTF16Encoded())
{
WriteConsoleAllW(handle, s.__WCStr(), s.length);
} else {
// ascii
WriteConsoleAllA(handle, s.__CStr(), s.length);
}
return;
}
#endif
hx::strbuf convertBuf;
if (info==null())
{
PRINTF("?? %s\n", text.raw_ptr() ? text.out_str(&convertBuf) : "null");
}
else
{
const char *filename = Dynamic((info)->__Field(HX_CSTRING("fileName"), HX_PROP_DYNAMIC))->toString().utf8_str(0,false);
int line = Dynamic((info)->__Field( HX_CSTRING("lineNumber") , HX_PROP_DYNAMIC))->__ToInt();
hx::strbuf convertBuf;
//PRINTF("%s:%d: %s\n", filename, line, text.raw_ptr() ? text.out_str(&convertBuf) : "null");
PRINTF("%s:%d: %s\n", filename, line, text.raw_ptr() ? text.out_str(&convertBuf) : "null");
}
fflush(stdout);
}
void __hxcpp_exit(int inExitCode)
{
exit(inExitCode);
}
double __time_stamp()
{
#ifdef HX_WINDOWS
static __int64 t0=0;
static double period=0;
__int64 now;
if (QueryPerformanceCounter((LARGE_INTEGER*)&now))
{
if (t0==0)
{
t0 = now;
period = 1.0/qpcFrequency.QuadPart;
}
if (period!=0)
return (now-t0)*period;
}
return (double)clock() / ( (double)CLOCKS_PER_SEC);
#elif defined(__unix__) || defined(__APPLE__)
static double t0 = 0;
struct timeval tv;
if( gettimeofday(&tv,0) )
throw Dynamic("Could not get time");
double t = ( tv.tv_sec + ((double)tv.tv_usec) / 1000000.0 );
if (t0==0) t0 = t;
return t-t0;
#else
return (double)clock() / ( (double)CLOCKS_PER_SEC);
#endif
}
::cpp::Int64 __time_stamp_ms()
{
#ifdef HX_WINDOWS
// MSDN states that QueryPerformanceCounter will always succeed on XP and above, so I'm ignoring the result.
auto now = LARGE_INTEGER{ 0 };
QueryPerformanceCounter(&now);
return now.QuadPart * LONGLONG{ 1000 } / qpcFrequency.QuadPart;
#else
auto time = timespec();
if (clock_gettime(CLOCK_MONOTONIC, &time))
{
throw ::Dynamic(HX_CSTRING("Failed to get the monotonic clock time"));
}
return time.tv_sec * 1000 + (time.tv_nsec / 1000000);
#endif
}
#if defined(HX_WINDOWS) && !defined(HX_WINRT)
/*
ISWHITE and ParseCommandLine are based on the implementation of the
.NET Core runtime, CoreCLR, which is licensed under the MIT license:
Copyright (c) Microsoft. All rights reserved.
See LICENSE file in the CoreCLR project root for full license information.
The original source code of ParseCommandLine can be found in
https://github.com/dotnet/coreclr/blob/master/src/vm/util.cpp
*/
#define ISWHITE(x) ((x)==(' ') || (x)==('\t') || (x)==('\n') || (x)==('\r') )
static void ParseCommandLine(LPWSTR psrc, Array<String> &out)
{
unsigned int argcount = 1; // discovery of arg0 is unconditional, below
bool fInQuotes;
int iSlash;
/* A quoted program name is handled here. The handling is much
simpler than for other arguments. Basically, whatever lies
between the leading double-quote and next one, or a terminal null
character is simply accepted. Fancier handling is not required
because the program name must be a legal NTFS/HPFS file name.
Note that the double-quote characters are not copied, nor do they
contribute to numchars.
This "simplification" is necessary for compatibility reasons even
though it leads to mishandling of certain cases. For example,
"c:\tests\"test.exe will result in an arg0 of c:\tests\ and an
arg1 of test.exe. In any rational world this is incorrect, but
we need to preserve compatibility.
*/
LPWSTR pStart = psrc;
bool skipQuote = false;
// Pairs of double-quotes vanish...
while(psrc[0]=='\"' && psrc[1]=='\"')
psrc += 2;
if (*psrc == '\"')
{
// scan from just past the first double-quote through the next
// double-quote, or up to a null, whichever comes first
psrc++;
while ((*psrc!= '\"') && (*psrc != '\0'))
{
psrc++;
// Pairs of double-quotes vanish...
while(psrc[0]=='\"' && psrc[1]=='\"')
psrc += 2;
}
skipQuote = true;
}
else
{
/* Not a quoted program name */
while (!ISWHITE(*psrc) && *psrc != '\0')
psrc++;
}
// We have now identified arg0 as pStart (or pStart+1 if we have a leading
// quote) through psrc-1 inclusive
if (skipQuote)
pStart++;
String arg0("");
while (pStart < psrc)
{
arg0 += String::fromCharCode(*pStart);
pStart++;
}
// out.Add(arg0); // the command isn't part of Sys.args()
// if we stopped on a double-quote when arg0 is quoted, skip over it
if (skipQuote && *psrc == '\"')
psrc++;
while ( *psrc != '\0')
{
LEADINGWHITE:
// The outofarg state.
while (ISWHITE(*psrc))
psrc++;
if (*psrc == '\0')
break;
else
if (*psrc == '#')
{
while (*psrc != '\0' && *psrc != '\n')
psrc++; // skip to end of line
goto LEADINGWHITE;
}
argcount++;
fInQuotes = FALSE;
String arg("");
while ((!ISWHITE(*psrc) || fInQuotes) && *psrc != '\0')
{
switch (*psrc)
{
case '\\':
iSlash = 0;
while (*psrc == '\\')
{
iSlash++;
psrc++;
}
if (*psrc == '\"')
{
for ( ; iSlash >= 2; iSlash -= 2)
{
arg += String("\\");
}
if (iSlash & 1)
{
arg += String::fromCharCode(*psrc);
psrc++;
}
else
{
fInQuotes = !fInQuotes;
psrc++;
}
}
else
for ( ; iSlash > 0; iSlash--)
{
arg += String("\\");
}
break;
case '\"':
fInQuotes = !fInQuotes;
psrc++;
break;
default:
arg += String::fromCharCode(*psrc);
psrc++;
}
}
out.Add(arg);
arg = String("");
}
}
#endif
#ifdef __APPLE__
#if !defined(IPHONE) && !defined(APPLETV) && !defined(HX_APPLEWATCH)
extern "C" {
extern int *_NSGetArgc(void);
extern char ***_NSGetArgv(void);
}
#endif
#endif
Array<String> __get_args()
{
Array<String> result(0,0);
if (_hxcpp_argc)
{
for(int i=1;i<_hxcpp_argc;i++)
result->push( String::create(_hxcpp_argv[i],strlen(_hxcpp_argv[i])) );
return result;
}
#ifdef HX_WINRT
// Do nothing
#elif defined(HX_WINDOWS)
LPWSTR str = GetCommandLineW();
ParseCommandLine(str, result);
#else
#ifdef __APPLE__
#if !defined(IPHONE) && !defined(APPLETV) && !defined(HX_APPLEWATCH)
int argc = *_NSGetArgc();
char **argv = *_NSGetArgv();
for(int i=1;i<argc;i++)
result->push( String::create(argv[i],strlen(argv[i])) );
#endif
#else
#ifdef ANDROID
// TODO: Get from java
#elif defined(__linux__)
char buf[80];
sprintf(buf, "/proc/%d/cmdline", getpid());
FILE *cmd = fopen(buf,"rb");
bool real_arg = 0;
if (cmd)
{
hx::QuickVec<char> arg;
buf[0] = '\0';
while (fread(buf, 1, 1, cmd))
{
if ((unsigned char)buf[0] == 0) // line terminator
{
if (real_arg)
result->push( String::create(arg.mPtr, arg.mSize) );
real_arg = true;
arg.clear();
}
else
arg.push(buf[0]);
}
fclose(cmd);
}
#endif
#endif
#endif
return result;
}
void __hxcpp_print_string(const String &inV)
{
#ifdef HX_WINDOWS
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode;
if (GetConsoleMode(handle, &mode) && inV.isUTF16Encoded())
{
fflush(stdout);
WriteConsoleAllW(handle, inV.__WCStr(), inV.length);
return;
}
#endif
hx::strbuf convertBuf;
PRINTF("%s", inV.out_str(&convertBuf) );
}
void __hxcpp_println_string(const String &inV)
{
#ifdef HX_WINDOWS
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode;
if (GetConsoleMode(handle, &mode) && inV.isUTF16Encoded())
{
fflush(stdout);
WriteConsoleAllW(handle, inV.__WCStr(), inV.length);
fwrite("\n", 1, 1, stdout);
fflush(stdout);
return;
}
#endif
hx::strbuf convertBuf;
PRINTF("%s\n", inV.out_str(&convertBuf));
fflush(stdout);
}
// --- Casting/Converting ---------------------------------------------------------
bool __instanceof(const Dynamic &inValue, const Dynamic &inType)
{
if (inValue==null())
return false;
if (inType==hx::Object::__SGetClass())
return true;
hx::Class c = inType;
if (c==null())
return false;
return c->CanCast(inValue.GetPtr());
}
int __int__(double x)
{
#ifndef EMSCRIPTEN
if (x < -0x7fffffff || x>0x7fffffff )
{
__int64 big_int = (__int64)(x);
return big_int & 0xffffffff;
}
else
#endif
return (int)x;
}
static inline bool is_hex_string(const char *c, int len)
{
return (len > 2 && c[0] == '0' && (c[1] == 'x' || c[1] == 'X'))
|| (len > 3 && (c[0] == '-' || c[0] == '+') && c[1] == '0' && (c[2] == 'x' || c[2] == 'X'));
}
Dynamic __hxcpp_parse_int(const String &inString)
{
if (!inString.raw_ptr())
return null();
hx::strbuf buf;
const char *str = inString.utf8_str(&buf);
// On the first non space char check to see if we've got a hex string
while (isspace(*str)) ++str;
bool isHex = is_hex_string(str, strlen(str));
char *end = 0;
long result;
if (isHex)
{
bool neg = str[0] == '-';
if (neg) str++;
result = strtoul(str,&end,16);
if (neg) result = -result;
}
else
result = strtol(str,&end,10);
#ifdef HX_WINDOWS
if (str==end && !isHex)
#else
if (str==end)
#endif
return null();
return (int)result;
}
double __hxcpp_parse_substr_float(const String &inString,int start, int length)
{
if (start>=inString.length || length<1 || (start+length)>inString.length )
return Math_obj::NaN;
hx::strbuf buf;
const char *str = inString.ascii_substr(&buf,start,length);
char *end = (char *)str;
double result = str ? strtod(str,&end) : 0;
if (end==str)
return Math_obj::NaN;
return result;
}
double __hxcpp_parse_float(const String &inString)
{
if (!inString.raw_ptr())
return Math_obj::NaN;
hx::strbuf buf;
const char *str = inString.utf8_str(&buf);
char *end = (char *)str;
double result = str ? strtod(str,&end) : 0;
if (end==str)
return Math_obj::NaN;
return result;
}
bool __hxcpp_same_closure(Dynamic &inF1,Dynamic &inF2)
{
hx::Object *p1 = inF1.GetPtr();
hx::Object *p2 = inF2.GetPtr();
if (p1==0 || p2==0)
return false;
if ( (p1->__GetHandle() != p2->__GetHandle()))
return false;
return p1->__Compare(p2)==0;
}
namespace hx
{
struct VarArgFunc : public hx::Object
{
HX_IS_INSTANCE_OF enum { _hx_ClassId = hx::clsIdClosure };
VarArgFunc(Dynamic &inFunc) : mRealFunc(inFunc) {
HX_OBJ_WB_NEW_MARKED_OBJECT(this)
}
#if (HXCPP_API_LEVEL>=500)
VarArgFunc(::hx::Callable<::Dynamic(::cpp::VirtualArray)>& inFunc) : mRealFunc(inFunc) {
HX_OBJ_WB_NEW_MARKED_OBJECT(this)
}
#endif
int __GetType() const { return vtFunction; }
::String __ToString() const { return mRealFunc->__ToString() ; }
void __Mark(hx::MarkContext *__inCtx) { HX_MARK_MEMBER(mRealFunc); }
#ifdef HXCPP_VISIT_ALLOCS
void __Visit(hx::VisitContext *__inCtx) { HX_VISIT_MEMBER(mRealFunc); }
#endif
void *__GetHandle() const { return mRealFunc.GetPtr(); }
Dynamic __Run(const Array<Dynamic> &inArgs)
{
#if (HXCPP_API_LEVEL>=500)
return hx::invoker::invoke(mRealFunc.mPtr, inArgs);
#else
return mRealFunc->__run(inArgs);
#endif
}
Dynamic mRealFunc;
};
}
#if (HXCPP_API_LEVEL>=500)
Dynamic __hxcpp_create_var_args(::hx::Callable<::Dynamic(::cpp::VirtualArray)>& inArrayFunc)
#else
Dynamic __hxcpp_create_var_args(Dynamic &inArrayFunc)
#endif
{
return Dynamic(new hx::VarArgFunc(inArrayFunc));
}
// --- CFFI helpers ------------------------------------------------------------------
// Field name management
static std::mutex sgFieldMapMutex;
typedef std::map<std::string,int> StringToField;
// These need to be pointers because of the unknown order of static object construction.
String *sgFieldToString=0;
int sgFieldToStringSize=0;
int sgFieldToStringAlloc=0;
StringToField *sgStringToField=0;
static String sgNullString;
const String &__hxcpp_field_from_id( int f )
{
if (!sgFieldToString)
return sgNullString;
return sgFieldToString[f];
}
int __hxcpp_field_to_id( const char *inFieldName )
{
std::lock_guard<std::mutex> lock(sgFieldMapMutex);
if (!sgFieldToStringAlloc)
{
sgFieldToStringAlloc = 100;
sgFieldToString = (String *)HxAlloc(sgFieldToStringAlloc * sizeof(String));
sgStringToField = new StringToField;
}
std::string f(inFieldName);
StringToField::iterator i = sgStringToField->find(f);
if (i!=sgStringToField->end())
return i->second;
int result = sgFieldToStringSize;
(*sgStringToField)[f] = result;
String str(inFieldName,strlen(inFieldName));
// Make into "const" string that will not get collected...
str = String((char *)hx::InternalCreateConstBuffer(str.raw_ptr(),(str.length+1) * sizeof(char),true), str.length );
if (sgFieldToStringAlloc<=sgFieldToStringSize+1)
{
int oldAlloc = sgFieldToStringAlloc;
String *oldData = sgFieldToString;
sgFieldToStringAlloc *= 2;
String *newData = (String *)malloc(sgFieldToStringAlloc*sizeof(String));
if (oldAlloc)
memcpy(newData, oldData, oldAlloc*sizeof(String));
// Let oldData dangle to keep it thread safe, rather than require mutex on id read.
sgFieldToString = newData;
}
sgFieldToString[sgFieldToStringSize++] = str;
return result;
}
// --- haxe.Int32 ---------------------------------------------------------------------
void __hxcpp_check_overflow(int x)
{
if( (((x) >> 30) & 1) != ((unsigned int)(x) >> 31) )
throw Dynamic(HX_CSTRING("Overflow ")+x);
}
// --- Memory ---------------------------------------------------------------------
unsigned char *__hxcpp_memory = 0;
void __hxcpp_memory_memset(Array<unsigned char> &inBuffer ,int pos, int len, int value)
{
if (pos<inBuffer->length)
{
if (pos+len>inBuffer->length)
len = inBuffer->length - pos;
if (len>0)
memset( inBuffer->Pointer() + pos, value, len);
}
}