neopdf_capi 0.1.1

C language interface to NeoPDF
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! The C-language interface for `NeoPDF`

use std::ffi::CStr;
use std::os::raw::{c_char, c_double, c_int};
use std::slice;

use neopdf::gridpdf::GridArray;
use neopdf::metadata::{InterpolatorType, MetaData, SetType};
use neopdf::parser::SubgridData;
use neopdf::pdf::PDF;
use neopdf::writer::GridArrayCollection;

/// Result codes for `NeoPDF` operations
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NeopdfResult {
    /// Operation completed successfully.
    Success = 0,
    /// A null pointer was encountered where a valid pointer was expected.
    ErrorNullPointer = -1,
    /// The provided data was invalid or could not be processed.
    ErrorInvalidData = -2,
    /// A memory allocation or deallocation error occurred.
    ErrorMemoryError = -3,
    /// The provided length or size argument was invalid.
    ErrorInvalidLength = -4,
}

impl From<NeopdfResult> for c_int {
    fn from(result: NeopdfResult) -> Self {
        result as Self
    }
}

/// Opaque pointer to a PDF object.
pub struct NeoPDFWrapper(PDF);

/// Structure to hold an array of PDF pointers and its length.
#[repr(C)]
pub struct NeoPDFMembers {
    /// Pointers to the `NeoPDF` objects.
    pub pdfs: *mut *mut NeoPDFWrapper,
    /// The number of PDF members.
    pub size: usize,
}

/// Loads a given member of the PDF set.
///
/// # Panics
///
/// This function will panic if the provided C string is not valid UTF-8.
///
/// # Safety
///
/// The `pdf_name` C string must be null-terminated and valid UTF-8.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_load(
    pdf_name: *const c_char,
    member: usize,
) -> *mut NeoPDFWrapper {
    let c_str = unsafe { CStr::from_ptr(pdf_name) };
    let pdf_name = c_str.to_str().expect("Invalid UTF-8 string");
    let pdf = PDF::load(pdf_name, member);
    Box::into_raw(Box::new(NeoPDFWrapper(pdf)))
}

/// Loads all members of the PDF set.
///
/// Returns a `NeoPDFMembers` containing pointers to all PDF objects in the set.
/// The caller is responsible for freeing the memory using `neopdf_pdf_array_free`.
///
/// # Panics
///
/// This function will panic if the provided C string is not valid UTF-8.
///
/// # Safety
///
/// The `pdf_name` C string must be null-terminated and valid UTF-8.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_load_all(pdf_name: *const c_char) -> NeoPDFMembers {
    let c_str = unsafe { CStr::from_ptr(pdf_name) };
    let pdf_name = c_str.to_str().expect("Invalid UTF-8 string");

    let pdfs = PDF::load_pdfs(pdf_name);
    let length = pdfs.len();

    let mut pdf_pointers: Vec<*mut NeoPDFWrapper> = pdfs
        .into_iter()
        .map(|pdf| Box::into_raw(Box::new(NeoPDFWrapper(pdf))))
        .collect();

    let pdfs_ptr = pdf_pointers.as_mut_ptr();
    std::mem::forget(pdf_pointers); // Prevent Vec from being dropped

    NeoPDFMembers {
        pdfs: pdfs_ptr,
        size: length,
    }
}

/// Frees a PDF object.
///
/// # Panics
///
/// This function does not panic.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object previously
/// allocated by `neopdf_pdf_load`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_free(pdf: *mut NeoPDFWrapper) {
    if pdf.is_null() {
        return;
    }
    unsafe { drop(Box::from_raw(pdf)) };
}

/// Frees the memory allocated for a `NeoPDFMembers`.
///
/// # Safety
///
/// The `array` must be a valid `NeoPDFMembers` returned by `neopdf_pdf_load_all`.
/// After calling this function, the array and all PDF objects it contains
/// become invalid and must not be used.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_array_free(array: NeoPDFMembers) {
    if array.pdfs.is_null() {
        return;
    }

    let pdf_pointers = unsafe { Vec::from_raw_parts(array.pdfs, array.size, array.size) };

    for pdf_ptr in pdf_pointers {
        if !pdf_ptr.is_null() {
            unsafe { drop(Box::from_raw(pdf_ptr)) };
        }
    }
}

