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
//! This file contains lib to call hnsw from julia (or any language providing a C api)
//! The AnnT trait is implemented with macros for u32, u16, u8, f32, f64 and i32.  
//! The macro declare_myapi_type!  produces struct HnswApif32 and so on.
//!

#![allow(non_camel_case_types)]

use core::ffi::c_ulonglong;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::path::PathBuf;
use std::ptr;

use anndists::dist::distances::*;

use crate::api::*;
use crate::hnsw::*;
use crate::hnswio::*;

// the export macro makes the macro global in crate and accecssible via crate::declare_myapi_type!
#[macro_export]
macro_rules! declare_myapi_type(
    ($name:ident, $ty:ty) => (
        pub struct $name {
#[allow(dead_code)]
        pub(crate) opaque: Box<dyn AnnT<Val=$ty>>,
        } // end struct
        impl $name {
            pub fn new(arg: Box<dyn AnnT<Val=$ty>>) -> Self {
                $name{ opaque:arg}
            } // end new
        } // end impl
    )
);

declare_myapi_type!(HnswApiNodata, NoData);

// declare_myapi_type!(HnswApif64, f64);
// declare_myapi_type!(HnswApif32, f32);

/// to be able to return a vector from rust in a julia struct before converting to a julia Vector
#[repr(C)]
pub struct Vec_api<T> {
    len: i64,
    ptr: *const T,
} // end struct

#[repr(C)]
/// The basic Neighbour info returned by api
pub struct Neighbour_api {
    /// id of neighbour
    pub id: usize,
    /// distance of data sent in request to this neighbour
    pub d: f32,
}

impl From<&Neighbour> for Neighbour_api {
    fn from(neighbour: &Neighbour) -> Self {
        Neighbour_api {
            id: neighbour.d_id,
            d: neighbour.distance,
        }
    }
}

#[repr(C)]
/// The response to a neighbour search requests
pub struct Neighbourhood_api {
    pub nbgh: i64,
    pub neighbours: *const Neighbour_api,
}

#[repr(C)]
pub struct Neighbour_api_parsearch_answer {
    /// The number of answers (o request), i.e size of both vectors nbgh and neighbours
    pub nb_answer: usize,
    /// for each request, we get a Neighbourhood_api
    pub neighbourhoods: *const Neighbourhood_api,
}

//===================================== f32  type =====================================

// macros have been exported to the root of the crate so we do not refer to them via api::
super::declare_myapi_type!(HnswApif32, f32);
super::declare_myapi_type!(HnswApif64, f64);

//===================================================================================================
//  These are the macros to generate trait implementation for useful numeric types
#[allow(unused_macros)]

macro_rules! generate_insert(
($function_name:ident, $api_name:ty, $type_val:ty) => (
        #[no_mangle]
        pub extern "C" fn $function_name(hnsw_api : *mut $api_name, len:usize, data : *const $type_val, id : usize) {
        log::trace!("entering insert, type {:?} vec len is {:?}, id : {:?} ", stringify!($type_val), len, id);
        //  construct vector: Rust clones and take ownership.
        let data_v : Vec<$type_val>;
        unsafe {
            let slice = std::slice::from_raw_parts(data, len);
            data_v = Vec::from(slice);
            log::trace!("calling insert data");
            (*hnsw_api).opaque.insert_data(&data_v, id);
        }
        log::trace!("exiting insert for type {:?}", stringify!($type_val));
        }  // end of insert
    )
);

macro_rules! generate_parallel_insert(
($function_name:ident, $api_name:ty, $type_val:ty) => (
        #[no_mangle]
        pub extern "C" fn $function_name(hnsw_api : *mut $api_name, nb_vec: usize, vec_len : usize,
                        datas : *mut *const $type_val, ids : *const usize) {
            //
            log::trace!("entering parallel_insert type {:?}  , vec len is {:?}, nb_vec : {:?}", stringify!($type_val), vec_len, nb_vec);
            let data_ids : Vec<usize>;
            let data_ptrs : Vec<*const $type_val>;
            unsafe {
                let slice = std::slice::from_raw_parts(ids, nb_vec);
                data_ids = Vec::from(slice);
            }
            // log::debug!("got ids");
            unsafe {
                let slice = std::slice::from_raw_parts(datas, nb_vec);
                data_ptrs = Vec::from(slice);
            }
            // log::debug!("got data ptrs");
            let mut data_v = Vec::<Vec<$type_val>>::with_capacity(nb_vec);
            for i in 0..nb_vec {
                unsafe {
                    let slice = std::slice::from_raw_parts(data_ptrs[i], vec_len);
                    let v = Vec::from(slice);
                    data_v.push(v);
                }
            }
            // log::debug!("sending request");
            let mut request : Vec<(&Vec<$type_val>, usize)> = Vec::with_capacity(nb_vec);
            for i in 0..nb_vec {
                request.push((&data_v[i], data_ids[i]));
            }
            //
            unsafe { (*hnsw_api).opaque.parallel_insert_data(&request); };
            log::trace!("exiting parallel_insert");
        } // end of parallel_insert
    )
);

