netcdf 0.7.0

High-level NetCDF bindings for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
//! Variables in the netcdf file

#![allow(clippy::similar_names)]
use super::attribute::AttrValue;
use super::attribute::Attribute;
use super::dimension::Dimension;
use super::error;
use super::types::VariableType;
#[cfg(feature = "ndarray")]
use ndarray::ArrayD;
use netcdf_sys::*;
use std::convert::TryInto;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::marker::Sized;

#[allow(clippy::doc_markdown)]
/// This struct defines a `netCDF` variable.
#[derive(Debug, Clone)]
pub struct Variable<'g> {
    /// The variable name
    pub(crate) dimensions: Vec<Dimension<'g>>,
    /// the `netCDF` variable type identifier (from netcdf-sys)
    pub(crate) vartype: nc_type,
    pub(crate) ncid: nc_type,
    pub(crate) varid: nc_type,
    pub(crate) _group: PhantomData<&'g nc_type>,
}

#[derive(Debug)]
/// Mutable access to a variable.
#[allow(clippy::module_name_repetitions)]
pub struct VariableMut<'g>(
    pub(crate) Variable<'g>,
    pub(crate) PhantomData<&'g mut nc_type>,
);

impl<'g> std::ops::Deref for VariableMut<'g> {
    type Target = Variable<'g>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Enum for variables endianness
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Endianness {
    /// Native endianness, depends on machine architecture (x86_64 is Little)
    Native,
    /// Lille endian
    Little,
    /// Big endian
    Big,
}

#[allow(clippy::len_without_is_empty)]
impl<'g> Variable<'g> {
    pub(crate) fn find_from_name(ncid: nc_type, name: &str) -> error::Result<Option<Variable<'g>>> {
        let cname = super::utils::short_name_to_bytes(name)?;
        let mut varid = 0;
        let e =
            unsafe { super::with_lock(|| nc_inq_varid(ncid, cname.as_ptr().cast(), &mut varid)) };
        if e == NC_ENOTVAR {
            return Ok(None);
        }
        error::checked(e)?;

        let mut xtype = 0;
        let mut ndims = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_var(
                    ncid,
                    varid,
                    std::ptr::null_mut(),
                    &mut xtype,
                    &mut ndims,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                )
            }))?;
        }
        let mut dimids = vec![0; ndims.try_into()?];
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_vardimid(ncid, varid, dimids.as_mut_ptr())
            }))?;
        }
        let dimensions = super::dimension::dimensions_from_variable(ncid, varid)?
            .collect::<error::Result<Vec<_>>>()?;

        Ok(Some(Variable {
            dimensions,
            ncid,
            varid,
            vartype: xtype,
            _group: PhantomData,
        }))
    }

    /// Get name of variable
    pub fn name(&self) -> String {
        let mut name = vec![0_u8; NC_MAX_NAME as usize + 1];
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_varname(self.ncid, self.varid, name.as_mut_ptr().cast())
            }))
            .unwrap();
        }
        let zeropos = name.iter().position(|&x| x == 0).unwrap_or(name.len());
        name.resize(zeropos, 0);

        String::from_utf8(name).expect("Variable name contained invalid sequence")
    }
    /// Get an attribute of this variable
    pub fn attribute<'a>(&'a self, name: &str) -> Option<Attribute<'a>> {
        // Need to lock when reading the first attribute (per variable)
        Attribute::find_from_name(self.ncid, Some(self.varid), name)
            .expect("Could not retrieve attribute")
    }
    /// Iterator over all the attributes of this variable
    pub fn attributes(&self) -> impl Iterator<Item = Attribute> {
        // Need to lock when reading the first attribute (per variable)
        crate::attribute::AttributeIterator::new(self.ncid, Some(self.varid))
            .expect("Could not get attributes")
            .map(Result::unwrap)
    }
    /// Dimensions for a variable
    pub fn dimensions(&self) -> &[Dimension] {
        &self.dimensions
    }
    /// Get the type of this variable
    pub fn vartype(&self) -> VariableType {
        VariableType::from_id(self.ncid, self.vartype).unwrap()
    }
    /// Get current length of the variable
    pub fn len(&self) -> usize {
        self.dimensions.iter().map(Dimension::len).product()
    }
    /// Get endianness of the variable.
    ///
    /// # Errors
    ///
    /// Not a `netCDF-4` file
    pub fn endian_value(&self) -> error::Result<Endianness> {
        let mut e: nc_type = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_var_endian(self.ncid, self.varid, &mut e)
            }))?;
        }
        match e {
            NC_ENDIAN_NATIVE => Ok(Endianness::Native),
            NC_ENDIAN_LITTLE => Ok(Endianness::Little),
            NC_ENDIAN_BIG => Ok(Endianness::Big),
            _ => Err(NC_EVARMETA.into()),
        }
    }
}
impl<'g> VariableMut<'g> {
    /// Sets compression on the variable. Must be set before filling in data.
    ///
    /// `deflate_level` can take a value 0..=9, with 0 being no
    /// compression (good for CPU bound tasks), and 9 providing the
    /// highest compression level (good for memory bound tasks)
    ///
    /// # Errors
    ///
    /// Not a `netcdf-4` file or `deflate_level` not valid
    pub fn compression(&mut self, deflate_level: nc_type) -> error::Result<()> {
        unsafe {
            error::checked(super::with_lock(|| {
                nc_def_var_deflate(self.ncid, self.varid, false as _, true as _, deflate_level)
            }))?;
        }

        Ok(())
    }

