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
//! Contains functions and enums describing variable types

use super::error;
use crate::with_lock;
use netcdf_sys::*;
use std::convert::TryInto;

/// Basic numeric types
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum BasicType {
    /// Signed 1 byte integer
    Byte,
    /// Unsigned 1 byte integer
    Ubyte,
    /// Signed 2 byte integer
    Short,
    /// Unsigned 2 byte integer
    Ushort,
    /// Signed 4 byte integer
    Int,
    /// Unsigned 4 byte integer
    Uint,
    /// Signed 8 byte integer
    Int64,
    /// Unsigned 8 byte integer
    Uint64,
    /// Single precision floating point number
    Float,
    /// Double precision floating point number
    Double,
}

impl BasicType {
    /// Size of the type in bytes
    fn size(self) -> usize {
        match self {
            Self::Byte | Self::Ubyte => 1,
            Self::Short | Self::Ushort => 2,
            Self::Int | Self::Uint | Self::Float => 4,
            Self::Int64 | Self::Uint64 | Self::Double => 8,
        }
    }
    /// `nc_type` of the type
    pub(crate) fn id(self) -> nc_type {
        use super::Numeric;
        match self {
            Self::Byte => i8::NCTYPE,
            Self::Ubyte => u8::NCTYPE,
            Self::Short => i16::NCTYPE,
            Self::Ushort => u16::NCTYPE,
            Self::Int => i32::NCTYPE,
            Self::Uint => u32::NCTYPE,
            Self::Int64 => i64::NCTYPE,
            Self::Uint64 => u64::NCTYPE,
            Self::Float => f32::NCTYPE,
            Self::Double => f64::NCTYPE,
        }
    }

    /// `rusty` name of the type
    pub fn name(self) -> &'static str {
        match self {
            BasicType::Byte => "i8",
            BasicType::Ubyte => "u8",
            BasicType::Short => "i16",
            BasicType::Ushort => "u16",
            BasicType::Int => "i32",
            BasicType::Uint => "u32",
            BasicType::Int64 => "i64",
            BasicType::Uint64 => "u64",
            BasicType::Float => "f32",
            BasicType::Double => "f64",
        }
    }
}

#[allow(missing_docs)]
impl BasicType {
    pub fn is_i8(self) -> bool {
        self == Self::Byte
    }
    pub fn is_u8(self) -> bool {
        self == Self::Ubyte
    }
    pub fn is_i16(self) -> bool {
        self == Self::Short
    }
    pub fn is_u16(self) -> bool {
        self == Self::Ushort
    }
    pub fn is_i32(self) -> bool {
        self == Self::Int
    }
    pub fn is_u32(self) -> bool {
        self == Self::Uint
    }
    pub fn is_i64(self) -> bool {
        self == Self::Int64
    }
    pub fn is_u64(self) -> bool {
        self == Self::Uint64
    }
    pub fn is_f32(self) -> bool {
        self == Self::Float
    }
    pub fn is_f64(self) -> bool {
        self == Self::Double
    }
}

#[derive(Clone, Debug)]
/// A set of bytes which with unspecified endianess
pub struct OpaqueType {
    ncid: nc_type,
    id: nc_type,
}

impl OpaqueType {
    /// Get the name of this opaque type
    pub fn name(&self) -> String {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        error::checked(super::with_lock(|| unsafe {
            nc_inq_opaque(
                self.ncid,
                self.id,
                name.as_mut_ptr() as *mut _,
                std::ptr::null_mut(),
            )
        }))
        .unwrap();

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        String::from_utf8(name[..pos].to_vec()).unwrap()
    }
    /// Number of bytes this type occupies
    pub fn size(&self) -> usize {
        let mut numbytes = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_inq_opaque(self.ncid, self.id, std::ptr::null_mut(), &mut numbytes)
        }))
        .unwrap();
        numbytes
    }
    pub(crate) fn add(location: nc_type, name: &str, size: usize) -> error::Result<Self> {
        let name = super::utils::short_name_to_bytes(name)?;
        let mut id = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_def_opaque(location, size, name.as_ptr() as *const _, &mut id)
        }))?;

        Ok(Self { ncid: location, id })
    }
}

/// Type of variable length
#[derive(Debug, Clone)]
pub struct VlenType {
    ncid: nc_type,
    id: nc_type,
}

