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
//! Interact with netcdf dimensions

#![allow(clippy::similar_names)]
use super::error;
use netcdf_sys::*;
use std::convert::TryInto;
use std::marker::PhantomData;

/// Represents a netcdf dimension
#[derive(Debug, Clone)]
pub struct Dimension<'g> {
    /// None when unlimited (size = 0)
    pub(crate) len: Option<core::num::NonZeroUsize>,
    pub(crate) id: Identifier,
    pub(crate) _group: PhantomData<&'g nc_type>,
}

/// Unique identifier for a dimensions in a file. Used when
/// names can not be used directly
#[derive(Debug, Copy, Clone)]
pub struct Identifier {
    pub(crate) ncid: nc_type,
    pub(crate) dimid: nc_type,
}

#[allow(clippy::len_without_is_empty)]
impl<'g> Dimension<'g> {
    /// Get current length of this dimension
    pub fn len(&self) -> usize {
        if let Some(x) = self.len {
            x.get()
        } else {
            let mut len = 0;
            let err = unsafe {
                // Must lock in case other variables adds to the dimension length
                error::checked(super::with_lock(|| {
                    nc_inq_dimlen(self.id.ncid, self.id.dimid, &mut len)
                }))
            };

            // Should log or handle this somehow...
            err.map(|_| len).unwrap_or(0)
        }
    }

    /// Checks whether the dimension is growable
    pub fn is_unlimited(&self) -> bool {
        self.len.is_none()
    }

    /// Gets the name of the dimension
    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_dimname(self.id.ncid, self.id.dimid, 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("Dimension did not have a valid name")
    }

    /// Grabs the unique identifier for this dimension, which
    /// can be used in `add_variable_from_identifiers`
    pub fn identifier(&self) -> Identifier {
        self.id
    }
}

pub(crate) fn from_name_toid(loc: nc_type, name: &str) -> error::Result<Option<nc_type>> {
    let mut dimid = 0;
    let cname = super::utils::short_name_to_bytes(name)?;
    let e = unsafe { super::with_lock(|| nc_inq_dimid(loc, cname.as_ptr().cast(), &mut dimid)) };
    if e == NC_EBADDIM {
        return Ok(None);
    }
    error::checked(e)?;

    Ok(Some(dimid))
}

pub(crate) fn from_name<'f>(loc: nc_type, name: &str) -> error::Result<Option<Dimension<'f>>> {
    let mut dimid = 0;
    let cname = super::utils::short_name_to_bytes(name)?;
    let e = unsafe { super::with_lock(|| nc_inq_dimid(loc, cname.as_ptr().cast(), &mut dimid)) };
    if e == NC_EBADDIM {
        return Ok(None);
    }
    error::checked(e)?;

    let mut dimlen = 0;
    unsafe {
        error::checked(super::with_lock(|| nc_inq_dimlen(loc, dimid, &mut dimlen)))?;
    }
    if dimlen != 0 {
        let mut nunlim = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_unlimdims(loc, &mut nunlim, std::ptr::null_mut())
            }))?;
        }
        if nunlim != 0 {
            let mut unlimdims = Vec::with_capacity(nunlim.try_into()?);
            unsafe {
                error::checked(super::with_lock(|| {
                    nc_inq_unlimdims(loc, std::ptr::null_mut(), unlimdims.as_mut_ptr())
                }))?;
            }
            unsafe { unlimdims.set_len(nunlim.try_into()?) }
            if unlimdims.contains(&dimid) {
                dimlen = 0;
            }
        }
    }

    Ok(Some(Dimension {
        len: core::num::NonZeroUsize::new(dimlen),
        id: Identifier { ncid: loc, dimid },
        _group: PhantomData,
    }))
}

pub(crate) fn dimensions_from_location<'g>(
    ncid: nc_type,
) -> error::Result<impl Iterator<Item = error::Result<Dimension<'g>>>> {
    let mut ndims = 0;
    unsafe {
        error::checked(super::with_lock(|| {
            nc_inq_dimids(ncid, &mut ndims, std::ptr::null_mut(), false as _)
        }))?;
    }
    let mut dimids = vec![0; ndims.try_into()?];
    unsafe {
        error::checked(super::with_lock(|| {
            nc_inq_dimids(ncid, std::ptr::null_mut(), dimids.as_mut_ptr(), false as _)
        }))?;
    }
    let unlimdims = {
        let mut nunlimdims = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_unlimdims(ncid, &mut nunlimdims, std::ptr::null_mut())
            }))?;
        }
        let mut unlimdims = Vec::with_capacity(nunlimdims.try_into()?);
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_unlimdims(ncid, std::ptr::null_mut(), unlimdims.as_mut_ptr())
            }))?;
        }
        unsafe {
            unlimdims.set_len(nunlimdims.try_into()?);
        }
        unlimdims
    };
    Ok(dimids.into_iter().map(move |dimid| {
        let mut dimlen = 0;
        if !unlimdims.contains(&dimid) {
            unsafe {
                error::checked(super::with_lock(|| nc_inq_dimlen(ncid, dimid, &mut dimlen)))?;
            }
        }
        Ok(Dimension {
            len: core::num::NonZeroUsize::new(dimlen),
            id: Identifier { ncid, dimid },
            _group: PhantomData,
        })
    }))
}