    /// Set chunking for variable. Must be set before inserting data
    ///
    /// Use this when reading or writing smaller units of the hypercube than
    /// the full dimensions lengths, to change how the variable is stored in
    /// the file. This has no effect on the memory order when reading/putting
    /// a buffer.
    ///
    /// # Errors
    ///
    /// Not a `netCDF-4` file or invalid chunksize
    pub fn chunking(&mut self, chunksize: &[usize]) -> error::Result<()> {
        if self.dimensions.is_empty() {
            // Can't really set chunking, would lead to segfault
            return Ok(());
        }
        if chunksize.len() != self.dimensions.len() {
            return Err(error::Error::SliceLen);
        }
        let len = chunksize
            .iter()
            .fold(1_usize, |acc, &x| acc.saturating_mul(x));
        if len == usize::max_value() {
            return Err(error::Error::Overflow);
        }
        unsafe {
            error::checked(super::with_lock(|| {
                nc_def_var_chunking(self.ncid, self.varid, NC_CHUNKED, chunksize.as_ptr())
            }))?;
        }

        Ok(())
    }
}

impl<'g> Variable<'g> {
    /// Checks for array mismatch
    fn check_indices(&self, indices: &[usize], putting: bool) -> error::Result<()> {
        if indices.len() != self.dimensions.len() {
            return Err(error::Error::IndexLen);
        }

        for (d, i) in self.dimensions.iter().zip(indices) {
            if d.is_unlimited() && putting {
                continue;
            }
            if *i > d.len() {
                return Err(error::Error::IndexMismatch);
            }
        }

        Ok(())
    }
    /// Create a default [0, 0, ..., 0] offset
    fn default_indices(&self, putting: bool) -> error::Result<Vec<usize>> {
        self.dimensions
            .iter()
            .map(|d| {
                if d.len() > 0 || putting {
                    Ok(0)
                } else {
                    Err(error::Error::IndexMismatch)
                }
            })
            .collect()
    }

    /// Assumes indices is valid for this variable
    fn check_sizelen(
        &self,
        totallen: usize,
        indices: &[usize],
        sizelen: &[usize],
        putting: bool,
    ) -> error::Result<()> {
        if sizelen.len() != self.dimensions.len() {
            return Err(error::Error::SliceLen);
        }

        for ((i, s), d) in indices.iter().zip(sizelen).zip(&self.dimensions) {
            if *s == 0 {
                return Err(error::Error::ZeroSlice);
            }
            if i.checked_add(*s).is_none() {
                return Err(error::Error::Overflow);
            }
            if i + s > d.len() {
                if !putting {
                    return Err(error::Error::SliceMismatch);
                }
                if !d.is_unlimited() {
                    return Err(error::Error::SliceMismatch);
                }
            }
        }

        let thislen = sizelen
            .iter()
            .fold(1_usize, |acc, &x| acc.saturating_mul(x));
        if thislen == usize::max_value() {
            return Err(error::Error::Overflow);
        }

        if totallen != thislen {
            return Err(error::Error::BufferLen(totallen, thislen));
        }

        Ok(())
    }

    /// Assumes indices is valid for this variable
    fn default_sizelen(
        &self,
        totallen: usize,
        indices: &[usize],
        putting: bool,
    ) -> error::Result<Vec<usize>> {
        let num_unlims = self
            .dimensions
            .iter()
            .fold(0, |acc, x| acc + usize::from(x.is_unlimited()));
        if num_unlims > 1 {
            return Err(error::Error::Ambiguous);
        }

        let mut sizelen = Vec::with_capacity(self.dimensions.len());

        let mut unlim_pos = None;
        for (pos, (&i, d)) in indices.iter().zip(&self.dimensions).enumerate() {
            if i >= d.len() {
                if !d.is_unlimited() {
                    return Err(error::Error::SliceMismatch);
                }
                if !putting {
                    return Err(error::Error::SliceMismatch);
                }
                unlim_pos = Some(pos);
                sizelen.push(1);
            } else if putting && d.is_unlimited() {
                unlim_pos = Some(pos);
                sizelen.push(1);
            } else {
                sizelen.push(d.len() - i);
            }
        }

        if let Some(pos) = unlim_pos {
            let l = sizelen
                .iter()
                .fold(1_usize, |acc, &x| acc.saturating_mul(x));
            if l == usize::max_value() {
                return Err(error::Error::Overflow);
            }
            sizelen[pos] = totallen / l;
        }

        let wantedlen = sizelen
            .iter()
            .fold(1_usize, |acc, &x| acc.saturating_mul(x));
        if wantedlen == usize::max_value() {
            return Err(error::Error::Overflow);
        }
        if totallen != wantedlen {
            return Err(error::Error::BufferLen(totallen, wantedlen));
        }
        Ok(sizelen)
    }
}