/// Retrieves the `x_min` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_x_min(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().x.min
}

/// Retrieves the `x_max` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_x_max(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().x.max
}

/// Retrieves the `q2_min` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_q2_min(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().q2.min
}

/// Retrieves the `q2_max` for this PDF set.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_q2_max(pdf: *mut NeoPDFWrapper) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.param_ranges().q2.max
}

/// Interpolates the PDF value (xf) for a given flavor, x, and Q2.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2(
    pdf: *mut NeoPDFWrapper,
    id: i32,
    x: f64,
    q2: f64,
) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.xfxq2(id, &[x, q2])
}

/// Interpolates the PDF value (xf) for a generic set of parameters.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_xfxq2_nd(
    pdf: *mut NeoPDFWrapper,
    id: i32,
    params: *mut f64,
    num_params: usize,
) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    let params = unsafe { slice::from_raw_parts(params, num_params) };

    pdf_obj.xfxq2(id, params)
}

/// Computes the `alpha_s` value at a given Q2.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_alphas_q2(pdf: *mut NeoPDFWrapper, q2: f64) -> f64 {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.alphas_q2(q2)
}

/// Returns the number of PIDs.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_num_pids(pdf: *mut NeoPDFWrapper) -> usize {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.pids().len()
}

/// Returns the PID representation of the PDF Grid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object, and the `pids` pointer must be valid for writing `num_pids` elements.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_pids(pdf: *mut NeoPDFWrapper, pids: *mut i32, num_pids: usize) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let pids = unsafe { slice::from_raw_parts_mut(pids, num_pids) };
    let pid_values = pdf_obj.pids();

    pids.copy_from_slice(pid_values.as_slice().unwrap());
}

/// Parameters for subgrids in the PDF grid.
#[repr(C)]
pub enum NeopdfSubgridParams {
    /// Parameters for subgrids in the PDF grid.
    Nucleons,
    /// The strong coupling constant (`alpha_s`) parameter.
    Alphas,
    /// The transverse momentum `kT` parameter.
    Kt,
    /// The momentum fraction (x) parameter.
    Momentum,
    /// The energy scale (Q^2) parameter.
    Scale,
}

/// Returns the number of subgrids in the PDF Grid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_num_subgrids(pdf: *mut NeoPDFWrapper) -> usize {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };
    pdf_obj.num_subgrids()
}

/// Returns the minimum and maximum value for a given parameter.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object, and the `param_range` pointer must be valid for writing two `f64` values.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_param_range(
    pdf: *mut NeoPDFWrapper,
    param: NeopdfSubgridParams,
    param_range: *mut f64,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let param_range = unsafe { slice::from_raw_parts_mut(param_range, 2) };
    let range_params = match param {
        NeopdfSubgridParams::Nucleons => &[
            pdf_obj.param_ranges().nucleons.min,
            pdf_obj.param_ranges().nucleons.max,
        ],
        NeopdfSubgridParams::Alphas => &[
            pdf_obj.param_ranges().alphas.min,
            pdf_obj.param_ranges().alphas.max,
        ],
        NeopdfSubgridParams::Kt => &[pdf_obj.param_ranges().kt.min, pdf_obj.param_ranges().kt.max],
        NeopdfSubgridParams::Momentum => {
            &[pdf_obj.param_ranges().x.min, pdf_obj.param_ranges().x.max]
        }
        NeopdfSubgridParams::Scale => {
            &[pdf_obj.param_ranges().q2.min, pdf_obj.param_ranges().q2.max]
        }
    };

    param_range.copy_from_slice(range_params);
}

/// Returns the shape of the subgrids in the order of their index for a given parameter.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object, and the `subgrid_shape` pointer must be valid for writing `num_subgrid` elements.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_subgrids_shape_for_param(
    pdf: *mut NeoPDFWrapper,
    subgrid_shape: *mut usize,
    num_subgrid: usize,
    subgrid_param: NeopdfSubgridParams,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let subgrid_shape = unsafe { slice::from_raw_parts_mut(subgrid_shape, num_subgrid) };
    let shape_subgrids: Vec<usize> = pdf_obj
        .subgrids()
        .iter()
        .map(|sub| match subgrid_param {
            NeopdfSubgridParams::Nucleons => sub.nucleons.len(),
            NeopdfSubgridParams::Alphas => sub.alphas.len(),
            NeopdfSubgridParams::Kt => sub.kts.len(),
            NeopdfSubgridParams::Momentum => sub.xs.len(),
            NeopdfSubgridParams::Scale => sub.q2s.len(),
        })
        .collect();

    subgrid_shape.copy_from_slice(&shape_subgrids);
}