pub(crate) fn dimensions_from_variable<'g>(
    ncid: nc_type,
    varid: nc_type,
) -> error::Result<impl Iterator<Item = error::Result<Dimension<'g>>>> {
    let mut ndims = 0;
    unsafe {
        error::checked(super::with_lock(|| {
            nc_inq_varndims(ncid, varid, &mut ndims)
        }))?;
    }
    let mut dimids = vec![0; ndims.try_into()?];
    unsafe {
        error::checked(super::with_lock(|| {
            nc_inq_vardimid(ncid, varid, dimids.as_mut_ptr())
        }))?;
    }
    let unlimdims = {
        let mut nunlimdims = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_unlimdims(ncid, &mut nunlimdims, std::ptr::null_mut())
            }))?;
        }
        let mut unlimdims = Vec::with_capacity(nunlimdims.try_into()?);
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_unlimdims(ncid, std::ptr::null_mut(), unlimdims.as_mut_ptr())
            }))?;
        }
        unsafe {
            unlimdims.set_len(nunlimdims.try_into()?);
        }
        unlimdims
    };

    Ok(dimids.into_iter().map(move |dimid| {
        let mut dimlen = 0;
        if !unlimdims.contains(&dimid) {
            unsafe {
                error::checked(super::with_lock(|| nc_inq_dimlen(ncid, dimid, &mut dimlen)))?;
            }
        }
        Ok(Dimension {
            len: core::num::NonZeroUsize::new(dimlen),
            id: Identifier { ncid, dimid },
            _group: PhantomData,
        })
    }))
}

pub(crate) fn dimension_from_name<'f>(
    ncid: nc_type,
    name: &str,
) -> error::Result<Option<Dimension<'f>>> {
    let cname = super::utils::short_name_to_bytes(name)?;
    let mut dimid = 0;
    let e = unsafe { super::with_lock(|| nc_inq_dimid(ncid, cname.as_ptr().cast(), &mut dimid)) };
    if e == NC_EBADDIM {
        return Ok(None);
    }
    error::checked(e)?;

    let mut dimlen = 0;
    unsafe {
        error::checked(super::with_lock(|| nc_inq_dimlen(ncid, dimid, &mut dimlen))).unwrap();
    }
    if dimlen != 0 {
        // Have to check if this dimension is unlimited
        let mut nunlim = 0;
        unsafe {
            error::checked(super::with_lock(|| {
                nc_inq_unlimdims(ncid, &mut nunlim, std::ptr::null_mut())
            }))?;
        }
        if nunlim != 0 {
            let mut unlimdims = Vec::with_capacity(nunlim.try_into()?);
            unsafe {
                error::checked(super::with_lock(|| {
                    nc_inq_unlimdims(ncid, std::ptr::null_mut(), unlimdims.as_mut_ptr())
                }))?;
            }
            unsafe { unlimdims.set_len(nunlim.try_into()?) }
            if unlimdims.contains(&dimid) {
                dimlen = 0;
            }
        }
    }
    Ok(Some(Dimension {
        len: core::num::NonZeroUsize::new(dimlen),
        id: super::dimension::Identifier { ncid, dimid },
        _group: PhantomData,
    }))
}

pub(crate) fn add_dimension_at<'f>(
    ncid: nc_type,
    name: &str,
    len: usize,
) -> error::Result<Dimension<'f>> {
    let cname = super::utils::short_name_to_bytes(name)?;
    let mut dimid = 0;
    unsafe {
        error::checked(super::with_lock(|| {
            nc_def_dim(ncid, cname.as_ptr().cast(), len, &mut dimid)
        }))?;
    }
    Ok(Dimension {
        len: core::num::NonZeroUsize::new(dimid.try_into()?),
        id: Identifier { ncid, dimid },
        _group: PhantomData,
    })
}