macro_rules! generate_search_neighbours(
($function_name:ident, $api_name:ty, $type_val:ty) => (
        #[no_mangle]
        pub extern "C" fn $function_name(hnsw_api : *const $api_name, len:usize, data : *const $type_val,
                                knbn : usize, ef_search : usize) ->  *const Neighbourhood_api {
            //
            log::trace!("entering search_neighbours type {:?}, vec len is {:?}, id : {:?} ef_search {:?}", stringify!($type_val), len, knbn, ef_search);
            let data_v : Vec<$type_val>;
            let neighbours : Vec<Neighbour>;
            unsafe {
                let slice = std::slice::from_raw_parts(data, len);
                data_v = Vec::from(slice);
                log::trace!("calling search neighbours {:?}", data_v);
                neighbours =  (*hnsw_api).opaque.search_neighbours(&data_v, knbn, ef_search);
            }
            let neighbours_api : Vec<Neighbour_api> = neighbours.iter().map(|n| Neighbour_api::from(n)).collect();
            log::trace!(" got nb neighbours {:?}", neighbours_api.len());
            // for i in 0..neighbours_api.len() {
            //    println!(" id {:?}  dist : {:?} ", neighbours_api[i].id, neighbours_api[i].d);
            // }
            let nbgh_i = neighbours.len() as i64;
            let neighbours_ptr = neighbours_api.as_ptr();
            std::mem::forget(neighbours_api);
            let answer = Neighbourhood_api {
                    nbgh : nbgh_i,
                    neighbours : neighbours_ptr,
            };
            log::trace!("search_neighbours returning nb neighbours {:?} id ptr {:?} ", nbgh_i, neighbours_ptr);
            Box::into_raw(Box::new(answer))
        }
    )
);

macro_rules! generate_parallel_search_neighbours(
($function_name:ident, $api_name:ty, $type_val:ty) => (
        #[no_mangle]
        /// search nb_vec of size vec_len. The the searches will be done in // as far as possible.
        pub extern "C" fn $function_name(hnsw_api : *const $api_name, nb_vec : usize, vec_len :i64,
                            data : *mut *const $type_val, knbn : usize, ef_search : usize) ->  *const Vec_api<Neighbourhood_api> {
            //
            // must build a Vec<Vec<f32> to build request
            log::trace!("recieving // search request for type: {:?} with {:?} vectors", stringify!($type_val), nb_vec);
            let neighbours : Vec<Vec<Neighbour> >;
            let mut data_v = Vec::<Vec<$type_val>>::with_capacity(nb_vec);
            unsafe {
                let slice = std::slice::from_raw_parts(data, nb_vec);
                let ptr_list : Vec<*const $type_val> = Vec::from(slice);
                for i in 0..nb_vec {
                    let slice_i = std::slice::from_raw_parts(ptr_list[i], vec_len as usize);
                    let v = Vec::from(slice_i);
                    data_v.push(v);
                }
            // log::debug!(" reconstructed input vectors");
            neighbours =  (*hnsw_api).opaque.parallel_search_neighbours(&data_v, knbn, ef_search);
            }
            // construct a vector of Neighbourhood_api
            // reverse work, construct 2 arrays, one vector of Neighbours, and one vectors of number of returned neigbours by input a vector.
            let mut neighbour_lists = Vec::<Neighbourhood_api>::with_capacity(nb_vec);
            for v in neighbours {
                let neighbours_api : Vec<Neighbour_api> = v.iter().map(|n| Neighbour_api::from(n)).collect();
                let nbgh = neighbours_api.len();
                let neighbours_api_ptr = neighbours_api.as_ptr();
                std::mem::forget(neighbours_api);
                let v_answer = Neighbourhood_api {
                        nbgh : nbgh as i64,
                        neighbours: neighbours_api_ptr,
                    };
                neighbour_lists.push(v_answer);
            }
            log::trace!(" reconstructed output  pointers to vectors");
            let neighbour_lists_ptr = neighbour_lists.as_ptr();
            std::mem::forget(neighbour_lists);
            let answer = Vec_api::<Neighbourhood_api> {
                len : nb_vec as i64,
                ptr : neighbour_lists_ptr,
            };
            Box::into_raw(Box::new(answer))
        }  // end of parallel_search_neighbours_f32 for HnswApif32
    )
);