#[allow(clippy::doc_markdown)]
/// This trait allow an implicit cast when fetching
/// a netCDF variable. These methods are not be called
/// directly, but used through methods on `Variable`
///
/// # Safety
/// This trait maps directly to netCDF semantics and needs
/// to upheld invariants therein.
pub unsafe trait Numeric
where
    Self: Sized,
{
    /// Constant corresponding to a netcdf type
    const NCTYPE: nc_type;

    /// Returns a single indexed value of the variable as Self
    ///
    /// # Safety
    ///
    /// Requires `indices` to be of a valid length
    unsafe fn single_value_from_variable(
        variable: &Variable,
        indices: &[usize],
    ) -> error::Result<Self>;

    /// Get multiple values at once, without checking the validity of
    /// `indices` or `slice_len`
    ///
    /// # Safety
    ///
    /// Requires `values` to be of at least size `slice_len.product()`,
    /// `indices` and `slice_len` to be of a valid length
    unsafe fn variable_to_ptr(
        variable: &Variable,
        indices: &[usize],
        slice_len: &[usize],
        values: *mut Self,
    ) -> error::Result<()>;

    #[allow(clippy::doc_markdown)]
    /// Put a single value into a netCDF variable
    ///
    /// # Safety
    ///
    /// Requires `indices` to be of a valid length
    unsafe fn put_value_at(
        variable: &mut VariableMut,
        indices: &[usize],
        value: Self,
    ) -> error::Result<()>;

    #[allow(clippy::doc_markdown)]
    /// put a SLICE of values into a netCDF variable at the given index
    ///
    /// # Safety
    ///
    /// Requires `indices` and `slice_len` to be of a valid length
    unsafe fn put_values_at(
        variable: &mut VariableMut,
        indices: &[usize],
        slice_len: &[usize],
        values: &[Self],
    ) -> error::Result<()>;

    /// get a SLICE of values into the variable, with the source
    /// strided by `strides`
    ///
    /// # Safety
    ///
    /// `values` must contain space for all the data,
    /// `indices`, `slice_len`, and `strides` must be of
    /// at least dimension length size.
    unsafe fn get_values_strided(
        variable: &Variable,
        indices: &[usize],
        slice_len: &[usize],
        strides: &[isize],
        values: *mut Self,
    ) -> error::Result<()>;

    /// put a SLICE of values into the variable, with the destination
    /// strided by `strides`
    ///
    /// # Safety
    ///
    /// `values` must contain space for all the data,
    /// `indices`, `slice_len`, and `strides` must be of
    /// at least dimension length size.
    unsafe fn put_values_strided(
        variable: &mut VariableMut,
        indices: &[usize],
        slice_len: &[usize],
        strides: &[isize],
        values: *const Self,
    ) -> error::Result<()>;
}

#[allow(clippy::doc_markdown)]
/// This macro implements the trait Numeric for the type `sized_type`.
///
/// The use of this macro reduce code duplication for the implementation of Numeric
/// for the common numeric types (i32, f32 ...): they only differs by the name of the
/// C function used to fetch values from the NetCDF variable (eg: `nc_get_var_ushort`, ...).
macro_rules! impl_numeric {
    (
        $sized_type: ty,
        $nc_type: ident,
        $nc_get_var: ident,
        $nc_get_vara_type: ident,
        $nc_get_var1_type: ident,
        $nc_put_var1_type: ident,
        $nc_put_vara_type: ident,
        $nc_get_vars_type: ident,
        $nc_put_vars_type: ident,
    ) => {
        #[allow(clippy::use_self)] // False positives
        unsafe impl Numeric for $sized_type {
            const NCTYPE: nc_type = $nc_type;

            // fetch ONE value from variable using `$nc_get_var1`
            unsafe fn single_value_from_variable(
                variable: &Variable,
                indices: &[usize],
            ) -> error::Result<Self> {
                // initialize `buff` to 0
                let mut buff: Self = 0 as _;
                // Get a pointer to an array
                let indices_ptr = indices.as_ptr();
                error::checked(super::with_lock(|| {
                    $nc_get_var1_type(variable.ncid, variable.varid, indices_ptr, &mut buff)
                }))?;
                Ok(buff)
            }

            unsafe fn variable_to_ptr(
                variable: &Variable,
                indices: &[usize],
                slice_len: &[usize],
                values: *mut Self,
            ) -> error::Result<()> {
                error::checked(super::with_lock(|| {
                    $nc_get_vara_type(
                        variable.ncid,
                        variable.varid,
                        indices.as_ptr(),
                        slice_len.as_ptr(),
                        values,
                    )
                }))
            }

            // put a SINGLE value into a netCDF variable at the given index
            unsafe fn put_value_at(
                variable: &mut VariableMut,
                indices: &[usize],
                value: Self,
            ) -> error::Result<()> {
                error::checked(super::with_lock(|| {
                    $nc_put_var1_type(variable.ncid, variable.varid, indices.as_ptr(), &value)
                }))
            }

            // put a SLICE of values into a netCDF variable at the given index
            unsafe fn put_values_at(
                variable: &mut VariableMut,
                indices: &[usize],
                slice_len: &[usize],
                values: &[Self],
            ) -> error::Result<()> {
                error::checked(super::with_lock(|| {
                    $nc_put_vara_type(
                        variable.ncid,
                        variable.varid,
                        indices.as_ptr(),
                        slice_len.as_ptr(),
                        values.as_ptr(),
                    )
                }))
            }

            unsafe fn get_values_strided(
                variable: &Variable,
                indices: &[usize],
                slice_len: &[usize],
                strides: &[isize],
                values: *mut Self,
            ) -> error::Result<()> {
                error::checked(super::with_lock(|| {
                    $nc_get_vars_type(
                        variable.ncid,
                        variable.varid,
                        indices.as_ptr(),
                        slice_len.as_ptr(),
                        strides.as_ptr(),
                        values,
                    )
                }))
            }

            unsafe fn put_values_strided(
                variable: &mut VariableMut,
                indices: &[usize],
                slice_len: &[usize],
                strides: &[isize],
                values: *const Self,
            ) -> error::Result<()> {
                error::checked(super::with_lock(|| {
                    $nc_put_vars_type(
                        variable.ncid,
                        variable.varid,
                        indices.as_ptr(),
                        slice_len.as_ptr(),
                        strides.as_ptr(),
                        values,
                    )
                }))
            }
        }
    };
}
impl_numeric!(
    u8,
    NC_UBYTE,
    nc_get_var_uchar,
    nc_get_vara_uchar,
    nc_get_var1_uchar,
    nc_put_var1_uchar,
    nc_put_vara_uchar,
    nc_get_vars_uchar,
    nc_put_vars_uchar,
);