impl VlenType {
    /// Name of the type
    pub fn name(&self) -> String {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        error::checked(super::with_lock(|| unsafe {
            nc_inq_vlen(
                self.ncid,
                self.id,
                name.as_mut_ptr() as *mut _,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        }))
        .unwrap();

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        String::from_utf8(name[..pos].to_vec()).unwrap()
    }

    pub(crate) fn add<T>(location: nc_type, name: &str) -> error::Result<Self>
    where
        T: super::Numeric,
    {
        let name = super::utils::short_name_to_bytes(name)?;
        let mut id = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_def_vlen(location, name.as_ptr() as *const _, T::NCTYPE, &mut id)
        }))?;

        Ok(Self { ncid: location, id })
    }

    /// Internal type
    pub fn typ(&self) -> BasicType {
        let mut bastyp = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_inq_vlen(
                self.ncid,
                self.id,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                &mut bastyp,
            )
        }))
        .unwrap();

        match bastyp {
            NC_BYTE => BasicType::Byte,
            NC_UBYTE => BasicType::Ubyte,
            NC_SHORT => BasicType::Short,
            NC_USHORT => BasicType::Ushort,
            NC_INT => BasicType::Int,
            NC_UINT => BasicType::Uint,
            NC_INT64 => BasicType::Int64,
            NC_UINT64 => BasicType::Uint64,
            NC_FLOAT => BasicType::Float,
            NC_DOUBLE => BasicType::Double,
            _ => panic!("Did not expect typeid {} in this context", bastyp),
        }
    }
}

#[derive(Debug, Clone)]
/// Multiple string values stored as integer type
pub struct EnumType {
    ncid: nc_type,
    id: nc_type,
}

impl EnumType {
    pub(crate) fn add<T: super::Numeric>(
        ncid: nc_type,
        name: &str,
        mappings: &[(&str, T)],
    ) -> error::Result<EnumType> {
        let name = super::utils::short_name_to_bytes(name)?;
        let mut id = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_def_enum(ncid, T::NCTYPE, name.as_ptr() as *const _, &mut id)
        }))?;

        for (name, val) in mappings {
            let name = super::utils::short_name_to_bytes(name)?;
            error::checked(super::with_lock(|| unsafe {
                nc_insert_enum(
                    ncid,
                    id,
                    name.as_ptr() as *const _,
                    val as *const T as *const _,
                )
            }))?;
        }

        Ok(Self { ncid, id })
    }

    /// Get the base type of the enum
    pub fn typ(&self) -> BasicType {
        let mut typ = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_inq_enum(
                self.ncid,
                self.id,
                std::ptr::null_mut(),
                &mut typ,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        }))
        .unwrap();
        match typ {
            NC_BYTE => BasicType::Byte,
            NC_UBYTE => BasicType::Ubyte,
            NC_SHORT => BasicType::Short,
            NC_USHORT => BasicType::Ushort,
            NC_INT => BasicType::Int,
            NC_UINT => BasicType::Uint,
            NC_INT64 => BasicType::Int64,
            NC_UINT64 => BasicType::Uint64,
            NC_FLOAT => BasicType::Float,
            NC_DOUBLE => BasicType::Double,
            _ => panic!("Did not expect typeid {} in this context", typ),
        }
    }

    /// Get a single member from an index
    ///
    /// # Safety
    /// Does not check type of enum
    unsafe fn member_at<T: super::Numeric>(&self, idx: usize) -> error::Result<(String, T)> {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        let mut t = std::mem::MaybeUninit::<T>::uninit();
        let idx = idx.try_into()?;
        super::with_lock(|| {
            nc_inq_enum_member(
                self.ncid,
                self.id,
                idx,
                name.as_mut_ptr() as *mut _,
                t.as_mut_ptr() as *mut _,
            )
        });

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        let name = String::from_utf8(name[..pos].to_vec()).unwrap();
        Ok((name, t.assume_init()))
    }

    /// Get all members of the enum
    pub fn members<'f, T: super::Numeric>(
        &'f self,
    ) -> error::Result<impl Iterator<Item = (String, T)> + 'f> {
        let mut typ = 0;
        let mut nummembers = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_inq_enum(
                self.ncid,
                self.id,
                std::ptr::null_mut(),
                &mut typ,
                std::ptr::null_mut(),
                &mut nummembers,
            )
        }))
        .unwrap();
        if typ != T::NCTYPE {
            return Err(error::Error::TypeMismatch);
        }

        Ok((0..nummembers).map(move |idx| unsafe { self.member_at::<T>(idx) }.unwrap()))
    }

    /// Name of the type
    pub fn name(&self) -> String {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        error::checked(super::with_lock(|| unsafe {
            nc_inq_enum(
                self.ncid,
                self.id,
                name.as_mut_ptr() as *mut _,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        }))
        .unwrap();

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        String::from_utf8(name[..pos].to_vec()).unwrap()
    }

    /// Get the name from the enum value
    pub fn name_from_value(&self, value: i64) -> Option<String> {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        let e = super::with_lock(|| unsafe {
            nc_inq_enum_ident(self.ncid, self.id, value, name.as_mut_ptr() as *mut _)
        });
        if e == NC_EINVAL {
            return None;
        }

        error::checked(e).unwrap();

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        Some(String::from_utf8(name[..pos].to_vec()).unwrap())
    }

    /// Size in bytes of this type
    fn size(&self) -> usize {
        self.typ().size()
    }
}

