sn_bindgen 0.13.18

A library to automatically generate C, Java, and C# files from Rust source files.
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
use super::*;
use crate::test_utils::fetch;
use indoc::indoc;

#[test]
fn non_repr_c_types_are_ignored() {
    let outputs = compile!(LangCSharp::default(), {
        pub struct Foo {
            bar: i32,
        }

        pub enum Meta {
            Foo,
            Bar,
            Baz,
        }
    });

    let actual = fetch(&outputs, "Types.cs");
    assert!(actual.is_empty());
}

#[test]
fn structs() {
    let outputs = compile!(LangCSharp::default(), {
        #[repr(C)]
        pub struct Record {
            id: u64,
            enabled: bool,
            name: *const c_char,
            random_numbers: [i32; 10],
            widget: Widget,
            gadgets: [Gadget; 100],
        }
    });

    let actual = fetch(&outputs, "Types.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Runtime.InteropServices;

         namespace Backend
         {
             public struct Record
             {
                 public ulong Id;
                 [MarshalAs(UnmanagedType.U1)]
                 public bool Enabled;
                 [MarshalAs(UnmanagedType.LPStr)]
                 public string Name;
                 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
                 public int[] RandomNumbers;
                 public Widget Widget;
                 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
                 public Gadget[] Gadgets;
             }

         }
         "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn native_structs() {
    let outputs = compile!(LangCSharp::default(), {
        #[repr(C)]
        pub struct Entry {
            id: u32,
            key_ptr: *const u8,
            key_len: usize,
            records_ptr: *const Record,
            records_len: usize,
            records_cap: usize,
            records_changelog: *const *const c_char,
            records_changelog_len: usize,
        }

        #[repr(C)]
        pub struct Wrapper {
            wrapped: Entry,
        }

        #[no_mangle]
        pub extern "C" fn fun0(entry: Entry) {}

        #[no_mangle]
        pub extern "C" fn fun1(entry: *const Entry) {}

        #[no_mangle]
        pub extern "C" fn fun2(
            user_data: *mut c_void,
            cb: extern "C" fn(
                user_data: *mut c_void,
                result: *const FfiResult,
                entry: *const Entry,
            ),
        ) {
        }

        #[no_mangle]
        pub extern "C" fn fun3(
            user_data: *mut c_void,
            cb: extern "C" fn(
                user_data: *mut c_void,
                result: *const FfiResult,
                entries: *const Entry,
                entries_len: usize,
            ),
        ) {
        }
    });

    // Wrapper types.
    let actual = fetch(&outputs, "Types.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Runtime.InteropServices;
         
         namespace Backend
         {
             public struct Entry
             {
                 public uint Id;
                 public List<byte> Key;
                 public List<Record> Records;
                 public List<string> RecordsChangelog;
  
                 internal Entry(EntryNative native)
                 {
                     Id = native.Id;
                     Key = Utils.CopyToByteList(native.KeyPtr, (int)native.KeyLen);
                     Records = Utils.CopyToObjectList<Record>(native.RecordsPtr, \
                                                             (int)native.RecordsLen);
                     RecordsChangelog = Utils.CopyToStringList(native.RecordsChangelogPtr, \
                                                             (int)native.RecordsChangelogLen);
                 }
  
                 internal EntryNative ToNative()
                 {
                     return new EntryNative
                     {
                         Id = Id,
                         KeyPtr = Utils.CopyFromByteList(Key),
                         KeyLen = (UIntPtr)(Key?.Count ?? 0),
                         RecordsPtr = Utils.CopyFromObjectList(Records),
                         RecordsLen = (UIntPtr)(Records?.Count ?? 0),
                         RecordsCap = UIntPtr.Zero,
                         RecordsChangelogPtr = Utils.CopyFromStringList(RecordsChangelog),
                         RecordsChangelogLen = (UIntPtr)(RecordsChangelog?.Count ?? 0)
                     };
                 }
             }
  
             internal struct EntryNative
             {
                 public uint Id;
                 public IntPtr KeyPtr;
                 public UIntPtr KeyLen;
                 public IntPtr RecordsPtr;
                 public UIntPtr RecordsLen;
                 public UIntPtr RecordsCap;
                 public IntPtr RecordsChangelogPtr;
                 public UIntPtr RecordsChangelogLen;
  
                 internal void Free()
                 {
                     Utils.FreeList(ref KeyPtr, ref KeyLen);
                     Utils.FreeList(ref RecordsPtr, ref RecordsLen);
                     Utils.FreeList(ref RecordsChangelogPtr, ref RecordsChangelogLen);
                 }
             }
  
             public struct Wrapper
             {
                 public Entry Wrapped;
  
                 internal Wrapper(WrapperNative native)
                 {
                     Wrapped = new Entry(native.Wrapped);
                 }
  
                 internal WrapperNative ToNative()
                 {
                     return new WrapperNative
                     {
                         Wrapped = Wrapped.ToNative()
                     };
                 }
             }
  
             internal struct WrapperNative
             {
                 public EntryNative Wrapped;
 
                 internal void Free()
                 {
                     Wrapped.Free();
                 }
             }
 
         }
        "
    );
    assert_multiline_eq!(actual, expected);

    // Functions.
    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public void Fun0(Entry entry)
                 {
                     var entryNative = entry.ToNative();
                     Fun0Native(entryNative);
                     entryNative.Free();
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun0\")]
                 private static extern void Fun0Native(EntryNative entry);
    
                 public void Fun1(ref Entry entry)
                 {
                     var entryNative = entry.ToNative();
                     Fun1Native(ref entryNative);
                     entryNative.Free();
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun1\")]
                 private static extern void Fun1Native(ref EntryNative entry);
    
                 public Task<Entry> Fun2Async()
                 {
                     var (ret, userData) = Utils.PrepareTask<Entry>();
                     Fun2Native(userData, DelegateOnFfiResultEntryCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun2\")]
                 private static extern void Fun2Native(IntPtr userData, \
                                                       FfiResultEntryCb cb);
    
                 public Task<List<Entry>> Fun3Async()
                 {
                     var (ret, userData) = Utils.PrepareTask<List<Entry>>();
                     Fun3Native(userData, DelegateOnFfiResultEntryListCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun3\")]
                 private static extern void Fun3Native(IntPtr userData, FfiResultEntryListCb cb);
    
                 private delegate void FfiResultEntryCb(IntPtr userData, \
                                                        IntPtr result, \
                                                        IntPtr entry);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultEntryCb))]
                 #endif
                 private static void OnFfiResultEntryCb(IntPtr userData, \
                                                        IntPtr result, \
                                                        IntPtr entry)
                 {
                     Utils.CompleteTask(userData, \
                                      Marshal.PtrToStructure<FfiResult>(result), \
                                      () => new Entry(Marshal.PtrToStructure<EntryNative>(entry)));
                 }
    
                 private static readonly FfiResultEntryCb DelegateOnFfiResultEntryCb = OnFfiResultEntryCb;
    
                 private delegate void FfiResultEntryListCb(IntPtr userData, \
                                                            IntPtr result, \
                                                            IntPtr entriesPtr, \
                                                            UIntPtr entriesLen);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultEntryListCb))]
                 #endif
                 private static void OnFfiResultEntryListCb(IntPtr userData, \
                                                            IntPtr result, \
                                                            IntPtr entriesPtr, \
                                                            UIntPtr entriesLen)
                 {
                     Utils.CompleteTask(\
                     userData, \
                     Marshal.PtrToStructure<FfiResult>(result), \
                     () => Utils.CopyToObjectList<EntryNative>(\
                       entriesPtr, \
                       (int)entriesLen).Select(native => new Entry(native)).ToList());
                 }
    
                 private static readonly FfiResultEntryListCb DelegateOnFfiResultEntryListCb = OnFfiResultEntryListCb;
  
             }
         }
        "
    );
    assert_multiline_eq!(actual, expected);
}