impl_numeric!(
    i8,
    NC_BYTE,
    nc_get_var_schar,
    nc_get_vara_schar,
    nc_get_var1_schar,
    nc_put_var1_schar,
    nc_put_vara_schar,
    nc_get_vars_schar,
    nc_put_vars_schar,
);

impl_numeric!(
    i16,
    NC_SHORT,
    nc_get_var_short,
    nc_get_vara_short,
    nc_get_var1_short,
    nc_put_var1_short,
    nc_put_vara_short,
    nc_get_vars_short,
    nc_put_vars_short,
);

impl_numeric!(
    u16,
    NC_USHORT,
    nc_get_var_ushort,
    nc_get_vara_ushort,
    nc_get_var1_ushort,
    nc_put_var1_ushort,
    nc_put_vara_ushort,
    nc_get_vars_ushort,
    nc_put_vars_ushort,
);

impl_numeric!(
    i32,
    NC_INT,
    nc_get_var_int,
    nc_get_vara_int,
    nc_get_var1_int,
    nc_put_var1_int,
    nc_put_vara_int,
    nc_get_vars_int,
    nc_put_vars_int,
);

impl_numeric!(
    u32,
    NC_UINT,
    nc_get_var_uint,
    nc_get_vara_uint,
    nc_get_var1_uint,
    nc_put_var1_uint,
    nc_put_vara_uint,
    nc_get_vars_uint,
    nc_put_vars_uint,
);

impl_numeric!(
    i64,
    NC_INT64,
    nc_get_var_longlong,
    nc_get_vara_longlong,
    nc_get_var1_longlong,
    nc_put_var1_longlong,
    nc_put_vara_longlong,
    nc_get_vars_longlong,
    nc_put_vars_longlong,
);

impl_numeric!(
    u64,
    NC_UINT64,
    nc_get_var_ulonglong,
    nc_get_vara_ulonglong,
    nc_get_var1_ulonglong,
    nc_put_var1_ulonglong,
    nc_put_vara_ulonglong,
    nc_get_vars_ulonglong,
    nc_put_vars_ulonglong,
);

impl_numeric!(
    f32,
    NC_FLOAT,
    nc_get_var_float,
    nc_get_vara_float,
    nc_get_var1_float,
    nc_put_var1_float,
    nc_put_vara_float,
    nc_get_vars_float,
    nc_put_vars_float,
);

impl_numeric!(
    f64,
    NC_DOUBLE,
    nc_get_var_double,
    nc_get_vara_double,
    nc_get_var1_double,
    nc_put_var1_double,
    nc_put_vara_double,
    nc_get_vars_double,
    nc_put_vars_double,
);

/// Holds the contents of a netcdf string. Use deref to get a `CStr`
struct NcString {
    data: *mut std::os::raw::c_char,
}
impl NcString {
    /// Create an `NcString`
    unsafe fn from_ptr(ptr: *mut i8) -> Self {
        Self { data: ptr }
    }
}
impl Drop for NcString {
    fn drop(&mut self) {
        unsafe {
            error::checked(super::with_lock(|| nc_free_string(1, &mut self.data))).unwrap();
        }
    }
}
impl std::ops::Deref for NcString {
    type Target = CStr;
    fn deref(&self) -> &Self::Target {
        unsafe { CStr::from_ptr(self.data) }
    }
}

