rusty_spine 0.5.0

Spine runtime for Rust (and wasm!) transpiled from the official C Runtime.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// Many functions in this file were copied from libc with the following license:

/*-
 * Copyright (c) 1990 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Chris Torek.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

use crate::c::FILE;
use std::any::Any;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::sync::{Arc, Mutex, Once};

pub mod types {
    #[allow(non_camel_case_types)]
    pub type c_short = i16;
    #[allow(non_camel_case_types)]
    pub type c_ushort = u16;
    #[allow(non_camel_case_types)]
    pub type c_int = i32;
    #[allow(non_camel_case_types)]
    pub type c_uint = u32;
    #[allow(non_camel_case_types)]
    pub type c_long = i64;
    #[allow(non_camel_case_types)]
    pub type c_ulong = u64;
    #[allow(non_camel_case_types)]
    pub type c_schar = i8;
    #[allow(non_camel_case_types)]
    pub type c_char = i8;
    #[allow(non_camel_case_types)]
    pub type c_uchar = u8;
    #[allow(non_camel_case_types)]
    pub type c_float = f32;
    #[allow(non_camel_case_types)]
    pub type c_double = f64;

    #[allow(non_camel_case_types)]
    #[repr(u8)]
    pub enum c_void {
        __variant1,
        __variant2,
    }
}
use self::types::*;

#[allow(non_camel_case_types)]
type size_t = c_ulong;

#[derive(Default)]
struct Allocator {
    allocations: HashMap<*const c_void, Vec<u8>>,
}

impl Allocator {
    fn singleton() -> Arc<Mutex<Allocator>> {
        static START: Once = Once::new();
        static mut INSTANCE: Option<Arc<Mutex<Allocator>>> = None;
        START.call_once(|| unsafe {
            INSTANCE = Some(Arc::new(Mutex::new(Allocator::default())));
        });
        unsafe {
            let singleton = INSTANCE.as_ref().unwrap();
            singleton.clone()
        }
    }

    pub fn malloc(&mut self, size: usize) -> *mut c_void {
        let mut data: Vec<u8> = vec![];
        data.resize(size, 0);
        let ptr = data.as_ptr();
        self.allocations.insert(ptr as *const c_void, data);
        ptr as *mut c_void
    }

    pub unsafe fn realloc(&mut self, ptr: *const c_void, size: usize) -> *mut c_void {
        let mut previous_allocation = self.allocations.remove(&ptr).unwrap();
        previous_allocation.resize(size, 0);
        let new_ptr = previous_allocation.as_ptr();
        self.allocations
            .insert(new_ptr as *const c_void, previous_allocation);
        new_ptr as *mut c_void
    }

    #[allow(dead_code)]
    pub unsafe fn size(&mut self, ptr: *const c_void) -> usize {
        self.allocations.get(&ptr).unwrap().len()
    }

    pub unsafe fn free(&mut self, ptr: *const c_void) {
        self.allocations.remove(&ptr).unwrap();
    }

    #[allow(dead_code)]
    pub fn size_allocated(&self) -> usize {
        let mut size = 0;
        for (_, allocation) in self.allocations.iter() {
            size += allocation.len();
        }
        size
    }
}

#[no_mangle]
pub unsafe extern "C" fn spine_isspace(c: c_int) -> c_int {
    if c == '\t' as i32
        || c == '\n' as i32
        || c == '\u{b}' as i32
        || c == '\u{c}' as i32
        || c == '\r' as i32
        || c == ' ' as i32
    {
        1 as c_int
    } else {
        0 as c_int
    }
}

#[no_mangle]
pub unsafe extern "C" fn spine_isdigit(c: c_int) -> c_int {
    ((c as c_uint).wrapping_sub('0' as i32 as c_uint) < 10 as c_int as c_uint) as c_int
}

#[no_mangle]
pub unsafe extern "C" fn spine_isalpha(c: c_int) -> c_int {
    if c >= 'a' as i32 && c <= 'z' as i32 || c >= 'A' as i32 && c <= 'Z' as i32 {
        1 as c_int
    } else {
        0 as c_int
    }
}

#[no_mangle]
pub unsafe extern "C" fn spine_isupper(c: c_int) -> c_int {
    if c >= 'A' as i32 && c <= 'Z' as i32 {
        1 as c_int
    } else {
        0 as c_int
    }
}

#[no_mangle]
pub unsafe extern "C" fn spine_strlen(str: *const c_char) -> c_ulong {
    let mut s: *const c_char;
    s = str;
    while *s != 0 {
        s = s.offset(1);
    }
    s.offset_from(str) as c_long as c_ulong
}

#[no_mangle]
pub unsafe extern "C" fn spine_strcmp(mut s1: *const c_char, mut s2: *const c_char) -> c_int {
    loop {
        let fresh0 = s2;
        s2 = s2.offset(1);
        if *s1 as c_int != *fresh0 as c_int {
            break;
        }
        let fresh1 = s1;
        s1 = s1.offset(1);
        if *fresh1 as c_int == 0 as c_int {
            return 0 as c_int;
        }
    }
    s2 = s2.offset(-1);
    *(s1 as *mut c_uchar) as c_int - *(s2 as *mut c_uchar) as c_int
}

#[no_mangle]
pub unsafe extern "C" fn spine_strncmp(
    mut s1: *const c_char,
    mut s2: *const c_char,
    mut n: size_t,
) -> c_int {
    if n == 0 as c_int as c_ulong {
        return 0 as c_int;
    }
    loop {
        let fresh0 = s2;
        s2 = s2.offset(1);
        if *s1 as c_int != *fresh0 as c_int {
            s2 = s2.offset(-1);
            return *(s1 as *mut c_uchar) as c_int - *(s2 as *mut c_uchar) as c_int;
        }
        let fresh1 = s1;
        s1 = s1.offset(1);
        if *fresh1 as c_int == 0 as c_int {
            break;
        }
        n = n.wrapping_sub(1);
        if n == 0 as c_int as c_ulong {
            break;
        }
    }
    0 as c_int
}

static mut CHARMAP: [c_uchar; 256] = [
    '\0' as i32 as c_uchar,
    '\u{1}' as i32 as c_uchar,
    '\u{2}' as i32 as c_uchar,
    '\u{3}' as i32 as c_uchar,
    '\u{4}' as i32 as c_uchar,
    '\u{5}' as i32 as c_uchar,
    '\u{6}' as i32 as c_uchar,
    '\u{7}' as i32 as c_uchar,
    '\u{8}' as i32 as c_uchar,
    '\t' as i32 as c_uchar,
    '\n' as i32 as c_uchar,
    '\u{b}' as i32 as c_uchar,
    '\u{c}' as i32 as c_uchar,
    '\r' as i32 as c_uchar,
    '\u{e}' as i32 as c_uchar,
    '\u{f}' as i32 as c_uchar,
    '\u{10}' as i32 as c_uchar,
    '\u{11}' as i32 as c_uchar,
    '\u{12}' as i32 as c_uchar,
    '\u{13}' as i32 as c_uchar,
    '\u{14}' as i32 as c_uchar,
    '\u{15}' as i32 as c_uchar,
    '\u{16}' as i32 as c_uchar,
    '\u{17}' as i32 as c_uchar,
    '\u{18}' as i32 as c_uchar,
    '\u{19}' as i32 as c_uchar,
    '\u{1a}' as i32 as c_uchar,
    '\u{1b}' as i32 as c_uchar,
    '\u{1c}' as i32 as c_uchar,
    '\u{1d}' as i32 as c_uchar,
    '\u{1e}' as i32 as c_uchar,
    '\u{1f}' as i32 as c_uchar,
    ' ' as i32 as c_uchar,
    '!' as i32 as c_uchar,
    '"' as i32 as c_uchar,
    '#' as i32 as c_uchar,
    '$' as i32 as c_uchar,
    '%' as i32 as c_uchar,
    '&' as i32 as c_uchar,
    '\'' as i32 as c_uchar,
    '(' as i32 as c_uchar,
    ')' as i32 as c_uchar,
    '*' as i32 as c_uchar,
    '+' as i32 as c_uchar,
    ',' as i32 as c_uchar,
    '-' as i32 as c_uchar,
    '.' as i32 as c_uchar,
    '/' as i32 as c_uchar,
    '0' as i32 as c_uchar,
    '1' as i32 as c_uchar,
    '2' as i32 as c_uchar,
    '3' as i32 as c_uchar,
    '4' as i32 as c_uchar,
    '5' as i32 as c_uchar,
    '6' as i32 as c_uchar,
    '7' as i32 as c_uchar,
    '8' as i32 as c_uchar,
    '9' as i32 as c_uchar,
    ':' as i32 as c_uchar,
    ';' as i32 as c_uchar,
    '<' as i32 as c_uchar,
    '=' as i32 as c_uchar,
    '>' as i32 as c_uchar,
    '?' as i32 as c_uchar,
    '@' as i32 as c_uchar,
    'a' as i32 as c_uchar,
    'b' as i32 as c_uchar,
    'c' as i32 as c_uchar,
    'd' as i32 as c_uchar,
    'e' as i32 as c_uchar,
    'f' as i32 as c_uchar,
    'g' as i32 as c_uchar,
    'h' as i32 as c_uchar,
    'i' as i32 as c_uchar,
    'j' as i32 as c_uchar,
    'k' as i32 as c_uchar,
    'l' as i32 as c_uchar,
    'm' as i32 as c_uchar,
    'n' as i32 as c_uchar,
    'o' as i32 as c_uchar,
    'p' as i32 as c_uchar,
    'q' as i32 as c_uchar,
    'r' as i32 as c_uchar,
    's' as i32 as c_uchar,
    't' as i32 as c_uchar,
    'u' as i32 as c_uchar,
    'v' as i32 as c_uchar,
    'w' as i32 as c_uchar,
    'x' as i32 as c_uchar,
    'y' as i32 as c_uchar,
    'z' as i32 as c_uchar,
    '[' as i32 as c_uchar,
    '\\' as i32 as c_uchar,
    ']' as i32 as c_uchar,
    '^' as i32 as c_uchar,
    '_' as i32 as c_uchar,
    '`' as i32 as c_uchar,
    'a' as i32 as c_uchar,
    'b' as i32 as c_uchar,
    'c' as i32 as c_uchar,
    'd' as i32 as c_uchar,
    'e' as i32 as c_uchar,
    'f' as i32 as c_uchar,
    'g' as i32 as c_uchar,
    'h' as i32 as c_uchar,
    'i' as i32 as c_uchar,
    'j' as i32 as c_uchar,
    'k' as i32 as c_uchar,
    'l' as i32 as c_uchar,
    'm' as i32 as c_uchar,
    'n' as i32 as c_uchar,
    'o' as i32 as c_uchar,
    'p' as i32 as c_uchar,
    'q' as i32 as c_uchar,
    'r' as i32 as c_uchar,
    's' as i32 as c_uchar,
    't' as i32 as c_uchar,
    'u' as i32 as c_uchar,
    'v' as i32 as c_uchar,
    'w' as i32 as c_uchar,
    'x' as i32 as c_uchar,
    'y' as i32 as c_uchar,
    'z' as i32 as c_uchar,
    '{' as i32 as c_uchar,
    '|' as i32 as c_uchar,
    '}' as i32 as c_uchar,
    '~' as i32 as c_uchar,
    '\u{7f}' as i32 as c_uchar,
    -128i32 as c_uchar,
    -127i32 as c_uchar,
    -126i32 as c_uchar,
    -125i32 as c_uchar,
    -124i32 as c_uchar,
    -123i32 as c_uchar,
    -122i32 as c_uchar,
    -121i32 as c_uchar,
    -120i32 as c_uchar,
    -119i32 as c_uchar,
    -118i32 as c_uchar,
    -117i32 as c_uchar,
    -116i32 as c_uchar,
    -115i32 as c_uchar,
    -114i32 as c_uchar,
    -113i32 as c_uchar,
    -112i32 as c_uchar,
    -111i32 as c_uchar,
    -110i32 as c_uchar,
    -109i32 as c_uchar,
    -108i32 as c_uchar,
    -107i32 as c_uchar,
    -106i32 as c_uchar,
    -105i32 as c_uchar,
    -104i32 as c_uchar,
    -103i32 as c_uchar,
    -102i32 as c_uchar,
    -101i32 as c_uchar,
    -100i32 as c_uchar,
    -99i32 as c_uchar,
    -98i32 as c_uchar,
    -97i32 as c_uchar,
    -96i32 as c_uchar,
    -95i32 as c_uchar,
    -94i32 as c_uchar,
    -93i32 as c_uchar,
    -92i32 as c_uchar,
    -91i32 as c_uchar,
    -90i32 as c_uchar,
    -89i32 as c_uchar,
    -88i32 as c_uchar,
    -87i32 as c_uchar,
    -86i32 as c_uchar,
    -85i32 as c_uchar,
    -84i32 as c_uchar,
    -83i32 as c_uchar,
    -82i32 as c_uchar,
    -81i32 as c_uchar,
    -80i32 as c_uchar,
    -79i32 as c_uchar,
    -78i32 as c_uchar,
    -77i32 as c_uchar,
    -76i32 as c_uchar,
    -75i32 as c_uchar,
    -74i32 as c_uchar,
    -73i32 as c_uchar,
    -72i32 as c_uchar,
    -71i32 as c_uchar,
    -70i32 as c_uchar,
    -69i32 as c_uchar,
    -68i32 as c_uchar,
    -67i32 as c_uchar,
    -66i32 as c_uchar,
    -65i32 as c_uchar,
    -64i32 as c_uchar,
    -63i32 as c_uchar,
    -62i32 as c_uchar,
    -61i32 as c_uchar,
    -60i32 as c_uchar,
    -59i32 as c_uchar,
    -58i32 as c_uchar,
    -57i32 as c_uchar,
    -56i32 as c_uchar,
    -55i32 as c_uchar,
    -54i32 as c_uchar,
    -53i32 as c_uchar,
    -52i32 as c_uchar,
    -51i32 as c_uchar,
    -50i32 as c_uchar,
    -49i32 as c_uchar,
    -48i32 as c_uchar,
    -47i32 as c_uchar,
    -46i32 as c_uchar,
    -45i32 as c_uchar,
    -44i32 as c_uchar,
    -43i32 as c_uchar,
    -42i32 as c_uchar,
    -41i32 as c_uchar,
    -40i32 as c_uchar,
    -39i32 as c_uchar,
    -38i32 as c_uchar,
    -37i32 as c_uchar,
    -36i32 as c_uchar,
    -35i32 as c_uchar,
    -34i32 as c_uchar,
    -33i32 as c_uchar,
    -32i32 as c_uchar,
    -31i32 as c_uchar,
    -30i32 as c_uchar,
    -29i32 as c_uchar,
    -28i32 as c_uchar,
    -27i32 as c_uchar,
    -26i32 as c_uchar,
    -25i32 as c_uchar,
    -24i32 as c_uchar,
    -23i32 as c_uchar,
    -22i32 as c_uchar,
    -21i32 as c_uchar,
    -20i32 as c_uchar,
    -19i32 as c_uchar,
    -18i32 as c_uchar,
    -17i32 as c_uchar,
    -16i32 as c_uchar,
    -15i32 as c_uchar,
    -14i32 as c_uchar,
    -13i32 as c_uchar,
    -12i32 as c_uchar,
    -11i32 as c_uchar,
    -10i32 as c_uchar,
    -9i32 as c_uchar,
    -8i32 as c_uchar,
    -7i32 as c_uchar,
    -6i32 as c_uchar,
    -5i32 as c_uchar,
    -4i32 as c_uchar,
    -3i32 as c_uchar,
    -2i32 as c_uchar,
    -1i32 as c_uchar,
];
#[no_mangle]
pub unsafe extern "C" fn spine_strcasecmp(s1: *const c_char, s2: *const c_char) -> c_int {
    let cm: *const c_uchar = CHARMAP.as_ptr();
    let mut us1: *const c_uchar = s1 as *const c_uchar;
    let mut us2: *const c_uchar = s2 as *const c_uchar;
    loop {
        let fresh0 = us2;
        us2 = us2.offset(1);
        if *cm.offset(*us1 as isize) as c_int != *cm.offset(*fresh0 as isize) as c_int {
            break;
        }
        let fresh1 = us1;
        us1 = us1.offset(1);
        if *fresh1 as c_int == '\0' as i32 {
            return 0 as c_int;
        }
    }
    us2 = us2.offset(-1);
    *cm.offset(*us1 as isize) as c_int - *cm.offset(*us2 as isize) as c_int
}

#[no_mangle]
pub unsafe extern "C" fn spine_strcpy(mut to: *mut c_char, mut from: *const c_char) -> *mut c_char {
    let save: *mut c_char = to;
    loop {
        *to = *from;
        if *to as c_int == '\0' as i32 {
            break;
        }
        from = from.offset(1);
        to = to.offset(1);
    }
    save
}

#[no_mangle]
pub unsafe extern "C" fn spine_strncat(
    dst: *mut c_char,
    src: *const c_char,
    mut n: size_t,
) -> *mut c_char {
    if n != 0 as c_int as c_ulong {
        let mut d: *mut c_char = dst;
        let mut s: *const c_char = src;
        while *d as c_int != 0 as c_int {
            d = d.offset(1);
        }
        loop {
            let fresh0 = s;
            s = s.offset(1);
            *d = *fresh0;
            if *d as c_int == 0 as c_int {
                break;
            }
            d = d.offset(1);
            n = n.wrapping_sub(1);
            if n == 0 as c_int as c_ulong {
                break;
            }
        }
        *d = 0 as c_int as c_char;
    }
    dst
}

#[no_mangle]
pub unsafe extern "C" fn spine_strtol(
    nptr: *const c_char,
    endptr: *mut *mut c_char,
    mut base: c_int,
) -> c_long {
    let mut s: *const c_char;
    let mut acc: c_long;
    let mut cutoff: c_long;
    let mut c: c_int;
    let neg: c_int;
    let mut any: c_int;
    let mut cutlim: c_int;
    s = nptr;
    loop {
        let fresh0 = s;
        s = s.offset(1);
        c = *fresh0 as c_uchar as c_int;
        if spine_isspace(c) == 0 {
            break;
        }
    }
    if c == '-' as i32 {
        neg = 1 as c_int;
        let fresh1 = s;
        s = s.offset(1);
        c = *fresh1 as c_int;
    } else {
        neg = 0 as c_int;
        if c == '+' as i32 {
            let fresh2 = s;
            s = s.offset(1);
            c = *fresh2 as c_int;
        }
    }
    if (base == 0 as c_int || base == 16 as c_int)
        && c == '0' as i32
        && (*s as c_int == 'x' as i32 || *s as c_int == 'X' as i32)
    {
        c = *s.offset(1 as c_int as isize) as c_int;
        s = s.offset(2 as c_int as isize);
        base = 16 as c_int;
    }
    if base == 0 as c_int {
        base = if c == '0' as i32 {
            8 as c_int
        } else {
            10 as c_int
        };
    }
    cutoff = (if neg != 0 {
        (9223372036854775808 as c_ulong).wrapping_neg()
    } else {
        9223372036854775807 as c_long as c_ulong
    }) as c_long;
    cutlim = (cutoff % base as c_long) as c_int;
    cutoff /= base as c_long;
    if neg != 0 {
        if cutlim > 0 as c_int {
            cutlim -= base;
            cutoff += 1 as c_int as c_long;
        }
        cutlim = -cutlim;
    }
    acc = 0 as c_int as c_long;
    any = 0 as c_int;
    loop {
        if spine_isdigit(c) != 0 {
            c -= '0' as i32;
        } else {
            if spine_isalpha(c) == 0 {
                break;
            }
            c -= if spine_isupper(c) != 0 {
                'A' as i32 - 10 as c_int
            } else {
                'a' as i32 - 10 as c_int
            };
        }
        if c >= base {
            break;
        }
        if any >= 0 as c_int {
            if neg != 0 {
                if acc < cutoff || acc == cutoff && c > cutlim {
                    any = -(1 as c_int);
                    acc = (9223372036854775808 as c_ulong).wrapping_neg() as c_long;
                } else {
                    any = 1 as c_int;
                    acc *= base as c_long;
                    acc -= c as c_long;
                }
            } else if acc > cutoff || acc == cutoff && c > cutlim {
                any = -(1 as c_int);
                acc = 9223372036854775807 as c_long;
            } else {
                any = 1 as c_int;
                acc *= base as c_long;
                acc += c as c_long;
            }
        }
        let fresh3 = s;
        s = s.offset(1);
        c = *fresh3 as c_uchar as c_int;
    }
    if !endptr.is_null() {
        *endptr = (if any != 0 {
            s.offset(-(1 as c_int as isize))
        } else {
            nptr
        }) as *mut c_char;
    }
    acc
}

#[no_mangle]
pub unsafe extern "C" fn spine_strtoul(
    nptr: *const c_char,
    endptr: *mut *mut c_char,
    mut base: c_int,
) -> c_ulong {
    let mut s: *const c_char;
    let mut acc: c_ulong;
    let cutoff: c_ulong = (18446744073709551615 as c_ulong).wrapping_div(base as c_ulong);
    let mut c: c_int;
    let neg: c_int;
    let mut any: c_int;
    let cutlim: c_int = (18446744073709551615 as c_ulong).wrapping_rem(base as c_ulong) as c_int;
    s = nptr;
    loop {
        let fresh0 = s;
        s = s.offset(1);
        c = *fresh0 as c_uchar as c_int;
        if spine_isspace(c) == 0 {
            break;
        }
    }
    if c == '-' as i32 {
        neg = 1 as c_int;
        let fresh1 = s;
        s = s.offset(1);
        c = *fresh1 as c_int;
    } else {
        neg = 0 as c_int;
        if c == '+' as i32 {
            let fresh2 = s;
            s = s.offset(1);
            c = *fresh2 as c_int;
        }
    }
    if (base == 0 as c_int || base == 16 as c_int)
        && c == '0' as i32
        && (*s as c_int == 'x' as i32 || *s as c_int == 'X' as i32)
    {
        c = *s.offset(1 as c_int as isize) as c_int;
        s = s.offset(2 as c_int as isize);
        base = 16 as c_int;
    }
    if base == 0 as c_int {
        base = if c == '0' as i32 {
            8 as c_int
        } else {
            10 as c_int
        };
    }
    acc = 0 as c_int as c_ulong;
    any = 0 as c_int;
    loop {
        if spine_isdigit(c) != 0 {
            c -= '0' as i32;
        } else {
            if spine_isalpha(c) == 0 {
                break;
            }
            c -= if spine_isupper(c) != 0 {
                'A' as i32 - 10 as c_int
            } else {
                'a' as i32 - 10 as c_int
            };
        }
        if c >= base {
            break;
        }
        if any >= 0 as c_int {
            if acc > cutoff || acc == cutoff && c > cutlim {
                any = -(1 as c_int);
                acc = 18446744073709551615 as c_ulong;
            } else {
                any = 1 as c_int;
                acc = acc.wrapping_mul(base as c_ulong);
                acc = acc.wrapping_add(c as c_ulong);
            }
        }
        let fresh3 = s;
        s = s.offset(1);
        c = *fresh3 as c_uchar as c_int;
    }
    if neg != 0 && any > 0 as c_int {
        acc = acc.wrapping_neg();
    }
    if !endptr.is_null() {
        *endptr = (if any != 0 {
            s.offset(-(1 as c_int as isize))
        } else {
            nptr
        }) as *mut c_char;
    }
    acc
}

#[no_mangle]
pub unsafe extern "C" fn spine_strrchr(mut p: *const c_char, ch: c_int) -> *mut c_char {
    let mut save: *mut c_char = std::ptr::null_mut::<c_char>();
    loop {
        if *p as c_int == ch {
            save = p as *mut c_char;
        }
        if *p == 0 {
            return save;
        }
        p = p.offset(1);
    }
}

#[no_mangle]
unsafe fn spine_rand() -> c_int {
    unimplemented!();
}

#[no_mangle]
fn spine_sqrtf(x: c_float) -> c_float {
    x.sqrt()
}

#[no_mangle]
unsafe fn spine_malloc(size: size_t) -> *mut c_void {
    let singleton = Allocator::singleton();
    let mut allocator = singleton.lock().unwrap();
    allocator.malloc(size as usize)
}

#[no_mangle]
unsafe fn spine_realloc(ptr: *mut c_void, size: size_t) -> *mut c_void {
    if !ptr.is_null() {
        let singleton = Allocator::singleton();
        let mut allocator = singleton.lock().unwrap();
        allocator.realloc(ptr, size as usize)
    } else {
        std::ptr::null_mut()
    }
}

#[no_mangle]
unsafe fn spine_free(ptr: *mut c_void) {
    if !ptr.is_null() && ptr != 1 as *mut c_void {
        let singleton = Allocator::singleton();
        let mut allocator = singleton.lock().unwrap();
        allocator.free(ptr)
    }
}

#[no_mangle]
unsafe fn spine_memcpy(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void {
    std::ptr::copy_nonoverlapping(src, dest, n as usize);
    dest
}

#[no_mangle]
unsafe fn spine_memmove(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void {
    std::ptr::copy(src, dest, n as usize);
    dest
}

#[no_mangle]
unsafe fn spine_memset(s: *mut c_void, c: c_int, n: size_t) -> *mut c_void {
    for offset in 0..n {
        (*(s as *mut u8).offset(offset as isize)) = c as u8;
    }
    s
}

#[no_mangle]
unsafe fn spine_fopen(_filename: *const c_char, _modes: *const c_char) -> *mut FILE {
    unimplemented!();
}

#[no_mangle]
unsafe fn spine_fclose(_stream: *mut FILE) -> c_int {
    unimplemented!();
}

#[no_mangle]
unsafe fn spine_fread(_ptr: *mut c_void, _size: size_t, _n: size_t, _stream: *mut FILE) -> size_t {
    unimplemented!();
}

#[no_mangle]
unsafe fn spine_fseek(_stream: *mut FILE, _off: c_long, _whence: c_int) -> c_int {
    unimplemented!();
}

#[no_mangle]
unsafe fn spine_ftell(_stream: *mut FILE) -> c_long {
    unimplemented!();
}

fn fmt(format: String, args: Vec<Box<dyn Any>>) -> String {
    let mut new_str = "".to_owned();
    let mut percent = false;
    let mut index = 0;
    for char in format.chars() {
        if char == '%' {
            percent = true;
        } else if percent {
            if let Some(arg) = args.get(index) {
                match char {
                    'i' | 'd' => {
                        if let Some(i) = arg.downcast_ref::<i32>() {
                            new_str += &format!("{}", *i);
                        } else if let Some(i) = arg.downcast_ref::<u32>() {
                            new_str += &format!("{}", *i);
                        } else {
                            panic!("Unsupported printf argument type");
                        }
                    }
                    's' => {
                        if let Some(s) = arg.downcast_ref::<*const c_char>() {
                            new_str += unsafe { CStr::from_ptr(*s).to_str().unwrap() };
                        } else {
                            panic!("Unsupported printf argument type");
                        }
                    }
                    'f' => {
                        if let Some(f) = arg.downcast_ref::<f32>() {
                            new_str += &format!("{:.6}", *f);
                        } else if let Some(f) = arg.downcast_ref::<f64>() {
                            new_str += &format!("{:.6}", *f);
                        } else {
                            panic!("Unsupported printf argument type");
                        }
                    }
                    'x' => {
                        if let Some(i) = arg.downcast_ref::<i32>() {
                            new_str += &format!("{:x}", *i);
                        } else if let Some(i) = arg.downcast_ref::<u32>() {
                            new_str += &format!("{:x}", *i);
                        } else {
                            panic!("Unsupported printf argument type");
                        }
                    }
                    _ => {
                        panic!("Unsupported printf tag: %{}", char);
                    }
                }
            } else {
                panic!("Incorrect argument count");
            }
            percent = false;
            index += 1;
        } else {
            new_str.push(char);
        }
    }
    new_str
}

pub(crate) fn printf(c_format: *const c_char, args: Vec<Box<dyn Any>>) {
    let format = unsafe { CStr::from_ptr(c_format).to_str().unwrap().to_owned() };
    print!("{}", fmt(format, args));
}

pub(crate) fn sprintf(c_str: *mut c_char, c_format: *const c_char, args: Vec<Box<dyn Any>>) {
    let format = unsafe { CStr::from_ptr(c_format).to_str().unwrap().to_owned() };
    let result = fmt(format, args);
    unsafe {
        let str = CString::new(result).unwrap();
        spine_strcpy(c_str, str.as_ptr());
    }
}

pub(crate) fn sscanf(c_str: *const c_char, c_format: *const c_char, args: *mut c_uint) {
    let str = unsafe { CStr::from_ptr(c_str).to_str().unwrap().to_owned() };
    let format = unsafe { CStr::from_ptr(c_format).to_str().unwrap().to_owned() };
    assert_eq!(format, "%4x");
    unsafe {
        *args = c_uint::from_str_radix(&str[0..(str.len().min(4))], 16).unwrap();
    }
}

macro_rules! spine_printf {
    ($format:expr) => {
        crate::c::wasm::printf($format, vec![]);
    };
    ($format:expr, $($arg:expr),+ $(,)? ) => {
        crate::c::wasm::printf($format, vec![
            $(Box::new($arg)),+
        ]);
    };
}

macro_rules! spine_sprintf {
    ($str:expr, $format:expr) => {
        crate::c::wasm::sprintf($str, $format, vec![]);
    };
    ($str:expr, $format:expr, $($arg:expr),+ $(,)? ) => {
        crate::c::wasm::sprintf($str, $format, vec![
            $(Box::new($arg)),+
        ]);
    };
}

macro_rules! spine_sscanf {
    ($str:expr, $format:expr, $a:expr) => {
        crate::c::wasm::sscanf($str, $format, $a);
    };
    ($str:expr, $format:expr, $a:expr,) => {
        crate::c::wasm::sscanf($str, $format, $a);
    };
}

#[cfg(test)]
mod tests {
    use std::ffi::CString;

    use crate::c::{
        c_uint,
        wasm::{spine_strtol, spine_strtoul},
    };

    use super::{spine_strlen, Allocator};

    #[test]
    fn allocator() {
        let mut allocator = Allocator::default();
        let mut allocations = vec![];
        for _ in 0..30 {
            let data = allocator.malloc(255) as *mut u8;
            unsafe {
                for i in 0..255 {
                    *data.offset(i) = i as u8;
                }
                for i in 0..255 {
                    assert_eq!(*data.offset(i), i as u8);
                }
                assert_eq!(allocator.size(data as *const super::c_void), 255);
            }
            allocations.push(data);
        }
        assert_eq!(allocator.size_allocated(), 30 * 255);
        for allocation in allocations.iter() {
            unsafe { allocator.free(*allocation as *const super::c_void) }
        }
        assert_eq!(allocator.size_allocated(), 0);
    }

    #[test]
    fn strlen() {
        unsafe {
            let empty = CString::new("").unwrap();
            assert_eq!(spine_strlen(empty.as_ptr()), 0);
            let hello_world = CString::new("hello world").unwrap();
            assert_eq!(spine_strlen(hello_world.as_ptr()), 11);
        }
    }

    #[test]
    fn strtol() {
        unsafe {
            let str = CString::new("1234 hello world").unwrap();
            let mut endptr: *mut super::c_char = std::ptr::null_mut();
            let value = spine_strtol(str.as_ptr(), &mut endptr, 10);
            assert_eq!(value, 1234);
            assert_eq!(endptr as *const super::c_char, str.as_ptr().offset(4));

            let str = CString::new("hello world").unwrap();
            let mut endptr: *mut super::c_char = std::ptr::null_mut();
            let value = spine_strtol(str.as_ptr(), &mut endptr, 10);
            assert_eq!(value, 0);
            assert_eq!(endptr as *const super::c_char, str.as_ptr().offset(0));
        }
    }

    #[test]
    fn strtoul() {
        unsafe {
            let str = CString::new("1234 hello world").unwrap();
            let mut endptr: *mut super::c_char = std::ptr::null_mut();
            let value = spine_strtoul(str.as_ptr(), &mut endptr, 10);
            assert_eq!(value, 1234);
            assert_eq!(endptr as *const super::c_char, str.as_ptr().offset(4));

            let str = CString::new("hello world").unwrap();
            let mut endptr: *mut super::c_char = std::ptr::null_mut();
            let value = spine_strtoul(str.as_ptr(), &mut endptr, 10);
            assert_eq!(value, 0);
            assert_eq!(endptr as *const super::c_char, str.as_ptr().offset(0));
        }
    }

    #[test]
    fn fmt() {
        assert_eq!(
            super::fmt("integer: (%i)".to_string(), vec![Box::new(52)]),
            "integer: (52)"
        );
        assert_eq!(
            super::fmt("integer: (%d)".to_string(), vec![Box::new(123)]),
            "integer: (123)"
        );
        assert_eq!(
            super::fmt("float: (%f)".to_string(), vec![Box::new(3.14)]),
            "float: (3.140000)"
        );
        let c_str = CString::new("hello").unwrap();
        assert_eq!(
            super::fmt("string: (%s)".to_string(), vec![Box::new(c_str.as_ptr())]),
            "string: (hello)"
        );
        assert_eq!(
            super::fmt("hex: (%x)".to_string(), vec![Box::new(200)]),
            "hex: (c8)"
        );
    }

    #[test]
    fn sscanf() {
        let c_str = CString::new("3fa5").unwrap();
        let c_format = CString::new("%4x").unwrap();
        let mut uc: c_uint = 0;
        spine_sscanf!(c_str.as_ptr(), c_format.as_ptr(), &mut uc);
        assert_eq!(uc, 16293);

        let c_str = CString::new("3f").unwrap();
        spine_sscanf!(c_str.as_ptr(), c_format.as_ptr(), &mut uc);
        assert_eq!(uc, 63);

        let c_str = CString::new("3fa5ff").unwrap();
        spine_sscanf!(c_str.as_ptr(), c_format.as_ptr(), &mut uc);
        assert_eq!(uc, 16293);
    }
}