/// A type consisting of other types
#[derive(Debug, Clone)]
pub struct CompoundType {
    ncid: nc_type,
    id: nc_type,
}

impl CompoundType {
    pub(crate) fn add(ncid: nc_type, name: &str) -> error::Result<CompoundBuilder> {
        let name = super::utils::short_name_to_bytes(name)?;

        Ok(CompoundBuilder {
            ncid,
            name,
            size: 0,
            comp: Vec::new(),
        })
    }

    /// Size in bytes of this type
    fn size(&self) -> usize {
        let mut size = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound(
                self.ncid,
                self.id,
                std::ptr::null_mut(),
                &mut size,
                std::ptr::null_mut(),
            )
        }))
        .unwrap();
        size
    }

    /// Get the name of this type
    pub fn name(&self) -> String {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound(
                self.ncid,
                self.id,
                name.as_mut_ptr() as *mut _,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        }))
        .unwrap();

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        String::from_utf8(name[..pos].to_vec()).unwrap()
    }

    /// Get the fields of the compound
    pub fn fields(&self) -> impl Iterator<Item = CompoundField> {
        let ncid = self.ncid;
        let parent_id = self.id;

        let mut nfields = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound_nfields(ncid, parent_id, &mut nfields)
        }))
        .unwrap();

        (0..nfields).map(move |x| CompoundField {
            ncid,
            parent: parent_id,
            id: x,
        })
    }
}

/// Subfield of a compound
pub struct CompoundField {
    ncid: nc_type,
    parent: nc_type,
    id: usize,
}

impl CompoundField {
    /// Name of the compound field
    pub fn name(&self) -> String {
        let mut name = [0_u8; NC_MAX_NAME as usize + 1];
        let idx = self.id.try_into().unwrap();
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound_fieldname(self.ncid, self.parent, idx, name.as_mut_ptr() as *mut _)
        }))
        .unwrap();

        let pos = name
            .iter()
            .position(|&x| x == 0)
            .unwrap_or_else(|| name.len());
        String::from_utf8(name[..pos].to_vec()).unwrap()
    }

    /// type of the field
    pub fn typ(&self) -> VariableType {
        let mut typ = 0;
        let id = self.id.try_into().unwrap();
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound_fieldtype(self.ncid, self.parent, id, &mut typ)
        }))
        .unwrap();

        VariableType::from_id(self.ncid, typ).unwrap()
    }

    /// Offset in bytes of this field in the compound type
    pub fn offset(&self) -> usize {
        let mut offset = 0;
        let id = self.id.try_into().unwrap();
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound_field(
                self.ncid,
                self.parent,
                id,
                std::ptr::null_mut(),
                &mut offset,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        }))
        .unwrap();

        offset
    }

    /// Get dimensionality of this compound field
    pub fn dimensions(&self) -> Option<Vec<usize>> {
        let mut num_dims = 0;
        let id = self.id.try_into().unwrap();
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound_fieldndims(self.ncid, self.parent, id, &mut num_dims)
        }))
        .unwrap();

        if num_dims == 0 {
            return None;
        }

        let mut dims = vec![0; num_dims.try_into().unwrap()];
        error::checked(super::with_lock(|| unsafe {
            nc_inq_compound_fielddim_sizes(self.ncid, self.parent, id, dims.as_mut_ptr())
        }))
        .unwrap();

        Some(dims.iter().map(|&x| x.try_into().unwrap()).collect())
    }
}