impl<'g> VariableMut<'g> {
    /// Adds an attribute to the variable
    pub fn add_attribute<T>(&mut self, name: &str, val: T) -> error::Result<Attribute>
    where
        T: Into<AttrValue>,
    {
        Attribute::put(self.ncid, self.varid, name, val.into())
    }
}

impl<'g> Variable<'g> {
    ///  Fetches one specific value at specific indices
    ///  indices must has the same length as self.dimensions.
    pub fn value<T: Numeric>(&self, indices: Option<&[usize]>) -> error::Result<T> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, false)?;
            x
        } else {
            indices_ = self.default_indices(false)?;
            &indices_
        };

        unsafe { T::single_value_from_variable(self, indices) }
    }

    /// Reads a string variable. This involves two copies per read, and should
    /// be avoided in performance critical code
    pub fn string_value(&self, indices: Option<&[usize]>) -> error::Result<String> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, false)?;
            x
        } else {
            indices_ = self.default_indices(false)?;
            &indices_
        };

        let mut s: *mut std::os::raw::c_char = std::ptr::null_mut();
        unsafe {
            error::checked(super::with_lock(|| {
                nc_get_var1_string(self.ncid, self.varid, indices.as_ptr(), &mut s)
            }))?;
        }
        let string = unsafe { NcString::from_ptr(s) };
        Ok(string.to_string_lossy().into_owned())
    }

    #[cfg(feature = "ndarray")]
    /// Fetches variable
    pub fn values<T: Numeric>(
        &self,
        indices: Option<&[usize]>,
        slice_len: Option<&[usize]>,
    ) -> error::Result<ArrayD<T>> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, false)?;
            x
        } else {
            indices_ = self.default_indices(false)?;
            &indices_
        };
        let slice_len_: Vec<usize>;
        let full_length;
        let slice_len = if let Some(x) = slice_len {
            full_length = x.iter().fold(1_usize, |acc, x| acc.saturating_mul(*x));
            if full_length == usize::max_value() {
                return Err(error::Error::Overflow);
            }
            self.check_sizelen(full_length, indices, x, false)?;
            x
        } else {
            full_length = self.dimensions.iter().map(Dimension::len).product();
            slice_len_ = self.default_sizelen(full_length, indices, false)?;
            &slice_len_
        };

        let mut values = Vec::with_capacity(full_length);
        unsafe {
            T::variable_to_ptr(self, indices, slice_len, values.as_mut_ptr())?;
            values.set_len(full_length);
        }
        Ok(ArrayD::from_shape_vec(slice_len, values).unwrap())
    }

    /// Get the fill value of a variable
    pub fn fill_value<T: Numeric>(&self) -> error::Result<Option<T>> {
        if T::NCTYPE != self.vartype {
            return Err(error::Error::TypeMismatch);
        }
        let mut location = std::mem::MaybeUninit::uninit();
        let mut nofill: nc_type = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_var_fill(
                    self.ncid,
                    self.varid,
                    &mut nofill,
                    std::ptr::addr_of_mut!(location).cast(),
                )
            }))?;
        }
        if nofill == 1 {
            return Ok(None);
        }

        Ok(Some(unsafe { location.assume_init() }))
    }
    /// Fetches variable into slice
    /// buffer must be able to hold all the requested elements
    pub fn values_to<T: Numeric>(
        &self,
        buffer: &mut [T],
        indices: Option<&[usize]>,
        slice_len: Option<&[usize]>,
    ) -> error::Result<()> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, false)?;
            x
        } else {
            indices_ = self.default_indices(false)?;
            &indices_
        };
        let slice_len_: Vec<usize>;
        let slice_len = if let Some(x) = slice_len {
            self.check_sizelen(buffer.len(), indices, x, false)?;
            x
        } else {
            slice_len_ = self.default_sizelen(buffer.len(), indices, false)?;
            &slice_len_
        };

        unsafe { T::variable_to_ptr(self, indices, slice_len, buffer.as_mut_ptr()) }
    }

    /// Fetches variable into slice
    /// buffer must be able to hold all the requested elements
    pub fn values_strided_to<T: Numeric>(
        &self,
        buffer: &mut [T],
        indices: Option<&[usize]>,
        slice_len: Option<&[usize]>,
        strides: &[isize],
    ) -> error::Result<usize> {
        if strides.len() != self.dimensions.len() {
            return Err("stride_mismatch".into());
        }
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, false)?;
            x
        } else {
            indices_ = self.default_indices(false)?;
            &indices_
        };

        let slice_len_: Vec<usize>;
        let slice_len = if let Some(slice_len) = slice_len {
            if slice_len.len() != self.dimensions.len() {
                return Err("slice mismatch".into());
            }
            #[allow(clippy::cast_possible_wrap)]
            for (((d, &start), &count), &stride) in self
                .dimensions
                .iter()
                .zip(indices)
                .zip(slice_len)
                .zip(strides)
            {
                if stride == 0 && count != 1 {
                    return Err(error::Error::Stride);
                }
                if count == 0 {
                    return Err(error::Error::ZeroSlice);
                }
                if start as isize + (count as isize - 1) * stride > d.len() as isize {
                    return Err(error::Error::IndexMismatch);
                }
                if start as isize + count as isize * stride < 0 {
                    return Err(error::Error::IndexMismatch);
                }
            }
            slice_len
        } else {
            slice_len_ = self
                .dimensions
                .iter()
                .zip(indices)
                .zip(strides)
                .map(|((d, &start), &stride)| match stride {
                    0 => 1,
                    stride if stride < 0 => start / stride.abs() as usize,
                    stride => {
                        let dlen = d.len();
                        let round_up = stride.abs() as usize - 1;
                        (dlen - start + round_up) / stride.abs() as usize
                    }
                })
                .collect::<Vec<_>>();
            &slice_len_
        };
        if buffer.len() < slice_len.iter().product() {
            return Err("buffer too small".into());
        }
        unsafe { T::get_values_strided(self, indices, slice_len, strides, buffer.as_mut_ptr())? };
        Ok(slice_len.iter().product())
    }

    /// Get values of any type as bytes, with no further interpretation
    /// of the values.
    ///
    /// # Note
    ///
    /// When working with compound types, variable length arrays and
    /// strings will be allocated in `buf`, and this library will
    /// not keep track of the allocations.
    /// This can lead to memory leaks.
    pub fn raw_values(
        &self,
        buf: &mut [u8],
        start: &[usize],
        count: &[usize],
    ) -> error::Result<()> {
        let typ = self.vartype();
        match typ {
            super::types::VariableType::String | super::types::VariableType::Vlen(_) => {
                return Err(error::Error::TypeMismatch)
            }
            _ => (),
        }
        self.check_indices(start, false)?;
        self.check_sizelen(buf.len() / typ.size(), start, count, false)?;

        error::checked(super::with_lock(|| unsafe {
            nc_get_vara(
                self.ncid,
                self.varid,
                start.as_ptr(),
                count.as_ptr(),
                buf.as_mut_ptr().cast(),
            )
        }))
    }

    /// Get a vlen element
    pub fn vlen<T: Numeric>(&self, index: &[usize]) -> error::Result<Vec<T>> {
        if let super::types::VariableType::Vlen(v) = self.vartype() {
            if v.typ().id() != T::NCTYPE {
                return Err(error::Error::TypeMismatch);
            }
        } else {
            return Err(error::Error::TypeMismatch);
        };

        self.check_indices(index, false)?;

        let mut vlen = nc_vlen_t {
            len: 0,
            p: std::ptr::null_mut(),
        };

        let count = index.iter().map(|_| 1).collect::<Vec<usize>>();

        error::checked(super::with_lock(|| unsafe {
            nc_get_vara(
                self.ncid,
                self.varid,
                index.as_ptr(),
                count.as_ptr(),
                std::ptr::addr_of_mut!(vlen).cast(),
            )
        }))?;

        let mut v = Vec::<T>::with_capacity(vlen.len);

        unsafe {
            std::ptr::copy_nonoverlapping(vlen.p as *const T, v.as_mut_ptr(), vlen.len);
            v.set_len(vlen.len);
        }
        error::checked(super::with_lock(|| unsafe { nc_free_vlen(&mut vlen) })).unwrap();

        Ok(v)
    }
}