#[test]
fn type_aliases() {
    let outputs = compile!(LangCSharp::default(), {
        pub type Id = u64;
        // Double indirection.
        pub type UserId = Id;

        #[repr(C)]
        pub struct Message {
            id: Id,
            sender_id: UserId,
            receiver_ids: [Id; 10],
        }

        #[no_mangle]
        pub extern "C" fn fun(
            id: Id,
            user_data: *mut c_void,
            cb: extern "C" fn(*mut c_void, *const FfiResult, Id),
        ) {
        }
    });

    let actual = fetch(&outputs, "Types.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Runtime.InteropServices;

         namespace Backend
         {
             public struct Message
             {
                 public ulong Id;
                 public ulong SenderId;
                 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
                 public ulong[] ReceiverIds;
             }

         }
         "
    );
    assert_multiline_eq!(actual, expected);

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public Task<ulong> FunAsync(ulong id)
                 {
                     var (ret, userData) = Utils.PrepareTask<ulong>();
                     FunNative(id, userData, DelegateOnFfiResultULongCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun\")]
                 private static extern void FunNative(ulong id, \
                                                      IntPtr userData, \
                                                      FfiResultULongCb cb);
    
                 private delegate void FfiResultULongCb(IntPtr arg0, \
                                                        IntPtr arg1, \
                                                        ulong arg2);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultULongCb))]
                 #endif
                 private static void OnFfiResultULongCb(IntPtr arg0, \
                                                        IntPtr arg1, \
                                                        ulong arg2)
                 {
                     Utils.CompleteTask(arg0, \
                                      Marshal.PtrToStructure<FfiResult>(arg1), \
                                      () => arg2);
                 }
    
                 private static readonly FfiResultULongCb DelegateOnFfiResultULongCb = OnFfiResultULongCb;
    
             }
         }
         "
    );
    assert_multiline_eq!(actual, expected);
}

