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
use std::collections::{BTreeMap, HashMap};
use std::ffi::{CStr, CString};
use std::hash::Hash;
use std::mem;
use std::os::raw::c_char;
use std::ptr::NonNull;

pub trait FFIConversion<T> {
    unsafe fn ffi_from_const(ffi: *const Self) -> T;
    unsafe fn ffi_to_const(obj: T) -> *const Self;
    unsafe fn ffi_from(ffi: *mut Self) -> T {
        Self::ffi_from_const(ffi)
    }
    unsafe fn ffi_to(obj: T) -> *mut Self {
        Self::ffi_to_const(obj) as *mut _
    }
    unsafe fn ffi_from_opt(ffi: *mut Self) -> Option<T> {
        (!ffi.is_null()).then_some(<Self as FFIConversion<T>>::ffi_from(ffi))
    }
    unsafe fn ffi_to_opt(obj: Option<T>) -> *mut Self where Self: Sized {
        obj.map_or(NonNull::<Self>::dangling().as_ptr(), |o| <Self as FFIConversion<T>>::ffi_to(o))
    }
    unsafe fn destroy(ffi: *mut Self) {
        if ffi.is_null() {
            return;
        }
        unbox_any(ffi);
    }
}

impl FFIConversion<String> for c_char {
    unsafe fn ffi_from_const(ffi: *const Self) -> String {
        CStr::from_ptr(ffi).to_str().unwrap().to_string()
    }

    unsafe fn ffi_to_const(obj: String) -> *const Self {
        let s = CString::new(obj).unwrap();
        s.as_ptr()
    }

    unsafe fn ffi_from(ffi: *mut Self) -> String {
        Self::ffi_from_const(ffi as *const _)
    }

    unsafe fn ffi_to(obj: String) -> *mut Self {
        CString::new(obj).unwrap().into_raw()
    }

    unsafe fn destroy(ffi: *mut Self) {
        if ffi.is_null() {
            return;
        }
        unbox_string(ffi);
    }
}

impl FFIConversion<&str> for c_char {
    unsafe fn ffi_from_const(ffi: *const Self) -> &'static str {
        CStr::from_ptr(ffi).to_str().unwrap()
    }

    unsafe fn ffi_to_const(obj: &str) -> *const Self {
        let s = CString::new(obj).unwrap();
        s.as_ptr()
    }

    unsafe fn ffi_from(ffi: *mut Self) -> &'static str {
        Self::ffi_from_const(ffi)
    }

    unsafe fn ffi_to(obj: &str) -> *mut Self {
        CString::new(obj).unwrap().into_raw()
    }

    unsafe fn destroy(ffi: *mut Self) {
        if ffi.is_null() {
            return;
        }
        unbox_string(ffi);
    }
}

pub fn boxed<T>(obj: T) -> *mut T {
    Box::into_raw(Box::new(obj))
}

pub fn boxed_vec<T>(vec: Vec<T>) -> *mut T {
    let mut slice = vec.into_boxed_slice();
    let ptr = slice.as_mut_ptr();
    mem::forget(slice);
    ptr
}

// pub fn boxed_vec_iterator<T, I: IntoIterator<Item = T>>(vec: I) -> *mut T {
//     vec.into_iter().into
//     let mut slice = vec.into_boxed_slice();
//     let ptr = slice.as_mut_ptr();
//     mem::forget(slice);
//     ptr
// }

/// # Safety
pub unsafe fn unbox_any<T: ?Sized>(any: *mut T) -> Box<T> {
    Box::from_raw(any)
}

/// # Safety
pub unsafe fn unbox_string(data: *mut c_char) {
    let _ = CString::from_raw(data);
}

/// # Safety
pub unsafe fn unbox_vec<T>(vec: Vec<*mut T>) -> Vec<Box<T>> {
    vec.iter().map(|&x| unbox_any(x)).collect()
}

/// # Safety
pub unsafe fn unbox_any_vec<T>(vec: Vec<*mut T>) {
    for &x in vec.iter() {
        unbox_any(x);
    }
}

/// # Safety
pub unsafe fn unbox_any_vec_ptr<T>(ptr: *mut *mut T, count: usize) {
    unbox_any_vec(unbox_vec_ptr(ptr, count));
}