impl<'g> VariableMut<'g> {
    /// Put a single value at `indices`
    pub fn put_value<T: Numeric>(
        &mut self,
        value: T,
        indices: Option<&[usize]>,
    ) -> error::Result<()> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, true)?;
            x
        } else {
            indices_ = self.default_indices(true)?;
            &indices_
        };
        unsafe { T::put_value_at(self, indices, value) }
    }

    /// Internally converts to a `CString`, avoid using this function when performance
    /// is important
    pub fn put_string(&mut self, value: &str, indices: Option<&[usize]>) -> error::Result<()> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, true)?;
            x
        } else {
            indices_ = self.default_indices(true)?;
            &indices_
        };

        let value = std::ffi::CString::new(value).expect("String contained interior 0");
        let mut ptr = value.as_ptr();

        unsafe {
            error::checked(super::with_lock(|| {
                nc_put_var1_string(self.ncid, self.varid, indices.as_ptr(), &mut ptr)
            }))?;
        }

        Ok(())
    }

    /// Put a slice of values at `indices`
    pub fn put_values<T: Numeric>(
        &mut self,
        values: &[T],
        indices: Option<&[usize]>,
        slice_len: Option<&[usize]>,
    ) -> error::Result<()> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, true)?;
            x
        } else {
            indices_ = self.default_indices(true)?;
            &indices_
        };
        let slice_len_: Vec<usize>;
        let slice_len = if let Some(x) = slice_len {
            self.check_sizelen(values.len(), indices, x, true)?;
            x
        } else {
            slice_len_ = self.default_sizelen(values.len(), indices, true)?;
            &slice_len_
        };
        unsafe { T::put_values_at(self, indices, slice_len, values) }
    }

    /// Put a slice of values at `indices`, with destination strided
    pub fn put_values_strided<T: Numeric>(
        &mut self,
        values: &[T],
        indices: Option<&[usize]>,
        slice_len: Option<&[usize]>,
        strides: &[isize],
    ) -> error::Result<usize> {
        let indices_: Vec<usize>;
        let indices = if let Some(x) = indices {
            self.check_indices(x, true)?;
            x
        } else {
            indices_ = self.default_indices(true)?;
            &indices_
        };
        if strides.len() != self.dimensions.len() {
            return Err(error::Error::IndexMismatch);
        }

        let slice_len_: Vec<usize>;
        let slice_len = if let Some(slice_len) = slice_len {
            if slice_len.len() != self.dimensions.len() {
                return Err(error::Error::SliceMismatch);
            }
            for (((d, &start), &count), &stride) in self
                .dimensions
                .iter()
                .zip(indices)
                .zip(slice_len)
                .zip(strides)
            {
                if count == 0 {
                    return Err(error::Error::ZeroSlice);
                }
                #[allow(clippy::cast_possible_wrap)]
                let end = start as isize + (count as isize - 1) * stride;
                if end < 0 {
                    return Err(error::Error::IndexMismatch);
                }
                if !d.is_unlimited() && end > d.len().try_into()? {
                    return Err(error::Error::IndexMismatch);
                }
            }
            slice_len
        } else {
            slice_len_ = self
                .dimensions
                .iter()
                .zip(indices)
                .zip(strides)
                .map(|((d, &start), &stride)| {
                    match stride {
                        0 => 1,
                        stride if stride > 0 => {
                            let stride: usize = stride.try_into().unwrap();
                            let dlen = d.len();
                            (dlen - start + stride - 1) / stride
                        }
                        _stride => {
                            // Negative stride
                            1
                        }
                    }
                })
                .collect();
            &slice_len_
        };
        if values.len() < slice_len.iter().product() {
            return Err("not enough values".into());
        }
        unsafe { T::put_values_strided(self, indices, slice_len, strides, values.as_ptr())? };
        Ok(slice_len.iter().product())
    }

    /// Set a Fill Value
    ///
    /// # Errors
    ///
    /// Not a `netCDF-4` file, late define, `fill_value` has the wrong type
    #[allow(clippy::needless_pass_by_value)] // All values will be small
    pub fn set_fill_value<T>(&mut self, fill_value: T) -> error::Result<()>
    where
        T: Numeric,
    {
        if T::NCTYPE != self.vartype {
            return Err(error::Error::TypeMismatch);
        }
        unsafe {
            error::checked(super::with_lock(|| {
                nc_def_var_fill(
                    self.ncid,
                    self.varid,
                    NC_FILL,
                    std::ptr::addr_of!(fill_value).cast(),
                )
            }))?;
        }
        Ok(())
    }

    /// Set the fill value to no value. Use this when wanting to avoid
    /// duplicate writes into empty variables.
    ///
    /// # Errors
    ///
    /// Not a `netCDF-4` file
    ///
    /// # Safety
    ///
    /// Reading from this variable after having defined nofill
    /// will read potentially uninitialized data. Normally
    /// one will expect to find some filler value
    pub unsafe fn set_nofill(&mut self) -> error::Result<()> {
        error::checked(super::with_lock(|| {
            nc_def_var_fill(self.ncid, self.varid, NC_NOFILL, std::ptr::null_mut())
        }))
    }

    /// Set endianness of the variable. Must be set before inserting data
    ///
    /// `endian` can take a `Endianness` value with Native being `NC_ENDIAN_NATIVE` (0),
    /// Little `NC_ENDIAN_LITTLE` (1), Big `NC_ENDIAN_BIG` (2)
    ///
    /// # Errors
    ///
    /// Not a `netCDF-4` file, late define
    pub fn endian(&mut self, e: Endianness) -> error::Result<()> {
        let endianness = match e {
            Endianness::Native => NC_ENDIAN_NATIVE,
            Endianness::Little => NC_ENDIAN_LITTLE,
            Endianness::Big => NC_ENDIAN_BIG,
        };
        unsafe {
            error::checked(super::with_lock(|| {
                nc_def_var_endian(self.ncid, self.varid, endianness)
            }))?;
        }
        Ok(())
    }

    /// Get values of any type as bytes
    ///
    /// # Safety
    ///
    /// When working with compound types, variable length arrays and
    /// strings create pointers from the buffer, and tries to copy
    /// memory from these locations. Compound types which does not
    /// have these elements will be safe to access, and can treat
    /// this function as safe
    pub unsafe fn put_raw_values(
        &mut self,
        buf: &[u8],
        start: &[usize],
        count: &[usize],
    ) -> error::Result<()> {
        let typ = self.vartype();
        match typ {
            super::types::VariableType::String | super::types::VariableType::Vlen(_) => {
                return Err(error::Error::TypeMismatch)
            }
            _ => (),
        }
        self.check_indices(start, true)?;
        self.check_sizelen(buf.len() / typ.size(), start, count, true)?;

        #[allow(unused_unsafe)]
        error::checked(super::with_lock(|| unsafe {
            nc_put_vara(
                self.ncid,
                self.varid,
                start.as_ptr(),
                count.as_ptr(),
                buf.as_ptr().cast(),
            )
        }))
    }

    /// Get a vlen element
    pub fn put_vlen<T: Numeric>(&mut self, vec: &[T], index: &[usize]) -> error::Result<()> {
        if let super::types::VariableType::Vlen(v) = self.vartype() {
            if v.typ().id() != T::NCTYPE {
                return Err(error::Error::TypeMismatch);
            }
        } else {
            return Err(error::Error::TypeMismatch);
        };

        self.check_indices(index, true)?;

        let vlen = nc_vlen_t {
            len: vec.len(),
            p: vec.as_ptr() as *mut _,
        };

        let count = index.iter().map(|_| 1).collect::<Vec<usize>>();

        error::checked(super::with_lock(|| unsafe {
            nc_put_vara(
                self.ncid,
                self.varid,
                index.as_ptr(),
                count.as_ptr(),
                std::ptr::addr_of!(vlen).cast(),
            )
        }))
    }
}