/// Returns the grid values of a parameter for a given subgrid.
///
/// # Panics
///
/// This function will panic if the `pdf` pointer is null.
///
/// # Safety
///
/// The `pdf` pointer must be a valid pointer to a `NeoPDF` object. The `subgrid` pointer must be valid for writing the number of elements specified by `subgrid_shape[subgrid_index]`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_pdf_subgrids_for_param(
    pdf: *mut NeoPDFWrapper,
    subgrid: *mut f64,
    subgrid_param: NeopdfSubgridParams,
    num_subgrid: usize,
    subgrid_shape: *mut usize,
    subgrid_index: usize,
) {
    assert!(!pdf.is_null());
    let pdf_obj = unsafe { &(*pdf).0 };

    let subgrid_shape = unsafe { slice::from_raw_parts(subgrid_shape, num_subgrid) };
    let subgrid = unsafe { slice::from_raw_parts_mut(subgrid, subgrid_shape[subgrid_index]) };
    let subgrid_knots = match subgrid_param {
        NeopdfSubgridParams::Nucleons => &pdf_obj.subgrids()[subgrid_index].nucleons,
        NeopdfSubgridParams::Alphas => &pdf_obj.subgrids()[subgrid_index].alphas,
        NeopdfSubgridParams::Kt => &pdf_obj.subgrids()[subgrid_index].kts,
        NeopdfSubgridParams::Momentum => &pdf_obj.subgrids()[subgrid_index].xs,
        NeopdfSubgridParams::Scale => &pdf_obj.subgrids()[subgrid_index].q2s,
    };

    subgrid.copy_from_slice(subgrid_knots.as_slice().unwrap());
}

/// An opaque struct holding the data for a single grid, including its subgrids and flavors.
/// C code should not access its fields directly.
pub struct NeoPDFGrid {
    subgrids: Vec<SubgridData>,
    flavors: Vec<i32>,
}

impl NeoPDFGrid {
    /// Creates a new, empty grid
    const fn new() -> Self {
        Self {
            subgrids: Vec::new(),
            flavors: Vec::new(),
        }
    }

    /// Adds a subgrid to the grid
    #[allow(clippy::too_many_arguments)]
    unsafe fn add_subgrid(
        &mut self,
        nucleons: *const c_double,
        num_nucleons: usize,
        alphas: *const c_double,
        num_alphas: usize,
        kts: *const c_double,
        num_kts: usize,
        xs: *const c_double,
        num_xs: usize,
        q2s: *const c_double,
        num_q2s: usize,
        grid_data: *const c_double,
        grid_data_len: usize,
    ) -> NeopdfResult {
        // Check for null pointers
        if nucleons.is_null()
            || alphas.is_null()
            || kts.is_null()
            || xs.is_null()
            || q2s.is_null()
            || grid_data.is_null()
        {
            return NeopdfResult::ErrorNullPointer;
        }

        let subgrid = unsafe {
            SubgridData {
                nucleons: slice::from_raw_parts(nucleons, num_nucleons).to_vec(),
                alphas: slice::from_raw_parts(alphas, num_alphas).to_vec(),
                kts: slice::from_raw_parts(kts, num_kts).to_vec(),
                xs: slice::from_raw_parts(xs, num_xs).to_vec(),
                q2s: slice::from_raw_parts(q2s, num_q2s).to_vec(),
                grid_data: slice::from_raw_parts(grid_data, grid_data_len).to_vec(),
            }
        };
        self.subgrids.push(subgrid);

        NeopdfResult::Success
    }

    /// Sets the flavor IDs for the grid
    unsafe fn set_flavors(&mut self, flavors: *const c_int, num_flavors: usize) -> NeopdfResult {
        if flavors.is_null() {
            return NeopdfResult::ErrorNullPointer;
        }
        self.flavors = unsafe { slice::from_raw_parts(flavors, num_flavors).to_vec() };

        NeopdfResult::Success
    }
}