#[allow(unused_macros)]
macro_rules! generate_file_dump(
    ($function_name:ident, $api_name:ty, $type_val:ty) => (
    #[no_mangle]
        pub extern "C" fn $function_name(hnsw_api : *const $api_name, namelen : usize, filename :*const u8) -> i64 {
            log::info!("receiving request for file dump");
            let slice = unsafe { std::slice::from_raw_parts(filename, namelen) } ;
            let fstring  = String::from_utf8_lossy(slice).into_owned();
            let res =  unsafe { (*hnsw_api).opaque.file_dump(&fstring) } ;
            if res.is_ok() {
                return 1;
            }
            else { return -1; }
        } // end of function_name
    )
);

static mut RELOADER_OPT: Option<HnswIo> = None;

#[allow(unused_macros)]
macro_rules! generate_loadhnsw(
    ($function_name:ident, $api_name:ty, $type_val:ty, $type_dist : ty) => (
        #[no_mangle]
        pub extern "C" fn $function_name(flen : usize, name : *const u8)  -> *const $api_name {
            let  slice = unsafe { std::slice::from_raw_parts(name, flen)} ;
            let filename = String::from_utf8_lossy(slice).into_owned();
            //
            unsafe {
                if RELOADER_OPT.is_some() {
                    log::error!("api can have nonly one mmap active");
                    return ptr::null();
                }
                RELOADER_OPT = Some(HnswIo::new(PathBuf::from("."), filename.clone()));
                let hnsw_loaded_res = RELOADER_OPT.as_mut().unwrap().load_hnsw::<$type_val, $type_dist>();

                if let Ok(hnsw_loaded) = hnsw_loaded_res {
                    let api = <$api_name>::new(Box::new(hnsw_loaded));
                    return Box::into_raw(Box::new(api));
                }
                else {
                    log::warn!("an error occured, could not reload data from {:?}", filename);
                    return ptr::null();
                }
            }
        }  // end of load_hnswdump_
     )
);

// here we must generate as many function as there are couples (type, distance) to be accessed from our needs in Julia

// f32
generate_loadhnsw!(
    load_hnswdump_f32_DistL1,
    HnswApif32,
    f32,
    anndists::dist::distances::DistL1
);
generate_loadhnsw!(
    load_hnswdump_f32_DistL2,
    HnswApif32,
    f32,
    anndists::dist::distances::DistL2
);
generate_loadhnsw!(
    load_hnswdump_f32_DistCosine,
    HnswApif32,
    f32,
    anndists::dist::distances::DistCosine
);
generate_loadhnsw!(
    load_hnswdump_f32_DistDot,
    HnswApif32,
    f32,
    anndists::dist::distances::DistDot
);
generate_loadhnsw!(
    load_hnswdump_f32_DistJensenShannon,
    HnswApif32,
    f32,
    anndists::dist::distances::DistJensenShannon
);
generate_loadhnsw!(
    load_hnswdump_f32_DistJeffreys,
    HnswApif32,
    f32,
    anndists::dist::distances::DistJeffreys
);

// i32
generate_loadhnsw!(
    load_hnswdump_i32_DistL1,
    HnswApii32,
    i32,
    anndists::dist::distances::DistL1
);
generate_loadhnsw!(
    load_hnswdump_i32_DistL2,
    HnswApii32,
    i32,
    anndists::dist::distances::DistL2
);
generate_loadhnsw!(
    load_hnswdump_i32_DistHamming,
    HnswApii32,
    i32,
    anndists::dist::distances::DistHamming
);

// u32
generate_loadhnsw!(
    load_hnswdump_u32_DistL1,
    HnswApiu32,
    u32,
    anndists::dist::distances::DistL1
);
generate_loadhnsw!(
    load_hnswdump_u32_DistL2,
    HnswApiu32,
    u32,
    anndists::dist::distances::DistL2
);
generate_loadhnsw!(
    load_hnswdump_u32_DistHamming,
    HnswApiu32,
    u32,
    anndists::dist::distances::DistHamming
);
generate_loadhnsw!(
    load_hnswdump_u32_DistJaccard,
    HnswApiu32,
    u32,
    anndists::dist::distances::DistJaccard
);

// u16
generate_loadhnsw!(
    load_hnswdump_u16_DistL1,
    HnswApiu16,
    u16,
    anndists::dist::distances::DistL1
);
generate_loadhnsw!(
    load_hnswdump_u16_DistL2,
    HnswApiu16,
    u16,
    anndists::dist::distances::DistL2
);
generate_loadhnsw!(
    load_hnswdump_u16_DistHamming,
    HnswApiu16,
    u16,
    anndists::dist::distances::DistHamming
);
generate_loadhnsw!(
    load_hnswdump_u16_DistLevenshtein,
    HnswApiu16,
    u16,
    anndists::dist::distances::DistLevenshtein
);