impl<'g> VariableMut<'g> {
    pub(crate) fn add_from_str(
        ncid: nc_type,
        xtype: nc_type,
        name: &str,
        dims: &[&str],
    ) -> error::Result<Self> {
        let dimensions = dims
            .iter()
            .map(
                |dimname| match super::dimension::from_name_toid(ncid, dimname) {
                    Ok(Some(id)) => Ok(id),
                    Ok(None) => Err(error::Error::NotFound(format!("dimensions {}", dimname))),
                    Err(e) => Err(e),
                },
            )
            .collect::<error::Result<Vec<_>>>()?;

        let cname = super::utils::short_name_to_bytes(name)?;
        let mut varid = 0;
        unsafe {
            let dimlen = dimensions.len().try_into()?;
            error::checked(super::with_lock(|| {
                nc_def_var(
                    ncid,
                    cname.as_ptr().cast(),
                    xtype,
                    dimlen,
                    dimensions.as_ptr(),
                    &mut varid,
                )
            }))?;
        }

        let dimensions = dims
            .iter()
            .map(|dimname| match super::dimension::from_name(ncid, dimname) {
                Ok(None) => Err(error::Error::NotFound(format!("dimensions {}", dimname))),
                Ok(Some(dim)) => Ok(dim),
                Err(e) => Err(e),
            })
            .collect::<error::Result<Vec<_>>>()?;

        Ok(VariableMut(
            Variable {
                ncid,
                varid,
                vartype: xtype,
                dimensions,
                _group: PhantomData,
            },
            PhantomData,
        ))
    }
}