/// A builder for a compound type
#[must_use]
pub struct CompoundBuilder {
    ncid: nc_type,
    name: [u8; NC_MAX_NAME as usize + 1],
    size: usize,
    comp: Vec<(
        VariableType,
        [u8; NC_MAX_NAME as usize + 1],
        Option<Vec<i32>>,
    )>,
}

impl CompoundBuilder {
    /// Add a type to the compound
    pub fn add_type(&mut self, name: &str, var: &VariableType) -> error::Result<&mut Self> {
        self.comp
            .push((var.clone(), super::utils::short_name_to_bytes(name)?, None));

        self.size += var.size();
        Ok(self)
    }

    /// Add a basic numeric type
    pub fn add<T: super::Numeric>(&mut self, name: &str) -> error::Result<&mut Self> {
        let var = VariableType::from_id(self.ncid, T::NCTYPE)?;
        self.add_type(name, &var)
    }

    /// Add an array of a basic type
    pub fn add_array<T: super::Numeric>(
        &mut self,
        name: &str,
        dims: &[usize],
    ) -> error::Result<&mut Self> {
        let var = VariableType::from_id(self.ncid, T::NCTYPE)?;
        self.add_array_type(name, &var, dims)
    }

    /// Add a type as an array
    pub fn add_array_type(
        &mut self,
        name: &str,
        var: &VariableType,
        dims: &[usize],
    ) -> error::Result<&mut Self> {
        self.comp.push((
            var.clone(),
            super::utils::short_name_to_bytes(name)?,
            Some(dims.iter().map(|&x| x.try_into().unwrap()).collect()),
        ));

        self.size += var.size() * dims.iter().product::<usize>();
        Ok(self)
    }

    /// Finalize the compound type
    pub fn build(self) -> error::Result<CompoundType> {
        let mut id = 0;
        error::checked(super::with_lock(|| unsafe {
            nc_def_compound(
                self.ncid,
                self.size,
                self.name.as_ptr() as *const _,
                &mut id,
            )
        }))?;

        let mut offset = 0;
        for (typ, name, dims) in &self.comp {
            match dims {
                None => {
                    error::checked(super::with_lock(|| unsafe {
                        nc_insert_compound(
                            self.ncid,
                            id,
                            name.as_ptr() as *const _,
                            offset,
                            typ.id(),
                        )
                    }))?;
                    offset += typ.size();
                }
                Some(dims) => {
                    let dimlen = dims.len().try_into().unwrap();
                    error::checked(super::with_lock(|| unsafe {
                        nc_insert_array_compound(
                            self.ncid,
                            id,
                            name.as_ptr() as *const _,
                            offset,
                            typ.id(),
                            dimlen,
                            dims.as_ptr(),
                        )
                    }))?;
                    offset += typ.size()
                        * dims
                            .iter()
                            .map(|x: &i32| -> usize { (*x).try_into().unwrap() })
                            .product::<usize>();
                }
            }
        }

        Ok(CompoundType {
            ncid: self.ncid,
            id,
        })
    }
}

/// Description of the variable
#[derive(Debug, Clone)]
pub enum VariableType {
    /// A basic numeric type
    Basic(BasicType),
    /// A string type
    String,
    /// Some bytes
    Opaque(OpaqueType),
    /// Variable length array
    Vlen(VlenType),
    /// Enum type
    Enum(EnumType),
    /// Compound type
    Compound(CompoundType),
}

impl VariableType {
    /// Get the basic type, if this type is a simple numeric type
    pub fn as_basic(&self) -> Option<BasicType> {
        match self {
            Self::Basic(x) => Some(*x),
            _ => None,
        }
    }

    /// Size in bytes of the type
    pub(crate) fn size(&self) -> usize {
        match self {
            Self::Basic(b) => b.size(),
            Self::String => panic!("A string does not have a defined size"),
            Self::Enum(e) => e.size(),
            Self::Opaque(o) => o.size(),
            Self::Vlen(_) => panic!("A variable length array does not have a defined size"),
            Self::Compound(c) => c.size(),
        }
    }

    /// Id of this type
    pub(crate) fn id(&self) -> nc_type {
        match self {
            Self::Basic(b) => b.id(),
            Self::String => NC_STRING,
            Self::Enum(e) => e.id,
            Self::Opaque(o) => o.id,
            Self::Vlen(v) => v.id,
            Self::Compound(c) => c.id,
        }
    }