/// # Safety
pub unsafe fn unbox_vec_ptr<T>(ptr: *mut T, count: usize) -> Vec<T> {
    Vec::from_raw_parts(ptr, count, count)
}

// /// # Safety
// pub unsafe fn unbox_simple_vec<T>(vec: VecFFI<T>) {
//     let mem = unbox_vec_ptr(vec.values, vec.count);
//     drop(mem)
// }
//
// pub unsafe fn unbox_vec_ffi<T>(vec: *mut VecFFI<T>) {
//     let vec_ffi = unbox_any(vec);
//     let _reconstructed_vec = unbox_vec_ptr(vec_ffi.values, vec_ffi.count);
// }


pub fn convert_vec_to_fixed_array<const N: usize>(data: &Vec<u8>) -> *mut [u8; N] {
    let mut fixed_array = [0u8; N];
    fixed_array.copy_from_slice(data);
    boxed(fixed_array)
}

pub unsafe fn from_simple_vec<N: Clone>(vec: *const N, count: usize) -> Vec<N> {
    std::slice::from_raw_parts(vec, count).to_vec()
}

pub unsafe fn from_complex_vec<N, V: FFIConversion<N>>(vec: *mut *mut V, count: usize) -> Vec<N> {
    (0..count)
        .map(|i| FFIConversion::ffi_from_const(*vec.add(i)))
        .collect()
}

pub unsafe fn to_simple_vec<O>(obj: Vec<O>) -> *mut O
    where Vec<*mut O>: FromIterator<*mut O> {
    boxed_vec(obj)
}

pub unsafe fn to_complex_vec<O, FFI>(obj: Vec<O>) -> *mut *mut FFI
    where
        FFI: FFIConversion<O>,
        Vec<*mut FFI>: FromIterator<*mut O> {
    boxed_vec(obj.into_iter()
        .map(|o| <FFI as FFIConversion<O>>::ffi_to(o))
        .collect::<Vec<*mut FFI>>())
}



pub unsafe fn from_simple_map<M, K, V>(count: usize, keys: *mut K, values: *mut V) -> M
    where
        M: FFIMapConversion<Key=K, Value=V>,
        K: Copy + Ord,
        V: Copy + Ord {
    fold_to_map(count, keys, values, |o| o, |o| o)
}

pub unsafe fn from_simple_complex_map<M, K, V, V2>(count: usize, keys: *mut K, values: *mut *mut V2) -> M
    where
        M: FFIMapConversion<Key=K, Value=V>,
        K: Copy + Ord,
        V: Ord,
        V2: FFIConversion<V> {
    fold_to_map(count, keys, values, |o| o, |o| FFIConversion::ffi_from(o))
}

pub unsafe fn from_complex_simple_map<M, K, V, K2>(count: usize, keys: *mut *mut K2, values: *mut V) -> M
    where
        M: FFIMapConversion<Key=K, Value=V>,
        V: Copy,
        K2: FFIConversion<K> {
    fold_to_map(count, keys, values, |o| FFIConversion::ffi_from(o), |o| o)
}

pub unsafe fn from_complex_map<M, K, V, K2, V2>(count: usize, keys: *mut *mut K2, values: *mut *mut V2) -> M
    where
        M: FFIMapConversion<Key=K, Value=V>,
        K: Ord,
        V: Ord,
        K2: FFIConversion<K>,
        V2: FFIConversion<V> {
    fold_to_map(count, keys, values, |o| FFIConversion::ffi_from(o), |o| FFIConversion::ffi_from(o))
}

pub unsafe fn fold_to_btree_map<K: Copy, V: Copy, K2: Ord, V2>(count: usize, keys: *mut K, values: *mut V, key_converter: impl Fn(K) -> K2, value_converter: impl Fn(V) -> V2) -> BTreeMap<K2, V2> {
    (0..count).fold(BTreeMap::new(), |mut acc, i| {
        let key = key_converter(*keys.add(i));
        let value = value_converter(*values.add(i));
        acc.insert(key, value);
        acc
    })
}


// pub fn to_complex_vec<N, V: FFIConversion<N>>(obj: Vec<V>) -> *mut *mut V {
    // boxed(V::from { count: obj.len(), values: boxed_complex_vec(obj) })
// }