/// Creates a new, empty `NeoPDFGrid`.
/// The caller is responsible for freeing the returned grid using `neopdf_grid_free`.
#[no_mangle]
pub extern "C" fn neopdf_grid_new() -> *mut NeoPDFGrid {
    Box::into_raw(Box::new(NeoPDFGrid::new()))
}

/// Adds a subgrid to an existing `NeoPDFGrid`.
/// This function takes ownership of the provided data arrays and resizes them as needed.
///
/// # Safety
/// - `grid` must be a valid pointer to a `NeoPDFGrid` created by `neopdf_grid_new`.
/// - The data pointers must be valid for the specified lengths.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_add_subgrid(
    grid: *mut NeoPDFGrid,
    nucleons: *const c_double,
    num_nucleons: usize,
    alphas: *const c_double,
    num_alphas: usize,
    kts: *const c_double,
    num_kts: usize,
    xs: *const c_double,
    num_xs: usize,
    q2s: *const c_double,
    num_q2s: usize,
    grid_data: *const c_double,
    grid_data_len: usize,
) -> NeopdfResult {
    unsafe {
        grid.as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |grid| {
                grid.add_subgrid(
                    nucleons,
                    num_nucleons,
                    alphas,
                    num_alphas,
                    kts,
                    num_kts,
                    xs,
                    num_xs,
                    q2s,
                    num_q2s,
                    grid_data,
                    grid_data_len,
                )
            })
    }
}

/// Sets the flavor IDs for a `NeoPDFGrid`.
///
/// # Safety
/// - `grid` must be a valid pointer to a `NeoPDFGrid`.
/// - `flavors` must be a valid pointer to an array of integers of size `num_flavors`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_set_flavors(
    grid: *mut NeoPDFGrid,
    flavors: *const c_int,
    num_flavors: usize,
) -> NeopdfResult {
    unsafe {
        grid.as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |grid| {
                grid.set_flavors(flavors, num_flavors)
            })
    }
}

/// Frees the memory allocated for a `NeoPDFGrid`.
///
/// # Safety
/// `grid` must be a valid pointer to a `NeoPDFGrid` created by `neopdf_grid_new`.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_free(grid: *mut NeoPDFGrid) {
    if !grid.is_null() {
        unsafe { drop(Box::from_raw(grid)) };
    }
}

/// Physical Parameters of the PDF set.
#[repr(C)]
pub struct NeoPDFPhysicsParameters {
    /// The flavor scheme used for the PDF set.
    pub flavor_scheme: *const c_char,
    /// Number of QCD loops in the calculation of PDF evolution.
    pub order_qcd: u32,
    /// Number of QCD loops in the calculation of `alpha_s`.
    pub alphas_order_qcd: u32,
    /// Value of the W boson mass.
    pub m_w: f64,
    /// Value of the Z boson mass.
    pub m_z: f64,
    /// Value of the `u` quark mass.
    pub m_up: f64,
    /// Value of the `d` quark mass.
    pub m_down: f64,
    /// Value of the `s` quark mass.
    pub m_strange: f64,
    /// Value of the `c` quark mass.
    pub m_charm: f64,
    /// Value of the `b` quark mass.
    pub m_bottom: f64,
    /// Value of the `t` quark mass.
    pub m_top: f64,
}

/// Metadata for PDF grids
#[repr(C)]
pub struct NeoPDFMetaData {
    set_desc: *const c_char,
    set_index: u32,
    num_members: u32,
    x_min: c_double,
    x_max: c_double,
    q_min: c_double,
    q_max: c_double,
    flavors: *const c_int,
    num_flavors: usize,
    format: *const c_char,
    alphas_q_values: *const c_double,
    num_alphas_q: usize,
    alphas_vals: *const c_double,
    num_alphas_vals: usize,
    polarised: bool,
    set_type: SetType,
    interpolator_type: InterpolatorType,
    error_type: *const c_char,
    hadron_pid: c_int,
    phys_params: NeoPDFPhysicsParameters,
}

/// Safely converts C string to Rust string
unsafe fn cstr_to_string(ptr: *const c_char) -> Option<String> {
    if ptr.is_null() {
        None
    } else {
        unsafe { Some(CStr::from_ptr(ptr).to_string_lossy().into_owned()) }
    }
}