// u8
generate_loadhnsw!(
    load_hnswdump_u8_DistL1,
    HnswApiu8,
    u8,
    anndists::dist::distances::DistL1
);
generate_loadhnsw!(
    load_hnswdump_u8_DistL2,
    HnswApiu8,
    u8,
    anndists::dist::distances::DistL2
);
generate_loadhnsw!(
    load_hnswdump_u8_DistHamming,
    HnswApiu8,
    u8,
    anndists::dist::distances::DistHamming
);
generate_loadhnsw!(
    load_hnswdump_u8_DistJaccard,
    HnswApiu8,
    u8,
    anndists::dist::distances::DistJaccard
);

// Reload only graph
generate_loadhnsw!(
    load_hnswdump_NoData_DistNoDist,
    HnswApiNodata,
    NoData,
    anndists::dist::NoDist
);

//=============== implementation for i32

#[no_mangle]
pub extern "C" fn init_hnsw_f32(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
) -> *const HnswApif32 {
    log::info!("entering init_hnsw_f32");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice).into_owned();
    // map distname to sthg. This whole block will go to a macro
    match dname.as_str() {
        "DistL1" => {
            log::info!(" received DistL1");
            let h = Hnsw::<f32, DistL1>::new(max_nb_conn, 10000, 16, ef_const, DistL1 {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistL2" => {
            let h = Hnsw::<f32, DistL2>::new(max_nb_conn, 10000, 16, ef_const, DistL2 {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistDot" => {
            let h = Hnsw::<f32, DistDot>::new(max_nb_conn, 10000, 16, ef_const, DistDot {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistHellinger" => {
            let h =
                Hnsw::<f32, DistHellinger>::new(max_nb_conn, 10000, 16, ef_const, DistHellinger {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistJeffreys" => {
            let h =
                Hnsw::<f32, DistJeffreys>::new(max_nb_conn, 10000, 16, ef_const, DistJeffreys {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistJensenShannon" => {
            let h = Hnsw::<f32, DistJensenShannon>::new(
                max_nb_conn,
                10000,
                16,
                ef_const,
                DistJensenShannon {},
            );
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        _ => {
            log::warn!("init_hnsw_f32 received unknow distance {:?} ", dname);
            let p = ptr::null::<HnswApif32>();
            return p;
        }
    } // znd match
} // end of init_hnsw_f32

/// same as max_layer with different arguments, we pass max_elements and max_layer
#[no_mangle]
pub extern "C" fn new_hnsw_f32(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
    max_elements: usize,
    max_layer: usize,
) -> *const HnswApif32 {
    log::debug!("entering new_hnsw_f32");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice);
    // map distname to sthg. This whole block will go to a macro
    match dname.as_ref() {
        "DistL1" => {
            log::info!(" received DistL1");
            let h =
                Hnsw::<f32, DistL1>::new(max_nb_conn, max_elements, max_layer, ef_const, DistL1 {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistL2" => {
            let h =
                Hnsw::<f32, DistL2>::new(max_nb_conn, max_elements, max_layer, ef_const, DistL2 {});
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistDot" => {
            let h = Hnsw::<f32, DistDot>::new(
                max_nb_conn,
                max_elements,
                max_layer,
                ef_const,
                DistDot {},
            );
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistHellinger" => {
            let h = Hnsw::<f32, DistHellinger>::new(
                max_nb_conn,
                max_elements,
                max_layer,
                ef_const,
                DistHellinger {},
            );
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistJeffreys" => {
            let h = Hnsw::<f32, DistJeffreys>::new(
                max_nb_conn,
                max_elements,
                max_layer,
                ef_const,
                DistJeffreys {},
            );
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        "DistJensenShannon" => {
            let h = Hnsw::<f32, DistJensenShannon>::new(
                max_nb_conn,
                max_elements,
                max_layer,
                ef_const,
                DistJensenShannon {},
            );
            let api = HnswApif32 {
                opaque: Box::new(h),
            };
            return Box::into_raw(Box::new(api));
        }
        _ => {
            log::warn!("init_hnsw_f32 received unknow distance {:?} ", dname);
            let p = ptr::null::<HnswApif32>();
            return p;
        }
    } // znd match
      //
} // end of new_hnsw_f32

#[no_mangle]
pub unsafe extern "C" fn drop_hnsw_f32(p: *const HnswApif32) {
    let _raw = Box::from_raw(p as *mut HnswApif32);
}

#[no_mangle]
pub unsafe extern "C" fn drop_hnsw_u16(p: *const HnswApiu16) {
    let _raw = Box::from_raw(p as *mut HnswApiu16);
}

#[no_mangle]
pub extern "C" fn init_hnsw_ptrdist_f32(
    max_nb_conn: usize,
    ef_const: usize,
    c_func: extern "C" fn(*const f32, *const f32, c_ulonglong) -> f32,
) -> *const HnswApif32 {
    log::info!("init_ hnsw_ptrdist: ptr  {:?}", c_func);
    let c_dist = DistCFFI::<f32>::new(c_func);
    let h = Hnsw::<f32, DistCFFI<f32>>::new(max_nb_conn, 10000, 16, ef_const, c_dist);
    let api = HnswApif32 {
        opaque: Box::new(h),
    };
    return Box::into_raw(Box::new(api));
}

#[no_mangle]
pub extern "C" fn insert_f32(hnsw_api: *mut HnswApif32, len: usize, data: *const f32, id: usize) {
    log::trace!("entering insert_f32, vec len is {:?}, id : {:?} ", len, id);
    //  construct vector: Rust clones and take ownership.
    let data_v: Vec<f32>;
    unsafe {
        let slice = std::slice::from_raw_parts(data, len);
        data_v = Vec::from(slice);
        //    log::debug!("calling insert data");
        (*hnsw_api).opaque.insert_data(&data_v, id);
    }
    // log::trace!("exiting insert_f32");
} // end of insert_f32

#[no_mangle]
pub extern "C" fn parallel_insert_f32(
    hnsw_api: *mut HnswApif32,
    nb_vec: usize,
    vec_len: usize,
    datas: *mut *const f32,
    ids: *const usize,
) {
    //
    // log::debug!("entering parallel_insert_f32 , vec len is {:?}, nb_vec : {:?}", vec_len, nb_vec);
    let data_ids: Vec<usize>;
    let data_ptrs: Vec<*const f32>;
    unsafe {
        let slice = std::slice::from_raw_parts(ids, nb_vec);
        data_ids = Vec::from(slice);
    }
    unsafe {
        let slice = std::slice::from_raw_parts(datas, nb_vec);
        data_ptrs = Vec::from(slice);
    }
    // log::debug!("got data ptrs");
    let mut data_v = Vec::<Vec<f32>>::with_capacity(nb_vec);
    for i in 0..nb_vec {
        unsafe {
            let slice = std::slice::from_raw_parts(data_ptrs[i], vec_len);
            let v = Vec::from(slice);
            data_v.push(v);
        }
    }
    // log::debug!("sending request");
    let mut request: Vec<(&Vec<f32>, usize)> = Vec::with_capacity(nb_vec);
    for i in 0..nb_vec {
        request.push((&data_v[i], data_ids[i]));
    }
    //
    unsafe {
        (*hnsw_api).opaque.parallel_insert_data(&request);
    };
    log::trace!("exiting parallel_insert");
} // end of parallel_insert_f32

#[no_mangle]
pub extern "C" fn search_neighbours_f32(
    hnsw_api: *const HnswApif32,
    len: usize,
    data: *const f32,
    knbn: usize,
    ef_search: usize,
) -> *const Neighbourhood_api {
    //
    log::trace!(
        "entering search_neighbours , vec len is {:?}, id : {:?} ef_search {:?}",
        len,
        knbn,
        ef_search
    );
    let data_v: Vec<f32>;
    let neighbours: Vec<Neighbour>;
    unsafe {
        let slice = std::slice::from_raw_parts(data, len);
        data_v = Vec::from(slice);
        log::trace!("calling search neighbours {:?}", data_v);
        neighbours = (*hnsw_api)
            .opaque
            .search_neighbours(&data_v, knbn, ef_search);
    }
    let neighbours_api: Vec<Neighbour_api> =
        neighbours.iter().map(|n| Neighbour_api::from(n)).collect();
    log::trace!(" got nb neighbours {:?}", neighbours_api.len());
    // for i in 0..neighbours_api.len() {
    //    println!(" id {:?}  dist : {:?} ", neighbours_api[i].id, neighbours_api[i].d);
    // }
    let nbgh_i = neighbours.len() as i64;
    let neighbours_ptr = neighbours_api.as_ptr();
    std::mem::forget(neighbours_api);
    let answer = Neighbourhood_api {
        nbgh: nbgh_i,
        neighbours: neighbours_ptr,
    };
    log::trace!(
        "search_neighbours returning nb neighbours {:?} id ptr {:?} ",
        nbgh_i,
        neighbours_ptr
    );
    Box::into_raw(Box::new(answer))
}
// end of search_neighbours for HnswApif32

generate_parallel_search_neighbours!(parallel_search_neighbours_f32, HnswApif32, f32);
generate_file_dump!(file_dump_f32, HnswApif32, f32);

//=============== implementation for i32

#[no_mangle]
pub extern "C" fn init_hnsw_i32(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
) -> *const HnswApii32 {
    log::info!("entering init_hnsw_i32");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice);
    // map distname to sthing. This whole block will go to a macro
    if dname == "DistL1" {
        log::info!(" received DistL1");
        let h = Hnsw::<i32, DistL1>::new(max_nb_conn, 10000, 16, ef_const, DistL1 {});
        let api = HnswApii32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistL2" {
        let h = Hnsw::<i32, DistL2>::new(max_nb_conn, 10000, 16, ef_const, DistL2 {});
        let api = HnswApii32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistHamming" {
        let h = Hnsw::<i32, DistHamming>::new(max_nb_conn, 10000, 16, ef_const, DistHamming {});
        let api = HnswApii32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    }
    let p = ptr::null::<HnswApii32>();
    p
} // end of init_hnsw_i32

#[no_mangle]
pub extern "C" fn init_hnsw_ptrdist_i32(
    max_nb_conn: usize,
    ef_const: usize,
    c_func: extern "C" fn(*const i32, *const i32, c_ulonglong) -> f32,
) -> *const HnswApii32 {
    log::debug!("init_ hnsw_ptrdist: ptr  {:?}", c_func);
    let c_dist = DistCFFI::<i32>::new(c_func);
    let h = Hnsw::<i32, DistCFFI<i32>>::new(max_nb_conn, 10000, 16, ef_const, c_dist);
    let api = HnswApii32 {
        opaque: Box::new(h),
    };
    return Box::into_raw(Box::new(api));
}

//==generation of function for i32

super::declare_myapi_type!(HnswApii32, i32);

generate_insert!(insert_i32, HnswApii32, i32);
generate_parallel_insert!(parallel_insert_i32, HnswApii32, i32);
generate_search_neighbours!(search_neighbours_i32, HnswApii32, i32);
generate_parallel_search_neighbours!(parallel_search_neighbours_i32, HnswApii32, i32);
generate_file_dump!(file_dump_i32, HnswApii32, i32);

//========== generation for u32

#[no_mangle]
pub extern "C" fn init_hnsw_u32(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
) -> *const HnswApiu32 {
    log::debug!("entering init_hnsw_u32");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice);
    // map distname to sthg. This whole block will go to a macro
    if dname == "DistL1" {
        log::debug!(" received DistL1");
        let h = Hnsw::<u32, DistL1>::new(max_nb_conn, 10000, 16, ef_const, DistL1 {});
        let api = HnswApiu32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistL2" {
        let h = Hnsw::<u32, DistL2>::new(max_nb_conn, 10000, 16, ef_const, DistL2 {});
        let api = HnswApiu32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistJaccard" {
        let h = Hnsw::<u32, DistJaccard>::new(max_nb_conn, 10000, 16, ef_const, DistJaccard {});
        let api = HnswApiu32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistHamming" {
        let h = Hnsw::<u32, DistHamming>::new(max_nb_conn, 10000, 16, ef_const, DistHamming {});
        let api = HnswApiu32 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    }
    //
    let p = ptr::null::<HnswApiu32>();
    p
} // end of init_hnsw_i32

#[no_mangle]
pub extern "C" fn init_hnsw_ptrdist_u32(
    max_nb_conn: usize,
    ef_const: usize,
    c_func: extern "C" fn(*const u32, *const u32, c_ulonglong) -> f32,
) -> *const HnswApiu32 {
    log::info!("init_ hnsw_ptrdist: ptr  {:?}", c_func);
    let c_dist = DistCFFI::<u32>::new(c_func);
    let h = Hnsw::<u32, DistCFFI<u32>>::new(max_nb_conn, 10000, 16, ef_const, c_dist);
    let api = HnswApiu32 {
        opaque: Box::new(h),
    };
    return Box::into_raw(Box::new(api));
}

super::declare_myapi_type!(HnswApiu32, u32);

generate_insert!(insert_u32, HnswApiu32, u32);
generate_parallel_insert!(parallel_insert_u32, HnswApiu32, u32);
generate_search_neighbours!(search_neighbours_u32, HnswApiu32, u32);
generate_parallel_search_neighbours!(parallel_search_neighbours_u32, HnswApiu32, u32);
generate_file_dump!(file_dump_u32, HnswApiu32, u32);

//============== generation of function for u16 =====================

super::declare_myapi_type!(HnswApiu16, u16);

#[no_mangle]
pub extern "C" fn init_hnsw_u16(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
) -> *const HnswApiu16 {
    log::info!("entering init_hnsw_u16");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice);
    // map distname to sthg. This whole block will go to a macro
    if dname == "DistL1" {
        log::info!(" received DistL1");
        let h = Hnsw::<u16, DistL1>::new(max_nb_conn, 10000, 16, ef_const, DistL1 {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistL2" {
        let h = Hnsw::<u16, DistL2>::new(max_nb_conn, 10000, 16, ef_const, DistL2 {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistHamming" {
        let h = Hnsw::<u16, DistHamming>::new(max_nb_conn, 10000, 16, ef_const, DistHamming {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistJaccard" {
        let h = Hnsw::<u16, DistJaccard>::new(max_nb_conn, 10000, 16, ef_const, DistJaccard {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistLevenshtein" {
        let h =
            Hnsw::<u16, DistLevenshtein>::new(max_nb_conn, 10000, 16, ef_const, DistLevenshtein {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    }
    let p = ptr::null::<HnswApiu16>();
    p
} // end of init_hnsw_u16

#[no_mangle]
pub extern "C" fn new_hnsw_u16(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
    max_elements: usize,
    max_layer: usize,
) -> *const HnswApiu16 {
    log::info!("entering init_hnsw_u16");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice);
    // map distname to sthg. This whole block will go to a macro
    if dname == "DistL1" {
        log::info!(" received DistL1");
        let h = Hnsw::<u16, DistL1>::new(max_nb_conn, max_elements, max_layer, ef_const, DistL1 {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistL2" {
        let h = Hnsw::<u16, DistL2>::new(max_nb_conn, max_elements, max_layer, ef_const, DistL2 {});
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistHamming" {
        let h = Hnsw::<u16, DistHamming>::new(
            max_nb_conn,
            max_elements,
            max_layer,
            ef_const,
            DistHamming {},
        );
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistJaccard" {
        let h = Hnsw::<u16, DistJaccard>::new(
            max_nb_conn,
            max_elements,
            max_layer,
            ef_const,
            DistJaccard {},
        );
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistLevenshtein" {
        let h = Hnsw::<u16, DistLevenshtein>::new(
            max_nb_conn,
            max_elements,
            max_layer,
            ef_const,
            DistLevenshtein {},
        );
        let api = HnswApiu16 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    }
    let p = ptr::null::<HnswApiu16>();
    p
} // end of init_hnsw_u16

#[no_mangle]
pub extern "C" fn init_hnsw_ptrdist_u16(
    max_nb_conn: usize,
    ef_const: usize,
    c_func: extern "C" fn(*const u16, *const u16, c_ulonglong) -> f32,
) -> *const HnswApiu16 {
    log::info!("init_ hnsw_ptrdist: ptr  {:?}", c_func);
    let c_dist = DistCFFI::<u16>::new(c_func);
    let h = Hnsw::<u16, DistCFFI<u16>>::new(max_nb_conn, 10000, 16, ef_const, c_dist);
    let api = HnswApiu16 {
        opaque: Box::new(h),
    };
    return Box::into_raw(Box::new(api));
}

generate_insert!(insert_u16, HnswApiu16, u16);
generate_parallel_insert!(parallel_insert_u16, HnswApiu16, u16);
generate_search_neighbours!(search_neighbours_u16, HnswApiu16, u16);
generate_parallel_search_neighbours!(parallel_search_neighbours_u16, HnswApiu16, u16);
generate_file_dump!(file_dump_u16, HnswApiu16, u16);

//============== generation of function for u8 =====================

super::declare_myapi_type!(HnswApiu8, u8);

#[no_mangle]
pub extern "C" fn init_hnsw_u8(
    max_nb_conn: usize,
    ef_const: usize,
    namelen: usize,
    cdistname: *const u8,
) -> *const HnswApiu8 {
    log::debug!("entering init_hnsw_u8");
    let slice = unsafe { std::slice::from_raw_parts(cdistname, namelen) };
    let dname = String::from_utf8_lossy(slice);
    // map distname to sthg. This whole block will go to a macro
    if dname == "DistL1" {
        log::info!(" received DistL1");
        let h = Hnsw::<u8, DistL1>::new(max_nb_conn, 10000, 16, ef_const, DistL1 {});
        let api = HnswApiu8 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistL2" {
        let h = Hnsw::<u8, DistL2>::new(max_nb_conn, 10000, 16, ef_const, DistL2 {});
        let api = HnswApiu8 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistHamming" {
        let h = Hnsw::<u8, DistHamming>::new(max_nb_conn, 10000, 16, ef_const, DistHamming {});
        let api = HnswApiu8 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    } else if dname == "DistJaccard" {
        let h = Hnsw::<u8, DistJaccard>::new(max_nb_conn, 10000, 16, ef_const, DistJaccard {});
        let api = HnswApiu8 {
            opaque: Box::new(h),
        };
        return Box::into_raw(Box::new(api));
    }
    let p = ptr::null::<HnswApiu8>();
    p
} // end of init_hnsw_u16

#[no_mangle]
pub extern "C" fn init_hnsw_ptrdist_u8(
    max_nb_conn: usize,
    ef_const: usize,
    c_func: extern "C" fn(*const u8, *const u8, c_ulonglong) -> f32,
) -> *const HnswApiu8 {
    log::info!("init_ hnsw_ptrdist: ptr  {:?}", c_func);
    let c_dist = DistCFFI::<u8>::new(c_func);
    let h = Hnsw::<u8, DistCFFI<u8>>::new(max_nb_conn, 10000, 16, ef_const, c_dist);
    let api = HnswApiu8 {
        opaque: Box::new(h),
    };
    return Box::into_raw(Box::new(api));
}

generate_insert!(insert_u8, HnswApiu8, u8);
generate_parallel_insert!(parallel_insert_u8, HnswApiu8, u8);
generate_search_neighbours!(search_neighbours_u8, HnswApiu8, u8);
generate_parallel_search_neighbours!(parallel_search_neighbours_u8, HnswApiu8, u8);
generate_file_dump!(file_dump_u8, HnswApiu8, u8);

//=========================== dump restore functions

/// This structure provides a light description of the graph to be passed to C compatible languages.
#[repr(C)]
pub struct DescriptionFFI {
    ///  value is 1 for Full 0 for Light
    pub dumpmode: u8,
    /// max number of connections in layers != 0
    pub max_nb_connection: u8,
    /// number of observed layers
    pub nb_layer: u8,
    /// search parameter
    pub ef: usize,
    /// total number of points
    pub nb_point: usize,
    /// dimension of data vector
    pub data_dimension: usize,
    /// length and pointer on dist name
    pub distname_len: usize,
    pub distname: *const u8,
    /// T typename
    pub t_name_len: usize,
    pub t_name: *const u8,
}

impl DescriptionFFI {
    pub fn new() -> Self {
        DescriptionFFI {
            dumpmode: 0,
            max_nb_connection: 0,
            nb_layer: 0,
            ef: 0,
            nb_point: 0,
            data_dimension: 0,
            distname_len: 0,
            distname: ptr::null(),
            t_name_len: 0,
            t_name: ptr::null(),
        }
    } // end of new
}

/// returns a const pointer to a DescriptionFFI from a dump file, given filename length and pointer (*const u8)
#[no_mangle]
pub extern "C" fn load_hnsw_description(flen: usize, name: *const u8) -> *const DescriptionFFI {
    // opens file
    let slice = unsafe { std::slice::from_raw_parts(name, flen) };
    let filename = String::from_utf8_lossy(slice).into_owned();
    let fpath = PathBuf::from(filename);
    let fileres = OpenOptions::new().read(true).open(&fpath);
    //
    let mut ffi_description = DescriptionFFI::new();
    match fileres {
        Ok(file) => {
            //
            let mut bufr = BufReader::with_capacity(10000000, file);
            let res = load_description(&mut bufr);
            if let Ok(description) = res {
                let distname = String::clone(&description.distname);
                let distname_ptr = distname.as_ptr();
                let distname_len = distname.len();
                std::mem::forget(distname);

                let t_name = String::clone(&description.t_name);
                let t_name_ptr = t_name.as_ptr();
                let t_name_len = t_name.len();
                std::mem::forget(t_name);

                ffi_description.dumpmode = 1; // CAVEAT
                ffi_description.max_nb_connection = description.max_nb_connection;
                ffi_description.nb_layer = description.nb_layer;
                ffi_description.ef = description.ef;
                ffi_description.data_dimension = description.dimension;
                ffi_description.distname_len = distname_len;
                ffi_description.distname = distname_ptr;
                ffi_description.t_name_len = t_name_len;
                ffi_description.t_name = t_name_ptr;
                return Box::into_raw(Box::new(ffi_description));
            } else {
                log::error!(
                    "could not get descrption of hnsw from file {:?}",
                    fpath.as_os_str()
                );
                println!(
                    "could not get descrption of hnsw from file {:?} ",
                    fpath.as_os_str()
                );
                return ptr::null();
            }
        }
        Err(_e) => {
            log::error!(
                "no such file, load_hnsw_description: could not open file {:?}",
                fpath.as_os_str()
            );
            println!(
                "no such file, load_hnsw_description: could not open file {:?}",
                fpath.as_os_str()
            );
            return ptr::null();
        }
    }
} // end of load_hnsw_description

//============ log initialization ============//

/// to initialize rust logging from Julia
#[no_mangle]
pub extern "C" fn init_rust_log() {
    let _res = env_logger::Builder::from_default_env().try_init();
}