pub(crate) fn variables_at_ncid<'g>(
    ncid: nc_type,
) -> error::Result<impl Iterator<Item = error::Result<Variable<'g>>>> {
    let mut nvars = 0;
    unsafe {
        error::checked(super::with_lock(|| {
            nc_inq_varids(ncid, &mut nvars, std::ptr::null_mut())
        }))?;
    }
    let mut varids = vec![0; nvars.try_into()?];
    unsafe {
        error::checked(super::with_lock(|| {
            nc_inq_varids(ncid, std::ptr::null_mut(), varids.as_mut_ptr())
        }))?;
    }
    Ok(varids.into_iter().map(move |varid| {
        let mut xtype = 0;
        unsafe {
            error::checked(super::with_lock(|| nc_inq_vartype(ncid, varid, &mut xtype)))?;
        }
        let dimensions = super::dimension::dimensions_from_variable(ncid, varid)?
            .collect::<error::Result<Vec<_>>>()?;
        Ok(Variable {
            ncid,
            varid,
            dimensions,
            vartype: xtype,
            _group: PhantomData,
        })
    }))
}

pub(crate) fn add_variable_from_identifiers<'g>(
    ncid: nc_type,
    name: &str,
    dims: &[super::dimension::Identifier],
    xtype: nc_type,
) -> error::Result<VariableMut<'g>> {
    let cname = super::utils::short_name_to_bytes(name)?;

    let dimensions = dims
        .iter()
        .map(move |&id| {
            // Internal netcdf detail, the top 16 bits gives the corresponding
            // file handle. This to ensure dimensions are not added from another
            // file which is unrelated to self
            if id.ncid >> 16 != ncid >> 16 {
                return Err(error::Error::WrongDataset);
            }
            let mut dimlen = 0;
            unsafe {
                error::checked(super::with_lock(|| {
                    nc_inq_dimlen(id.ncid, id.dimid, &mut dimlen)
                }))?;
            }
            Ok(Dimension {
                len: core::num::NonZeroUsize::new(dimlen),
                id,
                _group: PhantomData,
            })
        })
        .collect::<error::Result<Vec<_>>>()?;
    let dims = dims.iter().map(|x| x.dimid).collect::<Vec<_>>();

    let mut varid = 0;
    unsafe {
        let dimlen = dims.len().try_into()?;
        error::checked(super::with_lock(|| {
            nc_def_var(
                ncid,
                cname.as_ptr().cast(),
                xtype,
                dimlen,
                dims.as_ptr(),
                &mut varid,
            )
        }))?;
    }

    Ok(VariableMut(
        Variable {
            ncid,
            dimensions,
            varid,
            vartype: xtype,
            _group: PhantomData,
        },
        PhantomData,
    ))
}