/// Safely converts C array to Rust Vec
unsafe fn carray_to_vec<T: Copy>(ptr: *const T, len: usize) -> Option<Vec<T>> {
    if ptr.is_null() {
        None
    } else {
        unsafe { Some(slice::from_raw_parts(ptr, len).to_vec()) }
    }
}

/// Processes metadata from C struct to Rust struct
fn process_metadata(meta: *const NeoPDFMetaData) -> Option<MetaData> {
    if meta.is_null() {
        return None;
    }

    let meta = unsafe { &*meta };

    // Use helper functions for safer conversions
    let set_desc = unsafe { cstr_to_string(meta.set_desc) }?;
    let format = unsafe { cstr_to_string(meta.format) }?;
    let flavors = unsafe { carray_to_vec(meta.flavors, meta.num_flavors) }?;
    let alphas_q_values = unsafe { carray_to_vec(meta.alphas_q_values, meta.num_alphas_q) }?;
    let alphas_vals = unsafe { carray_to_vec(meta.alphas_vals, meta.num_alphas_vals) }?;
    let error_type = unsafe { cstr_to_string(meta.error_type) }?;
    let flavor_scheme = unsafe { cstr_to_string(meta.phys_params.flavor_scheme) }?;

    let metadata = MetaData {
        set_desc,
        set_index: meta.set_index,
        num_members: meta.num_members,
        x_min: meta.x_min,
        x_max: meta.x_max,
        q_min: meta.q_min,
        q_max: meta.q_max,
        flavors,
        format,
        alphas_q_values,
        alphas_vals,
        polarised: meta.polarised,
        set_type: meta.set_type.clone(),
        interpolator_type: meta.interpolator_type.clone(),
        error_type,
        hadron_pid: meta.hadron_pid,
        git_version: String::new(),  // placeholder to be overwritten
        code_version: String::new(), // placeholder to be overwritten
        flavor_scheme,
        order_qcd: meta.phys_params.order_qcd,
        alphas_order_qcd: meta.phys_params.alphas_order_qcd,
        m_w: meta.phys_params.m_w,
        m_z: meta.phys_params.m_z,
        m_up: meta.phys_params.m_up,
        m_down: meta.phys_params.m_down,
        m_strange: meta.phys_params.m_strange,
        m_charm: meta.phys_params.m_charm,
        m_bottom: meta.phys_params.m_bottom,
        m_top: meta.phys_params.m_top,
    };

    Some(metadata)
}

/// Represents a dynamically-sized collection of `NeoPDFGrid` pointers.
/// This struct is exposed to C and manages memory for the array of pointers.
#[repr(C)]
pub struct NeoPDFGridArrayCollection {
    /// A raw pointer to a C-style array of `NeoPDFGrid` pointers.
    /// This array holds the pointers to the individual grids added to the collection.
    grids: *mut *mut NeoPDFGrid,
    /// The current number of `NeoPDFGrid` pointers stored in the `grids` array.
    num_grids: usize,
    /// The total allocated capacity of the `grids` array.
    /// When `num_grids` reaches `capacity`, the array is reallocated to a larger size.
    capacity: usize,
}

impl NeoPDFGridArrayCollection {
    /// Creates a new, empty `NeoPDFGridArrayCollection`.
    /// Initializes the collection with no grids and zero capacity.
    const fn new() -> Self {
        Self {
            grids: std::ptr::null_mut(),
            num_grids: 0,
            capacity: 0,
        }
    }