// pub fn boxed_complex_vec<N, V>(obj: Vec<N>) -> *mut *mut V where Vec<*mut V>: FromIterator<*mut N> {
//     // where
//         // V: FFIConversion<N>,
//         // Vec<*mut V>: FromIterator<*mut N> {
//
// }
// fn fold<B, F>(mut self, init: B, mut f: F) -> B
//     where
//         Self: Sized,
//         F: FnMut(B, Self::Item) -> B,
// {

// pub unsafe fn from_simple_btree_map<B, F, N, K, V>(init: B) -> std::collections::BTreeMap<K, V>
//     where F: FnMut(B, std::collections::BTreeMap::Item) -> B {
//     fol
// }
//
// #[repr(C)]
// #[derive(Clone, Debug)]
// pub struct MapFFI<K, V> {
//     pub count: usize,
//     pub keys: *mut K,
//     pub values: *mut V,
// }
//
// impl<K, V> Drop for MapFFI<K, V> {
//     fn drop(&mut self) {
//         // TODO: Probably it needs to avoid drop for VecFFI and use chain of unbox_any_vec instead
//         unsafe {
//             // for complex maps:
//             // unbox_any_vec(unbox_vec_ptr(self.keys, self.count));
//             // unbox_any_vec(unbox_vec_ptr(self.values, self.count));
//             // for simple maps:
//             unbox_vec_ptr(self.keys, self.count);
//             unbox_vec_ptr(self.values, self.count);
//         }
//     }
// }
//
// impl<K, V> MapFFI<K, V> where K: Copy, V: Copy  {
//     pub unsafe fn fold_to_btree_map<K2: Ord, V2>(self, key_converter: impl Fn(K) -> K2, value_converter: impl Fn(V) -> V2) -> std::collections::BTreeMap<K2, V2> {
//         (0..self.count).fold(std::collections::BTreeMap::new(), |mut acc, i| {
//             let key = key_converter(*self.keys.add(i));
//             let value = value_converter(*self.values.add(i));
//             acc.insert(key, value);
//             acc
//         })
//     }
// }
//
// impl<K, V> MapFFI<K, V> where K: Copy, V: Copy  {
//     pub unsafe fn fold_to_hash_map<K2: Hash + PartialEq + Eq, V2>(self, key_converter: impl Fn(K) -> K2, value_converter: impl Fn(V) -> V2) -> std::collections::HashMap<K2, V2> {
//         (0..self.count).fold(std::collections::HashMap::new(), |mut acc, i| {
//             let key = key_converter(*self.keys.add(i));
//             let value = value_converter(*self.values.add(i));
//             acc.insert(key, value);
//             acc
//         })
//     }
// }

// pub unsafe fn fold_to_btree_map<K, V, K2: Ord, V2>(count: usize, keys: *mut K, values: *mut V, key_converter: impl Fn(K) -> K2, value_converter: impl Fn(V) -> V2) -> BTreeMap<K2, V2> {
//     (0..count).fold(BTreeMap::new(), |mut acc, i| {
//         let key = key_converter(*keys.add(i));
//         let value = value_converter(*values.add(i));
//         acc.insert(key, value);
//         acc
//     })
// }


// #[repr(C)]
// #[derive(Clone, Debug)]
// pub struct VecFFI<V> {
//     pub count: usize,
//     pub values: *mut V,
// }
//
// impl<V> VecFFI<V> {
//     pub fn new(vec: Vec<V>) -> VecFFI<V> {
//         Self { count: vec.len(), values: boxed_vec(vec) }
//     }
// }
//
// impl<V> Drop for VecFFI<V> {
//     fn drop(&mut self) {
//         // TODO: Probably it needs to avoid drop for VecFFI and use chain of unbox_any_vec instead
//         unsafe {
//             // for complex vecs:
//             // unbox_any_vec(unbox_vec_ptr(self.values, self.count));
//             // for simple vecs:
//             unbox_vec_ptr(self.values, self.count);
//         }
//     }
// }


/// We pass here main context of parent program

pub type OpaqueContext = *const std::os::raw::c_void;
pub type OpaqueContextFFI = OpaqueContext;

pub type OpaqueContextMut = *mut std::os::raw::c_void;
pub type OpaqueContextMutFFI = OpaqueContextMut;

impl FFIConversion<OpaqueContextFFI> for OpaqueContext {
    unsafe fn ffi_from_const(ffi: *const Self) -> OpaqueContextFFI {
        *ffi
    }