    /// Get the name of the type. The basic numeric types will
    /// have `rusty` names (u8/i32/f64/string)
    pub fn name(&self) -> String {
        match self {
            Self::Basic(b) => b.name().into(),
            Self::String => "string".into(),
            Self::Enum(e) => e.name(),
            Self::Opaque(o) => o.name(),
            Self::Vlen(v) => v.name(),
            Self::Compound(c) => c.name(),
        }
    }
}

#[allow(missing_docs)]
impl VariableType {
    pub fn is_string(&self) -> bool {
        matches!(self, Self::String)
    }
    pub fn is_i8(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_i8)
    }
    pub fn is_u8(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_u8)
    }
    pub fn is_i16(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_i16)
    }
    pub fn is_u16(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_u16)
    }
    pub fn is_i32(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_i32)
    }
    pub fn is_u32(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_u32)
    }
    pub fn is_i64(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_i64)
    }
    pub fn is_u64(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_u64)
    }
    pub fn is_f32(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_f32)
    }
    pub fn is_f64(&self) -> bool {
        self.as_basic().map_or(false, BasicType::is_f64)
    }
}

impl VariableType {
    /// Get the variable type from the id
    pub(crate) fn from_id(ncid: nc_type, xtype: nc_type) -> error::Result<Self> {
        match xtype {
            NC_BYTE => Ok(Self::Basic(BasicType::Byte)),
            NC_UBYTE => Ok(Self::Basic(BasicType::Ubyte)),
            NC_SHORT => Ok(Self::Basic(BasicType::Short)),
            NC_USHORT => Ok(Self::Basic(BasicType::Ushort)),
            NC_INT => Ok(Self::Basic(BasicType::Int)),
            NC_UINT => Ok(Self::Basic(BasicType::Uint)),
            NC_INT64 => Ok(Self::Basic(BasicType::Int64)),
            NC_UINT64 => Ok(Self::Basic(BasicType::Uint64)),
            NC_FLOAT => Ok(Self::Basic(BasicType::Float)),
            NC_DOUBLE => Ok(Self::Basic(BasicType::Double)),
            NC_STRING => Ok(Self::String),
            xtype => {
                let mut base_xtype = 0;
                error::checked(super::with_lock(|| unsafe {
                    nc_inq_user_type(
                        ncid,
                        xtype,
                        std::ptr::null_mut(),
                        std::ptr::null_mut(),
                        std::ptr::null_mut(),
                        std::ptr::null_mut(),
                        &mut base_xtype,
                    )
                }))?;
                match base_xtype {
                    NC_VLEN => Ok(VlenType { ncid, id: xtype }.into()),
                    NC_OPAQUE => Ok(OpaqueType { ncid, id: xtype }.into()),
                    NC_ENUM => Ok(EnumType { ncid, id: xtype }.into()),
                    NC_COMPOUND => Ok(CompoundType { ncid, id: xtype }.into()),
                    _ => panic!("Unexpected base type: {}", base_xtype),
                }
            }
        }
    }
}

pub(crate) fn all_at_location(
    ncid: nc_type,
) -> error::Result<impl Iterator<Item = error::Result<VariableType>>> {
    let typeids = {
        let mut num_typeids = 0;
        error::checked(with_lock(|| unsafe {
            nc_inq_typeids(ncid, &mut num_typeids, std::ptr::null_mut())
        }))?;
        let mut typeids = vec![0; num_typeids.try_into()?];
        error::checked(with_lock(|| unsafe {
            nc_inq_typeids(ncid, std::ptr::null_mut(), typeids.as_mut_ptr())
        }))?;
        typeids
    };
    Ok(typeids
        .into_iter()
        .map(move |x| VariableType::from_id(ncid, x)))
}

impl Into<VariableType> for CompoundType {
    fn into(self) -> VariableType {
        VariableType::Compound(self)
    }
}
impl Into<VariableType> for BasicType {
    fn into(self) -> VariableType {
        VariableType::Basic(self)
    }
}
impl Into<VariableType> for EnumType {
    fn into(self) -> VariableType {
        VariableType::Enum(self)
    }
}
impl Into<VariableType> for VlenType {
    fn into(self) -> VariableType {
        VariableType::Vlen(self)
    }
}
impl Into<VariableType> for OpaqueType {
    fn into(self) -> VariableType {
        VariableType::Opaque(self)
    }
}