    /// Adds a `NeoPDFGrid` pointer to the collection.
    /// This function handles dynamic resizing of the underlying array if needed.
    ///
    /// # Arguments
    /// * `grid` - A raw pointer to the `NeoPDFGrid` to be added.
    ///
    /// # Returns
    /// `NeoPDFResult::Success` if the grid was added successfully, or an error code
    /// (`ErrorNullPointer`, `ErrorMemoryError`) if an issue occurred.
    fn add_grid(&mut self, grid: *mut NeoPDFGrid) -> NeopdfResult {
        // Ensure the provided grid pointer is not null.
        if grid.is_null() {
            return NeopdfResult::ErrorNullPointer;
        }

        // Check if the current number of grids has reached the allocated capacity.
        // If so, resize the underlying array.
        if self.num_grids == self.capacity {
            // Determine the new capacity: double it if not zero, otherwise start with 4.
            let new_capacity = if self.capacity == 0 {
                4
            } else {
                self.capacity * 2
            };

            // Allocate new memory for the array of grid pointers.
            // If `grids` is null (first allocation), use `alloc`; otherwise, use `realloc`.
            let new_ptr = if self.grids.is_null() {
                unsafe {
                    // Allocate memory for `new_capacity` number of `*mut NeoPDFGrid`.
                    std::alloc::alloc(
                        std::alloc::Layout::array::<*mut NeoPDFGrid>(new_capacity).unwrap(),
                    )
                    // TODO: Would using `libc` better? See commit `54b3044`.
                    .cast::<()>()
                    .cast::<*mut NeoPDFGrid>()
                }
            } else {
                unsafe {
                    // Reallocate existing memory to `new_capacity`.
                    // The old pointer is cast to `u8` for `realloc`.
                    std::alloc::realloc(
                        self.grids.cast::<u8>(),
                        std::alloc::Layout::array::<*mut NeoPDFGrid>(self.capacity).unwrap(),
                        new_capacity * std::mem::size_of::<*mut NeoPDFGrid>(),
                    )
                    // TODO: Would using `libc` better? See commit `54b3044`.
                    .cast::<()>()
                    .cast::<*mut NeoPDFGrid>()
                }
            };

            // Check if reallocation failed (returned null).
            if new_ptr.is_null() {
                return NeopdfResult::ErrorMemoryError;
            }

            // Update the collection's pointer and capacity to the new allocation.
            self.grids = new_ptr;
            self.capacity = new_capacity;
        }

        // Add the new grid pointer to the end of the array.
        unsafe {
            *self.grids.add(self.num_grids) = grid;
        }
        // Increment the count of grids in the collection.
        self.num_grids += 1;

        NeopdfResult::Success
    }

    /// Returns the number of grids currently in the collection.
    const fn len(&self) -> usize {
        self.num_grids
    }

    /// Retrieves a reference to the `NeoPDFGrid` at the specified index.
    ///
    /// # Arguments
    /// * `index` - The zero-based index of the grid to retrieve.
    ///
    /// # Returns
    /// An `Option<&NeoPDFGrid>`: `Some` if the index is valid, `None` otherwise.
    fn get(&self, index: usize) -> Option<&NeoPDFGrid> {
        // Check for out-of-bounds access.
        if index >= self.num_grids {
            return None;
        }
        // Dereference the raw pointer at the given index to get a reference to NeoPDFGrid.
        unsafe { (*self.grids.add(index)).as_ref() }
    }
}

impl Drop for NeoPDFGridArrayCollection {
    fn drop(&mut self) {
        if self.grids.is_null() {
            return;
        }
        // Free each individual grid in the collection
        let grids_slice = unsafe { slice::from_raw_parts(self.grids, self.num_grids) };
        for &grid_ptr in grids_slice {
            if !grid_ptr.is_null() {
                // Re-Box the raw pointer and let it drop, freeing the memory
                unsafe { drop(Box::from_raw(grid_ptr)) };
            }
        }

        // Deallocate the memory for the pointer array itself
        unsafe {
            std::alloc::dealloc(
                self.grids.cast::<u8>(),
                std::alloc::Layout::array::<*mut NeoPDFGrid>(self.capacity).unwrap(),
            );
        }
    }
}

/// Creates a new, empty `NeoPDFGridArrayCollection`.
///
/// # Safety
/// The caller is responsible for freeing the returned collection using
/// `neopdf_gridarray_collection_free` to prevent memory leaks.
#[no_mangle]
pub extern "C" fn neopdf_gridarray_collection_new() -> *mut NeoPDFGridArrayCollection {
    // Allocate a new `NeoPDFGridArrayCollection` on the heap and return a raw pointer to it.
    Box::into_raw(Box::new(NeoPDFGridArrayCollection::new()))
}