    unsafe fn ffi_to_const(obj: OpaqueContextFFI) -> *const Self {
        obj as *const _
    }

    unsafe fn ffi_from(ffi: *mut Self) -> OpaqueContextFFI {
       *ffi
    }

    unsafe fn ffi_to(obj: OpaqueContextFFI) -> *mut Self {
        // Converting a const pointer to a mut pointer and then writing to it can lead to undefined
        // behavior if the original memory location wasn't meant to be mutable
        obj as *mut _
    }

    unsafe fn destroy(_ffi: *mut Self) {
        // No destroy no ownership here
    }
}

impl FFIConversion<OpaqueContextMutFFI> for OpaqueContextMut {
    unsafe fn ffi_from_const(ffi: *const Self) -> OpaqueContextMutFFI {
        *ffi
    }

    unsafe fn ffi_to_const(obj: OpaqueContextMutFFI) -> *const Self {
        obj as *const _
    }

    unsafe fn ffi_from(ffi: *mut Self) -> OpaqueContextMutFFI {
        *ffi
    }

    unsafe fn ffi_to(obj: OpaqueContextMutFFI) -> *mut Self {
        // Converting a const pointer to a mut pointer and then writing to it can lead to undefined
        // behavior if the original memory location wasn't meant to be mutable
        boxed(obj)
    }
}

// No Drop implementation for them

pub trait FFIVecConversion {
    type Value;
    unsafe fn decode(&self) -> Vec<Self::Value>;
    unsafe fn encode(obj: Vec<Self::Value>) -> *mut Self;
}


pub trait FFIMapConversion {
    type Key;
    type Value;
    fn new() -> Self;
    fn insert(&mut self, key: Self::Key, value: Self::Value);
}

impl<K: Ord, V> FFIMapConversion for BTreeMap<K, V> {
    type Key = K;
    type Value = V;
    fn new() -> Self { BTreeMap::new() }
    fn insert(&mut self, key: K, value: V) { BTreeMap::insert(self, key, value); }
}

impl<K: Hash + Eq, V> FFIMapConversion for HashMap<K, V> {
    type Key = K;
    type Value = V;
    fn new() -> Self { HashMap::new() }
    fn insert(&mut self, key: K, value: V) { HashMap::insert(self, key, value); }
}


pub unsafe fn fold_to_map<M, K, V, K2, V2>(
    count: usize,
    keys: *mut K,
    values: *mut V,
    key_converter: impl Fn(K) -> K2,
    value_converter: impl Fn(V) -> V2) -> M
    where
        M: FFIMapConversion<Key=K2, Value=V2>,
        K: Copy,
        V: Copy {
    (0..count).fold(M::new(), |mut acc, i| {
        let key = key_converter(*keys.add(i));
        let value = value_converter(*values.add(i));
        acc.insert(key, value);
        acc
    })
}

pub fn simple_vec_iterator<T, F>(iter: impl Iterator<Item=T>) -> *mut T
    where F: Fn(T) -> T {
    boxed_vec(iter.collect::<Vec<_>>())
}

// pub unsafe fn complex_vec_iterator<T: Vec<HashID>, U: Vec_HashID_FFI, F>(iter: impl Iterator<Item=T>) -> *mut *mut U
pub unsafe fn complex_vec_iterator<T, U>(iter: impl Iterator<Item=T>) -> *mut *mut U
    where
        // F: Fn(T) -> *mut U,
        U: FFIConversion<T> {
    boxed_vec(iter.map(|o| <U as FFIConversion<T>>::ffi_to(o)).collect())
}

#[macro_export]
macro_rules! vec_ffi_struct {
    ($name:ident, $t:ty) => {
        #[repr(C)]
        #[derive(Clone)]
        #[allow(non_camel_case_types)]
        pub struct $name {
            pub count: usize,
            pub values: *mut $t,
        }
    }
}

#[macro_export]
macro_rules! map_ffi_struct {
    ($name:ident, $k:ty, $v:ty) => {
        #[repr(C)]
        #[derive(Clone)]
        #[allow(non_camel_case_types)]
        pub struct $name {
            pub count: usize,
            pub keys: *mut $k,
            pub values: *mut $v,
        }
    }
}