#[test]
fn enums() {
    let outputs = compile!(LangCSharp::default(), {
        #[repr(C)]
        pub enum Mode {
            ReadOnly,
            WriteOnly,
            ReadAndWrite,
        }

        #[repr(C)]
        pub enum Binary {
            Zero = 0,
            One = 1,
        }
    });

    let actual = fetch(&outputs, "Types.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Runtime.InteropServices;

         namespace Backend
         {
             public enum Mode
             {
                 ReadOnly,
                 WriteOnly,
                 ReadAndWrite,
             }

             public enum Binary
             {
                 Zero = 0,
                 One = 1,
             }

         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_without_extern_and_no_mangle_are_ignored() {
    let outputs = compile!(LangCSharp::default(), {
        pub extern "C" fn fun1() {}

        #[no_mangle]
        pub fn fun2() {}
    });

    let actual = fetch(&outputs, "Backend.cs");
    assert_eq!("", actual, "expected empty output");
}

#[test]
fn functions_taking_no_callbacks() {
    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun0(engine: *mut Engine) {}
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public void Fun0(ref Engine engine)
                 {
                     Fun0Native(ref engine);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun0\")]
                 private static extern void Fun0Native(ref Engine engine);
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_taking_one_callback() {
    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun1(
            num: i32,
            name: *const c_char,
            user_data: *mut c_void,
            cb: extern "C" fn(user_data: *mut c_void, result: *const FfiResult),
        ) {
        }
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public Task Fun1Async(int num, string name)
                 {
                     var (ret, userData) = Utils.PrepareTask();
                     Fun1Native(num, name, userData, DelegateOnFfiResultCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun1\")]
                 private static extern void Fun1Native(\
                   int num, \
                   [MarshalAs(UnmanagedType.LPStr)] string name, \
                   IntPtr userData, \
                   FfiResultCb cb);
    
                 private delegate void FfiResultCb(IntPtr userData, IntPtr result);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultCb))]
                 #endif
                 private static void OnFfiResultCb(IntPtr userData, IntPtr result)
                 {
                     Utils.CompleteTask(userData, Marshal.PtrToStructure<FfiResult>(result));
                 }
    
                 private static readonly FfiResultCb DelegateOnFfiResultCb = OnFfiResultCb;
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_taking_multiple_callbacks() {
    // Only the native declaration should be produced.

    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun(
            input: i32,
            user_data: *mut c_void,
            cb0: extern "C" fn(user_data: *mut c_void),
            cb1: extern "C" fn(user_data: *mut c_void, result: *const FfiResult, output: i32),
        ) {
        }
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 [DllImport(DllName, EntryPoint = \"fun\")]
                 private static extern void FunNative(int input, \
                                                       IntPtr userData, \
                                                       NoneCb cb0, \
                                                       FfiResultIntCb cb1);
    
                 private delegate void FfiResultIntCb(IntPtr userData, \
                                                       IntPtr result, \
                                                       int output);
    
                 private delegate void NoneCb(IntPtr userData);
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_taking_array() {
    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun0(data_ptr: *const u8, data_len: usize) {}

        // Different naming convention
        #[no_mangle]
        pub extern "C" fn fun1(data: *const u8, data_len: usize) {}

        // Params before and/or after the array
        #[no_mangle]
        pub extern "C" fn fun2(id: u64, data_ptr: *const u8, data_len: usize) {}

        // This one does not follow the naming convention and thus is not transformed
        // to array.
        #[no_mangle]
        pub extern "C" fn fun3(result: *const FfiResult, len: usize) {}
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public void Fun0(List<byte> data)
                 {
                     Fun0Native(data?.ToArray(), (UIntPtr)(data?.Count ?? 0));
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun0\")]
                 private static extern void Fun0Native(\
                   [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, \
                   UIntPtr dataLen\
                 );
    
                 public void Fun1(List<byte> data)
                 {
                     Fun1Native(data?.ToArray(), (UIntPtr)(data?.Count ?? 0));
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun1\")]
                 private static extern void Fun1Native(\
                   [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, \
                   UIntPtr dataLen\
                 );
    
                 public void Fun2(ulong id, List<byte> data)
                 {
                     Fun2Native(id, data?.ToArray(), (UIntPtr)(data?.Count ?? 0));
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun2\")]
                 private static extern void Fun2Native(\
                   ulong id, \
                   [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] data, \
                   UIntPtr dataLen\
                 );
    
                 public void Fun3(ref FfiResult result, UIntPtr len)
                 {
                     Fun3Native(ref result, len);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun3\")]
                 private static extern void Fun3Native(ref FfiResult result, UIntPtr len);
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_taking_callback_taking_const_size_array() {
    let outputs = compile!(LangCSharp::default(), {
        pub type Nonce = [u8; NONCE_LEN];

        // Literal.
        #[no_mangle]
        pub extern "C" fn fun2(
            user_data: *mut c_void,
            cb: extern "C" fn(user_data: *mut c_void, result: *const FfiResult, key: [u8; 32]),
        ) {
        }

        // Pointor to array via named constant.
        #[no_mangle]
        pub extern "C" fn fun3(
            user_data: *mut c_void,
            cb: extern "C" fn(
                user_data: *mut c_void,
                result: *const FfiResult,
                nonce: *const Nonce,
            ),
        ) {
        }
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public Task<byte[]> Fun2Async()
                 {
                     var (ret, userData) = Utils.PrepareTask<byte[]>();
                     Fun2Native(userData, DelegateOnFfiResultByteArray32Cb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun2\")]
                 private static extern void Fun2Native(IntPtr userData, \
                                                       FfiResultByteArray32Cb cb);
    
                 public Task<byte[]> Fun3Async()
                 {
                     var (ret, userData) = Utils.PrepareTask<byte[]>();
                     Fun3Native(userData, DelegateOnFfiResultByteArrayNonceLenCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun3\")]
                 private static extern void Fun3Native(IntPtr userData, \
                                                       FfiResultByteArrayNonceLenCb cb);
    
                 private delegate void FfiResultByteArray32Cb(IntPtr userData, \
                                                              IntPtr result, \
                                                              IntPtr key);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultByteArray32Cb))]
                 #endif
                 private static void OnFfiResultByteArray32Cb(IntPtr userData, \
                                                              IntPtr result, \
                                                              IntPtr key)
                 {
                     Utils.CompleteTask(userData, \
                                      Marshal.PtrToStructure<FfiResult>(result), \
                                      () => Utils.CopyToByteArray(key, 32));
                 }
    
                 private static readonly FfiResultByteArray32Cb DelegateOnFfiResultByteArray32Cb = OnFfiResultByteArray32Cb;
    
                 private delegate void FfiResultByteArrayNonceLenCb(IntPtr userData, \
                                                                    IntPtr result, \
                                                                    IntPtr nonce);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultByteArrayNonceLenCb))]
                 #endif
                 private static void OnFfiResultByteArrayNonceLenCb(IntPtr userData, \
                                                                    IntPtr result, \
                                                                    IntPtr nonce)
                 {
                     Utils.CompleteTask(\
                     userData, \
                     Marshal.PtrToStructure<FfiResult>(result), \
                     () => Utils.CopyToByteArray(nonce, (int)Constants.NonceLen));
                 }
    
                 private static readonly FfiResultByteArrayNonceLenCb DelegateOnFfiResultByteArrayNonceLenCb = OnFfiResultByteArrayNonceLenCb;
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_taking_callback_taking_dynamic_array() {
    let outputs = compile!(LangCSharp::default(), {
        // Primitive type.
        #[no_mangle]
        pub extern "C" fn fun0(
            user_data: *mut c_void,
            cb: extern "C" fn(
                user_data: *mut c_void,
                result: *const FfiResult,
                data_ptr: *const u8,
                data_len: usize,
            ),
        ) {
        }

        // Structures.
        #[no_mangle]
        pub extern "C" fn fun1(
            user_data: *mut c_void,
            cb: extern "C" fn(
                user_data: *mut c_void,
                result: *const FfiResult,
                records_ptr: *const Record,
                records_len: usize,
            ),
        ) {
        }
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public Task<List<byte>> Fun0Async()
                 {
                     var (ret, userData) = Utils.PrepareTask<List<byte>>();
                     Fun0Native(userData, DelegateOnFfiResultByteListCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun0\")]
                 private static extern void Fun0Native(IntPtr userData, \
                                                       FfiResultByteListCb cb);
    
                 public Task<List<Record>> Fun1Async()
                 {
                     var (ret, userData) = Utils.PrepareTask<List<Record>>();
                     Fun1Native(userData, DelegateOnFfiResultRecordListCb);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun1\")]
                 private static extern void Fun1Native(IntPtr userData, \
                                                       FfiResultRecordListCb cb);
    
                 private delegate void FfiResultByteListCb(IntPtr userData, \
                                                           IntPtr result, \
                                                           IntPtr dataPtr, \
                                                           UIntPtr dataLen);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultByteListCb))]
                 #endif
                 private static void OnFfiResultByteListCb(IntPtr userData, \
                                                           IntPtr result, \
                                                           IntPtr dataPtr, \
                                                           UIntPtr dataLen)
                 {
                     Utils.CompleteTask(userData, \
                                      Marshal.PtrToStructure<FfiResult>(result), \
                                      () => Utils.CopyToByteList(dataPtr, (int)dataLen));
                 }
    
                 private static readonly FfiResultByteListCb DelegateOnFfiResultByteListCb = OnFfiResultByteListCb;
    
                 private delegate void FfiResultRecordListCb(IntPtr userData, \
                                                              IntPtr result, \
                                                              IntPtr recordsPtr, \
                                                              UIntPtr recordsLen);
    
                 #if __IOS__
                 [MonoPInvokeCallback(typeof(FfiResultRecordListCb))]
                 #endif
                 private static void OnFfiResultRecordListCb(IntPtr userData, \
                                                             IntPtr result, \
                                                             IntPtr recordsPtr, \
                                                             UIntPtr recordsLen)
                 {
                     Utils.CompleteTask(userData, \
                                      Marshal.PtrToStructure<FfiResult>(result), \
                                      () => Utils.CopyToObjectList<Record>(\
                                        recordsPtr, \
                                        (int)recordsLen));
                 }
    
                 private static readonly FfiResultRecordListCb DelegateOnFfiResultRecordListCb = OnFfiResultRecordListCb;
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_with_return_values() {
    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun(arg: i32) -> bool {}
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public bool Fun(int arg)
                 {
                     var ret = FunNative(arg);
                     return ret;
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun\")]
                 private static extern bool FunNative(int arg);
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn functions_taking_out_param() {
    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun(o_app: *mut *mut App) {}
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public void Fun(out IntPtr oApp)
                 {
                     FunNative(out oApp);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun\")]
                 private static extern void FunNative(out IntPtr oApp);
  
             }
         }
        "
    );
    assert_multiline_eq!(actual, expected);
}

#[test]
fn constants() {
    let mut lang = LangCSharp::new();
    lang.add_const("byte", "Custom", 45);

    let outputs = compile!(lang, {
        pub const NUMBER: i32 = 123;
        pub const STRING: &'static str = "hello world";
        pub const ARRAY: [u8; 4] = [0, 1, 2, 3];

        pub const STRUCT_VALUE: Record = Record {
            id: 0,
            secret_code: "xyz",
        };

        pub const STRUCT_REF: &'static Record = &Record {
            id: 1,
            secret_code: "xyz",
        };

        pub const EMPTY_STR: *const c_char = 0 as *const c_char;
    });

    let actual = fetch(&outputs, "Constants.cs");
    let expected = indoc!(
        "using System;

         namespace Backend
         {
             public static class Constants
             {
                 public const int Number = 123;
                 public const string String = \"hello world\";
                 public static readonly byte[] Array = new byte[] { 0, 1, 2, 3 };
                 public static readonly Record StructValue = new Record { \
                     id = 0, secretCode = \"xyz\" };
                 public static readonly Record StructRef = new Record { \
                     id = 1, secretCode = \"xyz\" };
                 public const string EmptyStr = \"\";
                 public const byte Custom = 45;
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn arrays() {
    let outputs = compile!(LangCSharp::default(), {
        pub const ARRAY_SIZE: usize = 20;
        pub type Key = [u8; 32];

        #[no_mangle]
        pub extern "C" fn fun0(a: [u8; 10], b: [u8; ARRAY_SIZE]) {}

        #[no_mangle]
        pub extern "C" fn fun1(a: *const [u8; 10]) {}

        #[no_mangle]
        pub extern "C" fn fun2(a: *const Key) {}
    });

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public void Fun0(byte[] a, byte[] b)
                 {
                     Fun0Native(a, b);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun0\")]
                 private static extern void Fun0Native(\
                   [MarshalAs(UnmanagedType.LPArray, SizeConst = 10)] \
                   byte[] a, \
                   [MarshalAs(UnmanagedType.LPArray, SizeConst = (int)Constants.ArraySize)] \
                   byte[] b);
    
                 public void Fun1(byte[] a)
                 {
                     Fun1Native(a);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun1\")]
                 private static extern void Fun1Native(\
                   [MarshalAs(UnmanagedType.LPArray, SizeConst = 10)] \
                   byte[] a);
    
                 public void Fun2(byte[] a)
                 {
                     Fun2Native(a);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun2\")]
                 private static extern void Fun2Native(\
                   [MarshalAs(UnmanagedType.LPArray, SizeConst = 32)] \
                   byte[] a);
  
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}

#[test]
fn opaque_types() {
    let mut lang = LangCSharp::new();
    lang.add_opaque_type("Handle");

    let outputs = compile!(lang, {
        #[no_mangle]
        pub extern "C" fn fun0(handle: *const Handle) {}

        #[repr(C)]
        pub struct Context {
            handle: *const Handle,
        }
    });

    let actual = fetch(&outputs, "Types.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Runtime.InteropServices;

         namespace Backend
         {
             public struct Context
             {
                 public IntPtr Handle;
             }

         }
        "
    );
    assert_multiline_eq!(actual, expected);

    let actual = fetch(&outputs, "Backend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Linq;
         using System.Runtime.InteropServices;
         using System.Threading.Tasks;

         namespace Backend
         {
             internal partial class Backend : IBackend
             {
                 #if __IOS__
                 private const string DllName = \"__Internal\";
                 #else
                 private const string DllName = \"backend\";
                 #endif
    
                 public void Fun0(IntPtr handle)
                 {
                     Fun0Native(handle);
                 }
    
                 [DllImport(DllName, EntryPoint = \"fun0\")]
                 private static extern void Fun0Native(IntPtr handle);

             }
         }
        "
    );
    assert_multiline_eq!(actual, expected);
}

#[test]
fn interface() {
    let outputs = compile!(LangCSharp::default(), {
        #[no_mangle]
        pub extern "C" fn fun(
            enabled: bool,
            user_data: *mut c_void,
            cb: extern "C" fn(user_data: *mut c_void, result: *const FfiResult),
        ) {
        }
    });

    let actual = fetch(&outputs, "IBackend.cs");
    let expected = indoc!(
        "using System;
         using System.Collections.Generic;
         using System.Threading.Tasks;

         namespace Backend
         {
             public partial interface IBackend
             {
                 Task FunAsync(bool enabled);
             }
         }
        "
    );

    assert_multiline_eq!(actual, expected);
}