-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathlibrary.js
3771 lines (3455 loc) · 144 KB
/
library.js
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2010 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
//"use strict";
// An implementation of basic necessary libraries for the web. This integrates
// with a compiled libc and with the rest of the JS runtime.
//
// We search the Library object when there is an external function. If the
// entry in the Library is a function, we insert it. If it is a string, we
// do another lookup in the library (a simple way to write a function once,
// if it can be called by different names). We also allow dependencies,
// using __deps. Initialization code to be run after allocating all
// global constants can be defined by __postset.
//
// Note that the full function name will be '_' + the name in the Library
// object. For convenience, the short name appears here. Note that if you add a
// new function with an '_', it will not be found.
addToLibrary({
$ptrToString: (ptr) => {
#if ASSERTIONS
assert(typeof ptr === 'number');
#endif
#if !CAN_ADDRESS_2GB && !MEMORY64
// With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
ptr >>>= 0;
#endif
return '0x' + ptr.toString(16).padStart(8, '0');
},
$zeroMemory: (address, size) => {
#if LEGACY_VM_SUPPORT
if (!HEAPU8.fill) {
for (var i = 0; i < size; i++) {
HEAPU8[address + i] = 0;
}
return;
}
#endif
HEAPU8.fill(0, address, address + size);
return address;
},
#if SAFE_HEAP
// Trivial wrappers around runtime functions that make these symbols available
// to native code.
segfault: '=segfault',
alignfault: '=alignfault',
#endif
// ==========================================================================
// JavaScript <-> C string interop
// ==========================================================================
#if !MINIMAL_RUNTIME
$exitJS__docs: '/** @param {boolean|number=} implicit */',
$exitJS__deps: [
'proc_exit',
#if ASSERTIONS || EXIT_RUNTIME
'$keepRuntimeAlive',
#endif
#if PTHREADS_DEBUG
'$runtimeKeepaliveCounter',
#endif
],
$exitJS: (status, implicit) => {
EXITSTATUS = status;
#if ASSERTIONS && !EXIT_RUNTIME
checkUnflushedContent();
#endif // ASSERTIONS && !EXIT_RUNTIME
#if PTHREADS
if (ENVIRONMENT_IS_PTHREAD) {
// implicit exit can never happen on a pthread
#if ASSERTIONS
assert(!implicit);
#endif
#if PTHREADS_DEBUG
dbg(`Pthread ${ptrToString(_pthread_self())} called exit(${status}), posting exitOnMainThread.`);
#endif
// When running in a pthread we propagate the exit back to the main thread
// where it can decide if the whole process should be shut down or not.
// The pthread may have decided not to exit its own runtime, for example
// because it runs a main loop, but that doesn't affect the main thread.
exitOnMainThread(status);
throw 'unwind';
}
#if PTHREADS_DEBUG
err(`main thread called exit(${status}): keepRuntimeAlive=${keepRuntimeAlive()} (counter=${runtimeKeepaliveCounter})`);
#endif // PTHREADS_DEBUG
#endif // PTHREADS
#if EXIT_RUNTIME
if (!keepRuntimeAlive()) {
exitRuntime();
}
#endif
#if ASSERTIONS
// if exit() was called explicitly, warn the user if the runtime isn't actually being shut down
if (keepRuntimeAlive() && !implicit) {
var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;
#if MODULARIZE
readyPromiseReject(msg);
#endif // MODULARIZE
err(msg);
}
#endif // ASSERTIONS
_proc_exit(status);
},
#endif
#if MINIMAL_RUNTIME
// minimal runtime doesn't do any exit cleanup handling so just
// map exit directly to the lower-level proc_exit syscall.
exit: 'proc_exit',
#else
exit: '$exitJS',
#endif
// Returns a pointer ('p'), which means an i32 on wasm32 and an i64 wasm64
// We have a separate JS version `getHeapMax()` which can be called directly
// avoiding any wrapper added for wasm64.
emscripten_get_heap_max__deps: ['$getHeapMax'],
emscripten_get_heap_max: () => getHeapMax(),
$getHeapMax: () =>
#if ALLOW_MEMORY_GROWTH
#if MEMORY64 == 1
{{{ MAXIMUM_MEMORY }}},
#else
// Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
// for any code that deals with heap sizes, which would require special
// casing all heap size related code to treat 0 specially.
{{{ Math.min(MAXIMUM_MEMORY, FOUR_GB - WASM_PAGE_SIZE) }}},
#endif
#else // no growth
HEAPU8.length,
#endif
#if ABORTING_MALLOC
$abortOnCannotGrowMemory: (requestedSize) => {
#if ASSERTIONS
#if ALLOW_MEMORY_GROWTH
abort(`Cannot enlarge memory arrays to size ${requestedSize} bytes (OOM). If you want malloc to return NULL (0) instead of this abort, do not link with -sABORTING_MALLOC (that is, the default when growth is enabled is to not abort, but you have overridden that)`);
#else // ALLOW_MEMORY_GROWTH
abort(`Cannot enlarge memory arrays to size ${requestedSize} bytes (OOM). Either (1) compile with -sINITIAL_MEMORY=X with X higher than the current value ${HEAP8.length}, (2) compile with -sALLOW_MEMORY_GROWTH which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -sABORTING_MALLOC=0`);
#endif // ALLOW_MEMORY_GROWTH
#else // ASSERTIONS
abort('OOM');
#endif // ASSERTIONS
},
#endif // ABORTING_MALLOC
#if TEST_MEMORY_GROWTH_FAILS
$growMemory: (size) => false,
#else
// Grows the wasm memory to the given byte size, and updates the JS views to
// it. Returns 1 on success, 0 on error.
$growMemory: (size) => {
var b = wasmMemory.buffer;
var pages = (size - b.byteLength + {{{ WASM_PAGE_SIZE - 1 }}}) / {{{ WASM_PAGE_SIZE }}};
#if RUNTIME_DEBUG
dbg(`growMemory: ${size} (+${size - b.byteLength} bytes / ${pages} pages)`);
#endif
#if MEMORYPROFILER
var oldHeapSize = b.byteLength;
#endif
try {
// round size grow request up to wasm page size (fixed 64KB per spec)
wasmMemory.grow(pages); // .grow() takes a delta compared to the previous size
updateMemoryViews();
#if MEMORYPROFILER
if (typeof emscriptenMemoryProfiler != 'undefined') {
emscriptenMemoryProfiler.onMemoryResize(oldHeapSize, b.byteLength);
}
#endif
return 1 /*success*/;
} catch(e) {
#if ASSERTIONS
err(`growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`);
#endif
}
// implicit 0 return to save code size (caller will cast "undefined" into 0
// anyhow)
},
#endif // ~TEST_MEMORY_GROWTH_FAILS
emscripten_resize_heap__deps: [
'$getHeapMax',
#if ASSERTIONS == 2
'emscripten_get_now',
#endif
#if ABORTING_MALLOC
'$abortOnCannotGrowMemory',
#endif
#if ALLOW_MEMORY_GROWTH
'$growMemory',
#endif
],
emscripten_resize_heap: 'ip',
emscripten_resize_heap: (requestedSize) => {
var oldSize = HEAPU8.length;
#if !MEMORY64 && !CAN_ADDRESS_2GB
// With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
requestedSize >>>= 0;
#endif
#if ALLOW_MEMORY_GROWTH == 0
#if ABORTING_MALLOC
abortOnCannotGrowMemory(requestedSize);
#else
return false; // malloc will report failure
#endif // ABORTING_MALLOC
#else // ALLOW_MEMORY_GROWTH == 0
// With multithreaded builds, races can happen (another thread might increase the size
// in between), so return a failure, and let the caller retry.
#if SHARED_MEMORY
if (requestedSize <= oldSize) {
return false;
}
#elif ASSERTIONS
assert(requestedSize > oldSize);
#endif
#if EMSCRIPTEN_TRACING
// Report old layout one last time
_emscripten_trace_report_memory_layout();
#endif
// Memory resize rules:
// 1. Always increase heap size to at least the requested size, rounded up
// to next page multiple.
// 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap
// geometrically: increase the heap size according to
// MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most
// overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).
// 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap
// linearly: increase the heap size by at least
// MEMORY_GROWTH_LINEAR_STEP bytes.
// 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by
// MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest
// 4. If we were unable to allocate as much memory, it may be due to
// over-eager decision to excessively reserve due to (3) above.
// Hence if an allocation fails, cut down on the amount of excess
// growth, in an attempt to succeed to perform a smaller allocation.
// A limit is set for how much we can grow. We should not exceed that
// (the wasm binary specifies it, so if we tried, we'd fail anyhow).
var maxHeapSize = getHeapMax();
if (requestedSize > maxHeapSize) {
#if ASSERTIONS
err(`Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`);
#endif
#if ABORTING_MALLOC
abortOnCannotGrowMemory(requestedSize);
#else
return false;
#endif
}
var alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple;
// Loop through potential heap size increases. If we attempt a too eager
// reservation that fails, cut down on the attempted size and reserve a
// smaller bump instead. (max 3 times, chosen somewhat arbitrarily)
for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
#if MEMORY_GROWTH_LINEAR_STEP == -1
var overGrownHeapSize = oldSize * (1 + {{{ MEMORY_GROWTH_GEOMETRIC_STEP }}} / cutDown); // ensure geometric growth
#if MEMORY_GROWTH_GEOMETRIC_CAP
// but limit overreserving (default to capping at +96MB overgrowth at most)
overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + {{{ MEMORY_GROWTH_GEOMETRIC_CAP }}} );
#endif
#else
var overGrownHeapSize = oldSize + {{{ MEMORY_GROWTH_LINEAR_STEP }}} / cutDown; // ensure linear growth
#endif
var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), {{{ WASM_PAGE_SIZE }}}));
#if ASSERTIONS == 2
var t0 = _emscripten_get_now();
#endif
var replacement = growMemory(newSize);
#if ASSERTIONS == 2
var t1 = _emscripten_get_now();
dbg(`Heap resize call from ${oldSize} to ${newSize} took ${(t1 - t0)} msecs. Success: ${!!replacement}`);
#endif
if (replacement) {
#if ASSERTIONS && WASM2JS
err('Warning: Enlarging memory arrays, this is not fast! ' + [oldSize, newSize]);
#endif
#if EMSCRIPTEN_TRACING
traceLogMessage("Emscripten", `Enlarging memory arrays from ${oldSize} to ${newSize}`);
// And now report the new layout
_emscripten_trace_report_memory_layout();
#endif
return true;
}
}
#if ASSERTIONS
err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`);
#endif
#if ABORTING_MALLOC
abortOnCannotGrowMemory(requestedSize);
#else
return false;
#endif
#endif // ALLOW_MEMORY_GROWTH
},
// Called after wasm grows memory. At that time we need to update the views.
// Without this notification, we'd need to check the buffer in JS every time
// we return from any wasm, which adds overhead. See
// https://github.com/WebAssembly/WASI/issues/82
emscripten_notify_memory_growth: (memoryIndex) => {
#if ASSERTIONS
assert(memoryIndex == 0);
#endif
updateMemoryViews();
},
_emscripten_system: (command) => {
#if ENVIRONMENT_MAY_BE_NODE
if (ENVIRONMENT_IS_NODE) {
if (!command) return 1; // shell is available
var cmdstr = UTF8ToString(command);
if (!cmdstr.length) return 0; // this is what glibc seems to do (shell works test?)
var cp = require('child_process');
var ret = cp.spawnSync(cmdstr, [], {shell:true, stdio:'inherit'});
var _W_EXITCODE = (ret, sig) => ((ret) << 8 | (sig));
// this really only can happen if process is killed by signal
if (ret.status === null) {
// sadly node doesn't expose such function
var signalToNumber = (sig) => {
// implement only the most common ones, and fallback to SIGINT
switch (sig) {
case 'SIGHUP': return 1;
case 'SIGINT': return 2;
case 'SIGQUIT': return 3;
case 'SIGFPE': return 8;
case 'SIGKILL': return 9;
case 'SIGALRM': return 14;
case 'SIGTERM': return 15;
}
return 2; // SIGINT
}
return _W_EXITCODE(0, signalToNumber(ret.signal));
}
return _W_EXITCODE(ret.status, 0);
}
#endif // ENVIRONMENT_MAY_BE_NODE
// int system(const char *command);
// http://pubs.opengroup.org/onlinepubs/000095399/functions/system.html
// Can't call external programs.
if (!command) return 0; // no shell available
return -{{{ cDefs.ENOSYS }}};
},
// ==========================================================================
// stdlib.h
// ==========================================================================
#if !STANDALONE_WASM
// TODO: There are currently two abort() functions that get imported to asm
// module scope: the built-in runtime function abort(), and this library
// function _abort(). Remove one of these, importing two functions for the
// same purpose is wasteful.
abort: () => {
#if ASSERTIONS
abort('native code called abort()');
#else
abort('');
#endif
},
#endif
// This object can be modified by the user during startup, which affects
// the initial values of the environment accessible by getenv.
$ENV: {},
// In -Oz builds, we replace memcpy() altogether with a non-unrolled wasm
// variant, so we should never emit emscripten_memcpy_js() in the build.
// In STANDALONE_WASM we avoid the emscripten_memcpy_js dependency so keep
// the wasm file standalone.
// In BULK_MEMORY mode we include native versions of these functions based
// on memory.fill and memory.copy.
// In MAIN_MODULE=1 or EMCC_FORCE_STDLIBS mode all of libc is force included
// so we cannot override parts of it, and therefore cannot use libc_optz.
#if (SHRINK_LEVEL < 2 || LINKABLE || process.env.EMCC_FORCE_STDLIBS) && !STANDALONE_WASM && !BULK_MEMORY
#if MIN_CHROME_VERSION < 45 || MIN_FIREFOX_VERSION < 34 || MIN_SAFARI_VERSION < 100101
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/copyWithin lists browsers that support TypedArray.prototype.copyWithin, but it
// has outdated information for Safari, saying it would not support it.
// https://github.com/WebKit/webkit/commit/24a800eea4d82d6d595cdfec69d0f68e733b5c52#diff-c484911d8df319ba75fce0d8e7296333R1 suggests support was added on Aug 28, 2015.
// Manual testing suggests:
// Safari/601.1 Version/9.0 on iPhone 4s with iOS 9.3.6 (released September 30, 2015) does not support copyWithin.
// but the following systems do:
// AppleWebKit/602.2.14 Safari/602.1 Version/10.0 Mobile/14B100 iPhone OS 10_1_1 on iPhone 5s with iOS 10.1.1 (released October 31, 2016)
// AppleWebKit/603.3.8 Safari/602.1 Version/10.0 on iPhone 5 with iOS 10.3.4 (released July 22, 2019)
// AppleWebKit/605.1.15 iPhone OS 12_3_1 Version/12.1.1 Safari/604.1 on iPhone SE with iOS 12.3.1
// AppleWebKit/605.1.15 Safari/604.1 Version/13.0.4 iPhone OS 13_3 on iPhone 6s with iOS 13.3
// AppleWebKit/605.1.15 Version/13.0.3 Intel Mac OS X 10_15_1 on Safari 13.0.3 (15608.3.10.1.4) on macOS Catalina 10.15.1
// Hence the support status of .copyWithin() for Safari version range [10.0.0, 10.1.0] is unknown.
emscripten_memcpy_js: `= Uint8Array.prototype.copyWithin
? (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num)
: (dest, src, num) => HEAPU8.set(HEAPU8.subarray(src, src+num), dest)`,
#else
emscripten_memcpy_js: (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num),
#endif
#endif
// ==========================================================================
// assert.h
// ==========================================================================
#if !STANDALONE_WASM
__assert_fail: (condition, filename, line, func) => {
abort(`Assertion failed: ${UTF8ToString(condition)}, at: ` + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
},
#endif
// ==========================================================================
// time.h
// ==========================================================================
_mktime_js__i53abi: true,
_mktime_js__deps: ['$ydayFromDate'],
_mktime_js: (tmPtr) => {
var date = new Date({{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_year, 'i32') }}} + 1900,
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_min, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'i32') }}},
0);
// There's an ambiguous hour when the time goes back; the tm_isdst field is
// used to disambiguate it. Date() basically guesses, so we fix it up if it
// guessed wrong, or fill in tm_isdst with the guess if it's -1.
var dst = {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_isdst, 'i32') }}};
var guessedOffset = date.getTimezoneOffset();
var start = new Date(date.getFullYear(), 0, 1);
var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
var winterOffset = start.getTimezoneOffset();
var dstOffset = Math.min(winterOffset, summerOffset); // DST is in December in South
if (dst < 0) {
// Attention: some regions don't have DST at all.
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_isdst, 'Number(summerOffset != winterOffset && dstOffset == guessedOffset)', 'i32') }}};
} else if ((dst > 0) != (dstOffset == guessedOffset)) {
var nonDstOffset = Math.max(winterOffset, summerOffset);
var trueOffset = dst > 0 ? dstOffset : nonDstOffset;
// Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.
date.setTime(date.getTime() + (trueOffset - guessedOffset)*60000);
}
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getDay()', 'i32') }}};
var yday = ydayFromDate(date)|0;
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}};
// To match expected behavior, update fields from date
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'date.getSeconds()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_min, 'date.getMinutes()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'date.getHours()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'date.getDate()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'date.getMonth()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_year, 'date.getYear()', 'i32') }}};
var timeMs = date.getTime();
if (isNaN(timeMs)) {
return -1;
}
// Return time in microseconds
return timeMs / 1000;
},
_gmtime_js__i53abi: true,
_gmtime_js: (time, tmPtr) => {
var date = new Date(time * 1000);
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'date.getUTCSeconds()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_min, 'date.getUTCMinutes()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'date.getUTCHours()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'date.getUTCDate()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'date.getUTCMonth()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_year, 'date.getUTCFullYear()-1900', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getUTCDay()', 'i32') }}};
var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0;
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}};
},
_timegm_js__i53abi: true,
_timegm_js: (tmPtr) => {
var time = Date.UTC({{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_year, 'i32') }}} + 1900,
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_min, 'i32') }}},
{{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'i32') }}},
0);
var date = new Date(time);
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getUTCDay()', 'i32') }}};
var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
var yday = ((date.getTime() - start) / (1000 * 60 * 60 * 24))|0;
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}};
return date.getTime() / 1000;
},
_localtime_js__i53abi: true,
_localtime_js__deps: ['$ydayFromDate'],
_localtime_js: (time, tmPtr) => {
var date = new Date(time*1000);
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'date.getSeconds()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_min, 'date.getMinutes()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'date.getHours()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'date.getDate()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'date.getMonth()', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_year, 'date.getFullYear()-1900', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'date.getDay()', 'i32') }}};
var yday = ydayFromDate(date)|0;
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_yday, 'yday', 'i32') }}};
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_gmtoff, '-(date.getTimezoneOffset() * 60)', LONG_TYPE) }}};
// Attention: DST is in December in South, and some regions don't have DST at all.
var start = new Date(date.getFullYear(), 0, 1);
var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
var winterOffset = start.getTimezoneOffset();
var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0;
{{{ makeSetValue('tmPtr', C_STRUCTS.tm.tm_isdst, 'dst', 'i32') }}};
},
// musl-internal function used to implement both `asctime` and `asctime_r`
__asctime_r: (tmPtr, buf) => {
var date = {
tm_sec: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_sec, 'i32') }}},
tm_min: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_min, 'i32') }}},
tm_hour: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_hour, 'i32') }}},
tm_mday: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mday, 'i32') }}},
tm_mon: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_mon, 'i32') }}},
tm_year: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_year, 'i32') }}},
tm_wday: {{{ makeGetValue('tmPtr', C_STRUCTS.tm.tm_wday, 'i32') }}}
};
var days = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ];
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var s = days[date.tm_wday] + ' ' + months[date.tm_mon] +
(date.tm_mday < 10 ? ' ' : ' ') + date.tm_mday +
(date.tm_hour < 10 ? ' 0' : ' ') + date.tm_hour +
(date.tm_min < 10 ? ':0' : ':') + date.tm_min +
(date.tm_sec < 10 ? ':0' : ':') + date.tm_sec +
' ' + (1900 + date.tm_year) + "\n";
// asctime_r is specced to behave in an undefined manner if the algorithm would attempt
// to write out more than 26 bytes (including the null terminator).
// See http://pubs.opengroup.org/onlinepubs/9699919799/functions/asctime.html
// Our undefined behavior is to truncate the write to at most 26 bytes, including null terminator.
stringToUTF8(s, buf, 26);
return buf;
},
#if STACK_OVERFLOW_CHECK >= 2
// Set stack limits used by binaryen's `StackCheck` pass.
#if MAIN_MODULE
$setStackLimits__deps: ['$setDylinkStackLimits'],
#endif
$setStackLimits: () => {
var stackLow = _emscripten_stack_get_base();
var stackHigh = _emscripten_stack_get_end();
#if RUNTIME_DEBUG
dbg(`setStackLimits: ${ptrToString(stackLow)}, ${ptrToString(stackHigh)}`);
#endif
#if MAIN_MODULE
// With dynamic linking we could have any number of pre-loaded libraries
// that each need to have their stack limits set.
setDylinkStackLimits(stackLow, stackHigh);
#else
___set_stack_limits(stackLow, stackHigh);
#endif
},
#endif
$withStackSave__internal: true,
$withStackSave__deps: ['stackSave', 'stackRestore'],
$withStackSave: (f) => {
var stack = stackSave();
var ret = f();
stackRestore(stack);
return ret;
},
_tzset_js__deps: ['$stringToUTF8'],
_tzset_js__internal: true,
_tzset_js: (timezone, daylight, std_name, dst_name) => {
// TODO: Use (malleable) environment variables instead of system settings.
var currentYear = new Date().getFullYear();
var winter = new Date(currentYear, 0, 1);
var summer = new Date(currentYear, 6, 1);
var winterOffset = winter.getTimezoneOffset();
var summerOffset = summer.getTimezoneOffset();
// Local standard timezone offset. Local standard time is not adjusted for
// daylight savings. This code uses the fact that getTimezoneOffset returns
// a greater value during Standard Time versus Daylight Saving Time (DST).
// Thus it determines the expected output during Standard Time, and it
// compares whether the output of the given date the same (Standard) or less
// (DST).
var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
// timezone is specified as seconds west of UTC ("The external variable
// `timezone` shall be set to the difference, in seconds, between
// Coordinated Universal Time (UTC) and local standard time."), the same
// as returned by stdTimezoneOffset.
// See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html
{{{ makeSetValue('timezone', '0', 'stdTimezoneOffset * 60', POINTER_TYPE) }}};
{{{ makeSetValue('daylight', '0', 'Number(winterOffset != summerOffset)', 'i32') }}};
function extractZone(date) {
var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/);
return match ? match[1] : "GMT";
};
var winterName = extractZone(winter);
var summerName = extractZone(summer);
if (summerOffset < winterOffset) {
// Northern hemisphere
stringToUTF8(winterName, std_name, {{{ cDefs.TZNAME_MAX + 1 }}});
stringToUTF8(summerName, dst_name, {{{ cDefs.TZNAME_MAX + 1 }}});
} else {
stringToUTF8(winterName, dst_name, {{{ cDefs.TZNAME_MAX + 1 }}});
stringToUTF8(summerName, std_name, {{{ cDefs.TZNAME_MAX + 1 }}});
}
},
$MONTH_DAYS_REGULAR: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
$MONTH_DAYS_LEAP: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
$MONTH_DAYS_REGULAR_CUMULATIVE: [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
$MONTH_DAYS_LEAP_CUMULATIVE: [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335],
$isLeapYear: (year) => year%4 === 0 && (year%100 !== 0 || year%400 === 0),
$ydayFromDate__deps: ['$isLeapYear', '$MONTH_DAYS_LEAP_CUMULATIVE', '$MONTH_DAYS_REGULAR_CUMULATIVE'],
$ydayFromDate: (date) => {
var leap = isLeapYear(date.getFullYear());
var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);
var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1; // -1 since it's days since Jan 1
return yday;
},
$arraySum: (array, index) => {
var sum = 0;
for (var i = 0; i <= index; sum += array[i++]) {
// no-op
}
return sum;
},
$addDays__deps: ['$isLeapYear', '$MONTH_DAYS_LEAP', '$MONTH_DAYS_REGULAR'],
$addDays: (date, days) => {
var newDate = new Date(date.getTime());
while (days > 0) {
var leap = isLeapYear(newDate.getFullYear());
var currentMonth = newDate.getMonth();
var daysInCurrentMonth = (leap ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR)[currentMonth];
if (days > daysInCurrentMonth-newDate.getDate()) {
// we spill over to next month
days -= (daysInCurrentMonth-newDate.getDate()+1);
newDate.setDate(1);
if (currentMonth < 11) {
newDate.setMonth(currentMonth+1)
} else {
newDate.setMonth(0);
newDate.setFullYear(newDate.getFullYear()+1);
}
} else {
// we stay in current month
newDate.setDate(newDate.getDate()+days);
return newDate;
}
}
return newDate;
},
// Note: this is not used in STANDALONE_WASM mode, because it is more
// compact to do it in JS.
strftime__deps: ['$isLeapYear', '$arraySum', '$addDays', '$MONTH_DAYS_REGULAR', '$MONTH_DAYS_LEAP',
'$intArrayFromString', '$writeArrayToMemory'
],
strftime: (s, maxsize, format, tm) => {
// size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timeptr);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html
var tm_zone = {{{ makeGetValue('tm', C_STRUCTS.tm.tm_zone, '*') }}};
var date = {
tm_sec: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_sec, 'i32') }}},
tm_min: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_min, 'i32') }}},
tm_hour: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_hour, 'i32') }}},
tm_mday: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_mday, 'i32') }}},
tm_mon: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_mon, 'i32') }}},
tm_year: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_year, 'i32') }}},
tm_wday: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_wday, 'i32') }}},
tm_yday: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_yday, 'i32') }}},
tm_isdst: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_isdst, 'i32') }}},
tm_gmtoff: {{{ makeGetValue('tm', C_STRUCTS.tm.tm_gmtoff, LONG_TYPE) }}},
tm_zone: tm_zone ? UTF8ToString(tm_zone) : ''
};
{{{ from64('date.tm_gmtoff') }}}
var pattern = UTF8ToString(format);
// expand format
var EXPANSION_RULES_1 = {
'%c': '%a %b %d %H:%M:%S %Y', // Replaced by the locale's appropriate date and time representation - e.g., Mon Aug 3 14:02:01 2013
'%D': '%m/%d/%y', // Equivalent to %m / %d / %y
'%F': '%Y-%m-%d', // Equivalent to %Y - %m - %d
'%h': '%b', // Equivalent to %b
'%r': '%I:%M:%S %p', // Replaced by the time in a.m. and p.m. notation
'%R': '%H:%M', // Replaced by the time in 24-hour notation
'%T': '%H:%M:%S', // Replaced by the time
'%x': '%m/%d/%y', // Replaced by the locale's appropriate date representation
'%X': '%H:%M:%S', // Replaced by the locale's appropriate time representation
// Modified Conversion Specifiers
'%Ec': '%c', // Replaced by the locale's alternative appropriate date and time representation.
'%EC': '%C', // Replaced by the name of the base year (period) in the locale's alternative representation.
'%Ex': '%m/%d/%y', // Replaced by the locale's alternative date representation.
'%EX': '%H:%M:%S', // Replaced by the locale's alternative time representation.
'%Ey': '%y', // Replaced by the offset from %EC (year only) in the locale's alternative representation.
'%EY': '%Y', // Replaced by the full alternative year representation.
'%Od': '%d', // Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading zeros if there is any alternative symbol for zero; otherwise, with leading <space> characters.
'%Oe': '%e', // Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading <space> characters.
'%OH': '%H', // Replaced by the hour (24-hour clock) using the locale's alternative numeric symbols.
'%OI': '%I', // Replaced by the hour (12-hour clock) using the locale's alternative numeric symbols.
'%Om': '%m', // Replaced by the month using the locale's alternative numeric symbols.
'%OM': '%M', // Replaced by the minutes using the locale's alternative numeric symbols.
'%OS': '%S', // Replaced by the seconds using the locale's alternative numeric symbols.
'%Ou': '%u', // Replaced by the weekday as a number in the locale's alternative representation (Monday=1).
'%OU': '%U', // Replaced by the week number of the year (Sunday as the first day of the week, rules corresponding to %U ) using the locale's alternative numeric symbols.
'%OV': '%V', // Replaced by the week number of the year (Monday as the first day of the week, rules corresponding to %V ) using the locale's alternative numeric symbols.
'%Ow': '%w', // Replaced by the number of the weekday (Sunday=0) using the locale's alternative numeric symbols.
'%OW': '%W', // Replaced by the week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols.
'%Oy': '%y', // Replaced by the year (offset from %C ) using the locale's alternative numeric symbols.
};
for (var rule in EXPANSION_RULES_1) {
pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_1[rule]);
}
var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
function leadingSomething(value, digits, character) {
var str = typeof value == 'number' ? value.toString() : (value || '');
while (str.length < digits) {
str = character[0]+str;
}
return str;
}
function leadingNulls(value, digits) {
return leadingSomething(value, digits, '0');
}
function compareByDay(date1, date2) {
function sgn(value) {
return value < 0 ? -1 : (value > 0 ? 1 : 0);
}
var compare;
if ((compare = sgn(date1.getFullYear()-date2.getFullYear())) === 0) {
if ((compare = sgn(date1.getMonth()-date2.getMonth())) === 0) {
compare = sgn(date1.getDate()-date2.getDate());
}
}
return compare;
}
function getFirstWeekStartDate(janFourth) {
switch (janFourth.getDay()) {
case 0: // Sunday
return new Date(janFourth.getFullYear()-1, 11, 29);
case 1: // Monday
return janFourth;
case 2: // Tuesday
return new Date(janFourth.getFullYear(), 0, 3);
case 3: // Wednesday
return new Date(janFourth.getFullYear(), 0, 2);
case 4: // Thursday
return new Date(janFourth.getFullYear(), 0, 1);
case 5: // Friday
return new Date(janFourth.getFullYear()-1, 11, 31);
case 6: // Saturday
return new Date(janFourth.getFullYear()-1, 11, 30);
}
}
function getWeekBasedYear(date) {
var thisDate = addDays(new Date(date.tm_year+1900, 0, 1), date.tm_yday);
var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4);
var janFourthNextYear = new Date(thisDate.getFullYear()+1, 0, 4);
var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear);
var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear);
if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) {
// this date is after the start of the first week of this year
if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) {
return thisDate.getFullYear()+1;
}
return thisDate.getFullYear();
}
return thisDate.getFullYear()-1;
}
var EXPANSION_RULES_2 = {
'%a': (date) => WEEKDAYS[date.tm_wday].substring(0,3) ,
'%A': (date) => WEEKDAYS[date.tm_wday],
'%b': (date) => MONTHS[date.tm_mon].substring(0,3),
'%B': (date) => MONTHS[date.tm_mon],
'%C': (date) => {
var year = date.tm_year+1900;
return leadingNulls((year/100)|0,2);
},
'%d': (date) => leadingNulls(date.tm_mday, 2),
'%e': (date) => leadingSomething(date.tm_mday, 2, ' '),
'%g': (date) => {
// %g, %G, and %V give values according to the ISO 8601:2000 standard week-based year.
// In this system, weeks begin on a Monday and week 1 of the year is the week that includes
// January 4th, which is also the week that includes the first Thursday of the year, and
// is also the first week that contains at least four days in the year.
// If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of
// the last week of the preceding year; thus, for Saturday 2nd January 1999,
// %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th,
// or 31st is a Monday, it and any following days are part of week 1 of the following year.
// Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01.
return getWeekBasedYear(date).toString().substring(2);
},
'%G': getWeekBasedYear,
'%H': (date) => leadingNulls(date.tm_hour, 2),
'%I': (date) => {
var twelveHour = date.tm_hour;
if (twelveHour == 0) twelveHour = 12;
else if (twelveHour > 12) twelveHour -= 12;
return leadingNulls(twelveHour, 2);
},
'%j': (date) => {
// Day of the year (001-366)
return leadingNulls(date.tm_mday + arraySum(isLeapYear(date.tm_year+1900) ? MONTH_DAYS_LEAP : MONTH_DAYS_REGULAR, date.tm_mon-1), 3);
},
'%m': (date) => leadingNulls(date.tm_mon+1, 2),
'%M': (date) => leadingNulls(date.tm_min, 2),
'%n': () => '\n',
'%p': (date) => {
if (date.tm_hour >= 0 && date.tm_hour < 12) {
return 'AM';
}
return 'PM';
},
'%S': (date) => leadingNulls(date.tm_sec, 2),
'%t': () => '\t',
'%u': (date) => date.tm_wday || 7,
'%U': (date) => {
var days = date.tm_yday + 7 - date.tm_wday;
return leadingNulls(Math.floor(days / 7), 2);
},
'%V': (date) => {
// Replaced by the week number of the year (Monday as the first day of the week)
// as a decimal number [01,53]. If the week containing 1 January has four
// or more days in the new year, then it is considered week 1.
// Otherwise, it is the last week of the previous year, and the next week is week 1.
// Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday]
var val = Math.floor((date.tm_yday + 7 - (date.tm_wday + 6) % 7 ) / 7);
// If 1 Jan is just 1-3 days past Monday, the previous week
// is also in this year.
if ((date.tm_wday + 371 - date.tm_yday - 2) % 7 <= 2) {
val++;
}
if (!val) {
val = 52;
// If 31 December of prev year a Thursday, or Friday of a
// leap year, then the prev year has 53 weeks.
var dec31 = (date.tm_wday + 7 - date.tm_yday - 1) % 7;
if (dec31 == 4 || (dec31 == 5 && isLeapYear(date.tm_year%400-1))) {
val++;
}
} else if (val == 53) {
// If 1 January is not a Thursday, and not a Wednesday of a
// leap year, then this year has only 52 weeks.
var jan1 = (date.tm_wday + 371 - date.tm_yday) % 7;
if (jan1 != 4 && (jan1 != 3 || !isLeapYear(date.tm_year)))
val = 1;
}
return leadingNulls(val, 2);
},
'%w': (date) => date.tm_wday,
'%W': (date) => {
var days = date.tm_yday + 7 - ((date.tm_wday + 6) % 7);
return leadingNulls(Math.floor(days / 7), 2);
},
'%y': (date) => {
// Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year]
return (date.tm_year+1900).toString().substring(2);
},
// Replaced by the year as a decimal number (for example, 1997). [ tm_year]
'%Y': (date) => date.tm_year+1900,
'%z': (date) => {
// Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ).
// For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich).
var off = date.tm_gmtoff;
var ahead = off >= 0;
off = Math.abs(off) / 60;
// convert from minutes into hhmm format (which means 60 minutes = 100 units)
off = (off / 60)*100 + (off % 60);
return (ahead ? '+' : '-') + String("0000" + off).slice(-4);
},
'%Z': (date) => date.tm_zone,
'%%': () => '%'
};
// Replace %% with a pair of NULLs (which cannot occur in a C string), then
// re-inject them after processing.
pattern = pattern.replace(/%%/g, '\0\0')
for (var rule in EXPANSION_RULES_2) {
if (pattern.includes(rule)) {
pattern = pattern.replace(new RegExp(rule, 'g'), EXPANSION_RULES_2[rule](date));
}
}
pattern = pattern.replace(/\0\0/g, '%')
var bytes = intArrayFromString(pattern, false);
if (bytes.length > maxsize) {
return 0;
}
writeArrayToMemory(bytes, s);
return bytes.length-1;
},
strftime_l__deps: ['strftime'],
strftime_l: (s, maxsize, format, tm, loc) => {
return _strftime(s, maxsize, format, tm); // no locale support yet
},
strptime__deps: ['$isLeapYear', '$arraySum', '$addDays', '$MONTH_DAYS_REGULAR', '$MONTH_DAYS_LEAP',
'$jstoi_q', '$intArrayFromString' ],
strptime: (buf, format, tm) => {
// char *strptime(const char *restrict buf, const char *restrict format, struct tm *restrict tm);
// http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html
var pattern = UTF8ToString(format);
// escape special characters
// TODO: not sure we really need to escape all of these in JS regexps
var SPECIAL_CHARS = '\\!@#$^&*()+=-[]/{}|:<>?,.';
for (var i=0, ii=SPECIAL_CHARS.length; i<ii; ++i) {
pattern = pattern.replace(new RegExp('\\'+SPECIAL_CHARS[i], 'g'), '\\'+SPECIAL_CHARS[i]);
}
// reduce number of matchers
var EQUIVALENT_MATCHERS = {
'A': '%a',
'B': '%b',
'c': '%a %b %d %H:%M:%S %Y',
'D': '%m\\/%d\\/%y',
'e': '%d',
'F': '%Y-%m-%d',
'h': '%b',
'R': '%H\\:%M',
'r': '%I\\:%M\\:%S\\s%p',
'T': '%H\\:%M\\:%S',
'x': '%m\\/%d\\/(?:%y|%Y)',
'X': '%H\\:%M\\:%S'
};
// TODO: take care of locale
var DATE_PATTERNS = {
/* weekday name */ 'a': '(?:Sun(?:day)?)|(?:Mon(?:day)?)|(?:Tue(?:sday)?)|(?:Wed(?:nesday)?)|(?:Thu(?:rsday)?)|(?:Fri(?:day)?)|(?:Sat(?:urday)?)',
/* month name */ 'b': '(?:Jan(?:uary)?)|(?:Feb(?:ruary)?)|(?:Mar(?:ch)?)|(?:Apr(?:il)?)|May|(?:Jun(?:e)?)|(?:Jul(?:y)?)|(?:Aug(?:ust)?)|(?:Sep(?:tember)?)|(?:Oct(?:ober)?)|(?:Nov(?:ember)?)|(?:Dec(?:ember)?)',
/* century */ 'C': '\\d\\d',
/* day of month */ 'd': '0[1-9]|[1-9](?!\\d)|1\\d|2\\d|30|31',
/* hour (24hr) */ 'H': '\\d(?!\\d)|[0,1]\\d|20|21|22|23',
/* hour (12hr) */ 'I': '\\d(?!\\d)|0\\d|10|11|12',
/* day of year */ 'j': '00[1-9]|0?[1-9](?!\\d)|0?[1-9]\\d(?!\\d)|[1,2]\\d\\d|3[0-6]\\d',