#[macro_export]
macro_rules! ffi_conversion_interface_ffi_vec_conversion {
    ($name:ident, $t:ty) => {
        impl ferment_interfaces::FFIConversion<Vec<$t>> for $name {
            unsafe fn ffi_from_const(ffi: *const $name) -> Vec<$t> {
                let ffi_ref = &*ffi;
                ferment_interfaces::FFIVecConversion::decode(ffi_ref)
            }
            unsafe fn ffi_to_const(obj: Vec<$t>) -> *const $name {
                ferment_interfaces::FFIVecConversion::encode(obj)
            }
            unsafe fn destroy(ffi: *mut $name) {
                ferment_interfaces::unbox_any(ffi);
            }
        }
    }
}

#[macro_export]
macro_rules! ffi_conversion_interface_ffi_map_conversion {
    ($name:ident, $map:ty, $from:block, $to:block) => {
        impl ferment_interfaces::FFIConversion<$map> for $name {
            unsafe fn ffi_from_const(ffi: *const $name) -> $map {
                $from
            }
            unsafe fn ffi_to_const(obj: $map) -> *const $name {
                $to
            }
            unsafe fn destroy(ffi: *mut $name) {
                ferment_interfaces::unbox_any(ffi);
            }
        }
    }
}

#[macro_export]
macro_rules! ffi_conversion_interface_ffi_hash_map_conversion {
    ($name:ident, $k:ty, $v:ty, $from: block, $to: block) => {
        ffi_conversion_interface_ffi_map_conversion!($name, HashMap<$k, $v>, $from, $to);
    }
}

#[macro_export]
macro_rules! ffi_vec_conversion {
    ($name:ident, $t:ty, $decode:block, $encode:block) => {
        impl ferment_interfaces::FFIVecConversion for $name {
            type Value = $t;
            unsafe fn decode(&self) -> Vec<Self::Value> { $decode }
            unsafe fn encode(obj: Vec<Self::Value>) -> *mut Self { $encode }
        }
    }
}

#[macro_export]
macro_rules! ffi_vec_simple_conversion {
    ($name:ident, $t:ty) => {
        ffi_vec_conversion!(
            $name,
            $t,
            { ferment_interfaces::from_simple_vec(self.values as *const Self::Value, self.count) },
            { ferment_interfaces::boxed(Self { count: obj.len(), values: ferment_interfaces::boxed_vec(obj) }) }
        );
    }
}

#[macro_export]
macro_rules! ffi_vec_complex_conversion {
    ($name:ident, $t:ty) => {
        ffi_vec_conversion!(
            $name,
            $t, {
                let count = self.count;
                let values = self.values;
                (0..count)
                    .map(|i| ferment_interfaces::FFIConversion::ffi_from_const(*values.add(i)))
                    .collect()
            }, {
                ferment_interfaces::boxed(Self { count: obj.len(), values: ferment_interfaces::complex_vec_iterator(obj.into_iter()) })
            }
        );
    }
}

#[macro_export]
macro_rules! ffi_drop_interface {
    ($name:ident, $drop_code:block) => {
        impl Drop for $name {
            fn drop(&mut self) {
                unsafe {
                    $drop_code
                }
            }
        }
    }
}


#[macro_export]
macro_rules! vec_ffi_simple_drop_interface {
    ($name:ident) => {
        ffi_drop_interface!($name, {
            ferment_interfaces::unbox_vec_ptr(self.values, self.count);
        });
    }
}

#[macro_export]
macro_rules! vec_ffi_complex_drop_interface {
    ($name:ident) => {
        ffi_drop_interface!($name, {
            ferment_interfaces::unbox_any_vec_ptr(self.values, self.count);
        });
    }
}

#[macro_export]
macro_rules! map_ffi_simple_drop_interface {
    ($name:ident) => {
        ffi_drop_interface!($name, {
            ferment_interfaces::unbox_vec_ptr(self.keys, self.count);
            ferment_interfaces::unbox_vec_ptr(self.values, self.count);
        });
    }
}

#[macro_export]
macro_rules! map_ffi_simple_complex_drop_interface {
    ($name:ident) => {
        ffi_drop_interface!($name, {
            ferment_interfaces::unbox_vec_ptr(self.keys, self.count);
            ferment_interfaces::unbox_any_vec_ptr(self.values, self.count);
        });
    }
}