/// Adds a `NeoPDFGrid` to a `NeoPDFGridArrayCollection`.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`.
/// - `grid` must be a valid, non-null pointer to a `NeoPDFGrid`.
/// - The `grid` pointer is taken ownership of by the collection; it should not be freed separately
///   until the collection itself is freed or the grid is removed from the collection.
#[no_mangle]
pub unsafe extern "C" fn neopdf_gridarray_collection_add_grid(
    collection: *mut NeoPDFGridArrayCollection,
    grid: *mut NeoPDFGrid,
) -> NeopdfResult {
    // Convert the raw `collection` pointer to a mutable reference.
    // This is unsafe because the pointer could be null or invalid.
    unsafe {
        collection
            .as_mut()
            .map_or(NeopdfResult::ErrorNullPointer, |collection| {
                // Call the safe `add_grid` method on the Rust struct.
                collection.add_grid(grid)
            })
    }
}

/// Frees the memory of a `NeoPDFGridArrayCollection` and all the grids it contains.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`
///   that was previously created by `neopdf_gridarray_collection_new`.
/// - After this call, the `collection` pointer and all grids it contained become invalid
///   and should not be used.
#[no_mangle]
pub unsafe extern "C" fn neopdf_gridarray_collection_free(
    collection: *mut NeoPDFGridArrayCollection,
) {
    if !collection.is_null() {
        // This will call the `Drop` implementation for `NeoPDFGridArrayCollection`
        unsafe { drop(Box::from_raw(collection)) };
    }
}

/// Compresses a collection of `NeoPDFGrid` objects and writes them to a file.
///
/// This function iterates through the grids in the collection, converts them to `GridArray`s,
/// and then uses the `neopdf::writer::GridArrayCollection::compress` function to write them.
///
/// # Safety
/// - `collection` must be a valid, non-null pointer to a `NeoPDFGridArrayCollection`.
/// - `metadata` must be a valid, non-null pointer to a `NeoPDFMetaData` struct.
/// - `output_path` must be a valid, null-terminated C string representing the output file path.
#[no_mangle]
pub unsafe extern "C" fn neopdf_grid_compress(
    collection: *const NeoPDFGridArrayCollection,
    metadata: *const NeoPDFMetaData,
    output_path: *const c_char,
) -> NeopdfResult {
    // Perform null pointer checks for all input arguments.
    if collection.is_null() || metadata.is_null() || output_path.is_null() {
        return NeopdfResult::ErrorNullPointer;
    }

    // Convert the raw `collection` pointer to an immutable reference.
    // This is unsafe as the pointer could be invalid.
    let collection = unsafe { &*collection };

    // Process the C-style `metadata` struct into a Rust `MetaData` struct.
    // If processing fails (e.g., due to invalid C strings), return an error.
    let Some(meta) = process_metadata(metadata) else {
        return NeopdfResult::ErrorInvalidData;
    };

    // Convert the C-style `output_path` string to a Rust string slice.
    // Check for valid UTF-8 conversion.
    let out_path = unsafe { CStr::from_ptr(output_path).to_str() };
    let Ok(out_path) = out_path else {
        return NeopdfResult::ErrorInvalidData;
    };

    // Create a `Vec` to hold `GridArray` objects, pre-allocating capacity for efficiency.
    let mut grid_arrays = Vec::with_capacity(collection.len());

    // Iterate through each `NeoPDFGrid` pointer in the collection.
    for i in 0..collection.len() {
        // Retrieve a reference to the `NeoPDFGrid` at the current index.
        // If retrieval fails (e.g., invalid index), return an error.
        let Some(grid) = collection.get(i) else {
            return NeopdfResult::ErrorInvalidData;
        };

        // Create a `GridArray` from the `NeoPDFGrid`'s internal `subgrids` and `flavors`.
        // `clone()` is used here to create owned copies of the `Vec` data.
        let grid_array = GridArray::new(grid.subgrids.clone(), grid.flavors.clone());
        // Add the newly created `GridArray` to the `grid_arrays` vector.
        grid_arrays.push(grid_array);
    }

    // Create a vector of references to the `GridArray` objects.
    // This is required by the `compress` function's signature.
    let grid_refs: Vec<&GridArray> = grid_arrays.iter().collect();

    // Call the `compress` function from the `neopdf::writer` module.
    // Map the `Result` to `NeoPDFResult`.
    match GridArrayCollection::compress(&grid_refs, &meta, out_path) {
        Ok(()) => NeopdfResult::Success,
        Err(_) => NeopdfResult::ErrorMemoryError,
    }
}