#[macro_export]
macro_rules! map_ffi_complex_simple_drop_interface {
    ($name:ident) => {
        ffi_drop_interface!($name, {
            ferment_interfaces::unbox_any_vec_ptr(self.keys, self.count);
            ferment_interfaces::unbox_vec_ptr(self.values, self.count);
        });
    }
}

#[macro_export]
macro_rules! map_ffi_complex_drop_interface {
    ($name:ident) => {
        ffi_drop_interface!($name, {
            ferment_interfaces::unbox_any_vec_ptr(self.keys, self.count);
            ferment_interfaces::unbox_any_vec_ptr(self.values, self.count);
        });
    }
}


#[macro_export]
macro_rules! vec_ffi_simple_expansion {
    ($name:ident, $t:ty) => {
        vec_ffi_struct!($name, $t);
        ffi_conversion_interface_ffi_vec_conversion!($name, $t);
        ffi_vec_simple_conversion!($name, $t);
        vec_ffi_simple_drop_interface!($name);
    }
}
#[macro_export]
macro_rules! vec_ffi_complex_expansion {
    ($name:ident, $t:ty) => {
        vec_ffi_struct!($name, *mut $t);
        ffi_conversion_interface_ffi_vec_conversion!($name, $t);
        ffi_vec_complex_conversion!($name, $t);
        vec_ffi_complex_drop_interface!($name);
    }
}

#[macro_export]
macro_rules! map_ffi_to {
    ($keys_method:ident, $values_method:ident) => {
        ferment_interfaces::boxed(Self {
            count: obj.len(),
            keys: ferment_interfaces::$keys_method(obj.into_keys()),
            values: ferment_interfaces::$values_method(obj.into_values())
        })
    }
}

#[macro_export]
macro_rules! map_ffi_from {
    ($method:ident) => {
        let ffi_ref = &*ffi;
        ferment_interfaces::$method(ffi_ref.count, ffi_ref.keys, ffi_ref.values)
    }
}

#[macro_export]
macro_rules! map_ffi_simple_expansion {
    ($name:ident, $map:ty, $k:ty, $v:ty) => {
        map_ffi_struct!($name, $k, $v);
        map_ffi_simple_drop_interface!($name);
        ffi_conversion_interface_ffi_map_conversion!(
            $name,
            $map, {
                let ffi_ref = &*ffi;
                ferment_interfaces::from_simple_map(ffi_ref.count, ffi_ref.keys, ffi_ref.values)
            }, {
                map_ffi_to!(simple_vec_iterator, simple_vec_iterator)
            }
        );
    }
}



#[macro_export]
macro_rules! map_ffi_simple_complex_expansion {
    ($name:ident, $map:ty, $k:ty, $v:ty) => {
        map_ffi_struct!($name, $k, *mut $v);
        map_ffi_simple_complex_drop_interface!($name);
        ffi_conversion_interface_ffi_map_conversion!(
            $name,
            $map,
            {
                let ffi_ref = &*ffi;
                ferment_interfaces::from_simple_complex_map(ffi_ref.count, ffi_ref.keys, ffi_ref.values)
            },
            map_ffi_to!(simple_vec_iterator, complex_vec_iterator)
        );
    }
}

#[macro_export]
macro_rules! map_ffi_complex_simple_expansion {
    ($name:ident, $map:ty, $k:ty, $v:ty) => {
        map_ffi_struct!($name, *mut $k, $v);
        map_ffi_complex_simple_drop_interface!($name);
        ffi_conversion_interface_ffi_map_conversion!(
            $name,
            $map,
            {
                let ffi_ref = &*ffi;
                ferment_interfaces::from_complex_simple_map(ffi_ref.count, ffi_ref.keys, ffi_ref.values)
            },
            { map_ffi_to!(complex_vec_iterator, simple_vec_iterator) }
        );
    }
}

#[macro_export]
macro_rules! map_ffi_complex_expansion {
    ($name:ident, $map:ty, $k:ty, $v:ty) => {
        map_ffi_struct!($name, *mut $k, *mut $v);
        map_ffi_complex_drop_interface!($name);
        ffi_conversion_interface_ffi_map_conversion!(
            $name,
            $map,
            {
                let ffi_ref = &*ffi;
                ferment_interfaces::from_complex_map(ffi_ref.count, ffi_ref.keys, ffi_ref.values)
            },
            { map_ffi_to!(complex_vec_iterator, complex_vec_iterator) }
        );
    }
}

// pub enum