netcdf3 0.6.1

A pure Rust library for reading and writing NetCDF-3 files
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
mod tests;

use std::collections::HashSet;
use std::iter::FromIterator;
use std::rc::Rc;

use crate::data_set::dimension::DimensionSize;
use crate::io::compute_padding_size;
use crate::{is_valid_name, Attribute, DataType, Dimension, InvalidDataSet, NC_MAX_VAR_DIMS};

/// NetCDF-3 variable
///
/// `Variable` instances are managed by the struct [`DataSet`](struct.DataSet.html).
///
/// `DataSet`s allow to create, get, remove and rename `Variable`s.
///
/// # Examples
///
/// ## Create a variable
///
/// ```
/// use netcdf3::{DataSet, Variable, DataType, DimensionType};
///
/// const VAR_NAME: &str = "var_1";
/// const DIM_NAME_1: &str = "dim_1";
/// const DIM_NAME_2: &str = "dim_2";
/// const DIM_SIZE_1: usize = 2;
/// const DIM_SIZE_2: usize = 3;
/// const DATA_F32: &'static [f32; 6] = &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
/// const DATA_F32_LEN: usize = DATA_F32.len();
///
/// assert_eq!(DATA_F32_LEN, DIM_SIZE_1 * DIM_SIZE_2);
///
/// // Create a data set
/// let mut data_set: DataSet = DataSet::new();
/// // Define 2 dimensions
/// data_set.set_unlimited_dim(DIM_NAME_1, DIM_SIZE_1).unwrap();
/// data_set.add_fixed_dim(DIM_NAME_2, DIM_SIZE_2).unwrap();
/// // Define a `f32` variable
/// data_set.add_var_f32(VAR_NAME, &[DIM_NAME_1, DIM_NAME_2]).unwrap();
///
/// assert_eq!(true,            data_set.has_var(VAR_NAME));
/// let var: &Variable = data_set.get_var(VAR_NAME).unwrap();
/// assert_eq!(VAR_NAME,                        var.name());
/// assert_eq!(true,                            var.is_record_var());
/// assert_eq!(2,                               var.num_dims());
/// assert_eq!(0,                               var.num_attrs());
/// assert_eq!(vec![DIM_NAME_1, DIM_NAME_2],    var.dim_names());
/// assert_eq!(DATA_F32_LEN,                    var.len());
/// assert_eq!(DataType::F32,                   var.data_type());
///
/// ```
///
/// ## Rename a variable
///
/// ```
/// use netcdf3::{DataSet, DataType};
/// const VAR_NAME_1: &str = "var_1";
/// const VAR_NAME_2: &str = "var_2";
/// const DIM_NAME: &str = "dim_1";
/// const VAR_DATA: [i32; 4] = [1, 2, 3, 4];
/// const VAR_DATA_LEN: usize = VAR_DATA.len();
///
/// // Create a data set and a variable
/// let mut data_set: DataSet = DataSet::new();
/// data_set.add_fixed_dim(DIM_NAME, VAR_DATA_LEN).unwrap();
/// data_set.add_var_i32::<&str>(VAR_NAME_1, &[DIM_NAME]).unwrap();
///
/// assert_eq!(1,                               data_set.num_vars());
/// assert_eq!(true,                            data_set.has_var(VAR_NAME_1));
/// assert_eq!(Some(VAR_DATA_LEN),              data_set.var_len(VAR_NAME_1));
/// assert_eq!(Some(DataType::I32),             data_set.var_data_type(VAR_NAME_1));
/// assert_eq!(false,                           data_set.has_var(VAR_NAME_2));
/// assert_eq!(None,                            data_set.var_len(VAR_NAME_2));
/// assert_eq!(None,                            data_set.var_data_type(VAR_NAME_2));
///
/// // Rename the variable
/// data_set.rename_var(VAR_NAME_1, VAR_NAME_2).unwrap();
///
/// assert_eq!(1,                               data_set.num_vars());
/// assert_eq!(false,                           data_set.has_var(VAR_NAME_1));
/// assert_eq!(None,                            data_set.var_len(VAR_NAME_1));
/// assert_eq!(None,                            data_set.var_data_type(VAR_NAME_1));
/// assert_eq!(true,                            data_set.has_var(VAR_NAME_2));
/// assert_eq!(Some(VAR_DATA_LEN),              data_set.var_len(VAR_NAME_2));
/// assert_eq!(Some(DataType::I32),             data_set.var_data_type(VAR_NAME_2));
/// ```
///
/// ## Remove a variable
///
/// ```
/// use netcdf3::{DataSet, DataType};
///
/// const DIM_NAME: &str = "dim_1";
/// const VAR_NAME: &str = "var_1";
/// const VAR_DATA: [i32; 4] = [1, 2, 3, 4];
/// const VAR_DATA_LEN: usize = VAR_DATA.len();
///
/// // Create a data set and a variable
/// let mut data_set: DataSet = DataSet::new();
///
/// data_set.add_fixed_dim(DIM_NAME, VAR_DATA_LEN).unwrap();
/// data_set.add_var_i32::<&str>(VAR_NAME, &[DIM_NAME]).unwrap();
///
/// assert_eq!(1,                               data_set.num_vars());
/// assert_eq!(true,                            data_set.has_var(VAR_NAME));
/// assert_eq!(Some(VAR_DATA_LEN),              data_set.var_len(VAR_NAME));
/// assert_eq!(Some(DataType::I32),             data_set.var_data_type(VAR_NAME));
///
/// // Remove the variable
/// data_set.remove_var(VAR_NAME).unwrap();
///
/// assert_eq!(0,                               data_set.num_vars());
/// assert_eq!(false,                           data_set.has_var(VAR_NAME));
/// assert_eq!(None,                            data_set.var_len(VAR_NAME));
/// assert_eq!(None,                            data_set.var_data_type(VAR_NAME));
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Variable {
    pub(crate) name: String,
    pub(crate) unlimited_dim: Option<Rc<Dimension>>,
    pub(crate) dims: Vec<Rc<Dimension>>,
    pub(crate) attrs: Vec<Attribute>,
    pub(crate) data_type: DataType,
}

impl Variable {
    pub(in crate::data_set) fn new(
        var_name: &str,
        var_dims: Vec<Rc<Dimension>>,
        data_type: DataType,
    ) -> Result<Variable, InvalidDataSet> {
        // Check if the name of the variable is a valid NetCDF-3 name.
        Variable::check_var_name(var_name)?;

        let unlimited_dim: Option<Rc<Dimension>> = match var_dims.first() {
            None => None,
            Some(first_dim) => match first_dim.is_unlimited() {
                false => None,
                true => Some(Rc::clone(first_dim)),
            },
        };
        Variable::check_dims_validity(var_name, &var_dims)?;

        Ok(Variable {
            name: var_name.to_string(),
            unlimited_dim,
            dims: var_dims,
            attrs: vec![],
            data_type,
            // data: None,
        })
    }

    /// Return the name of the variable.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the data type of the variable.
    ///
    /// # Example
    ///
    /// ```
    /// use netcdf3::{DataSet, Variable, DataType};
    /// const VAR_NAME: &str = "var_1";
    ///
    /// let data_set: DataSet = {
    ///     let mut data_set = DataSet::new();
    ///     data_set.add_var_i32::<&str>(VAR_NAME, &[]).unwrap();
    ///     data_set
    /// };
    ///
    /// let var: &Variable = data_set.get_var(VAR_NAME).unwrap();
    /// assert_eq!(DataType::I32,               var.data_type());
    /// ```
    pub fn data_type(&self) -> DataType {
        self.data_type.clone()
    }

    /// Returns the total number of elements.
    ///
    /// If the variable is a record variable then `len = num_chunks * chunk_len`.
    pub fn len(&self) -> usize {
        self.num_chunks() * self.chunk_len()
    }

    /// Returns whether there are no elements.
    pub fn is_empty(&self) -> bool {
        self.num_chunks() == 0 || self.chunk_len() == 0
    }

    pub fn use_dim(&self, dim_name: &str) -> bool {
        self.dims.iter().any(|dim| *dim.name.borrow() == dim_name)
    }

    /// Returns the number of dimensions (the rank) the the variables
    pub fn num_dims(&self) -> usize {
        self.dims.len()
    }

    /// Returns the list of the dimensions
    pub fn get_dims(&self) -> Vec<Rc<Dimension>> {
        self.dims.clone()
    }

    /// Returns the list of the dimension names
    pub fn dim_names(&self) -> Vec<String> {
        self.dims
            .iter()
            .map(|dim: &Rc<Dimension>| dim.name().to_string())
            .collect()
    }

    /// Returns :
    ///
    /// - `true` if the variable is defined over the *unlimited size* dimension, then has several records
    /// - `false` otherwise
    pub fn is_record_var(&self) -> bool {
        match self.dims.first() {
            None => false,
            Some(first_dim) => first_dim.is_unlimited(),
        }
    }

    /// Returns the number of attributes.
    pub fn num_attrs(&self) -> usize {
        self.attrs.len()
    }

    /// Returns :
    ///
    /// - `true` if the variable has the attribute
    /// - `false` if not
    pub fn has_attr(&self, attr_name: &str) -> bool {
        self.find_attr_from_name(attr_name).is_ok()
    }

    /// Returns the number of elements per chunk.
    ///
    /// If the variable id a *fixed-size* variable then `chunk_len = len`.
    pub fn chunk_len(&self) -> usize {
        let skip_len: usize = if self.is_record_var() { 1 } else { 0 };
        self.dims
            .iter()
            .skip(skip_len)
            .fold(1, |product, dim| product * dim.size())
    }

    /// Returns the size of each chunk (the number of bytes) including the padding bytes.
    ///
    /// # Example
    ///
    /// ```
    /// use netcdf3::{DataSet, Variable};
    ///
    /// const VAR_I8_NAME: &str = "scalar_var_i8";
    /// const VAR_U8_NAME: &str = "scalar_var_u8";
    /// const VAR_I16_NAME: &str = "scalar_var_i16";
    /// const VAR_I32_NAME: &str = "scalar_var_i32";
    /// const VAR_F32_NAME: &str = "scalar_var_f32";
    /// const VAR_F64_NAME: &str = "scalar_var_f64";
    ///
    /// let data_set: DataSet = {
    ///     let mut data_set = DataSet::new();
    ///     data_set.add_var_i8::<&str>(VAR_I8_NAME, &[]).unwrap();
    ///     data_set.add_var_u8::<&str>(VAR_U8_NAME, &[]).unwrap();
    ///     data_set.add_var_i16::<&str>(VAR_I16_NAME, &[]).unwrap();
    ///     data_set.add_var_i32::<&str>(VAR_I32_NAME, &[]).unwrap();
    ///     data_set.add_var_f32::<&str>(VAR_F32_NAME, &[]).unwrap();
    ///     data_set.add_var_f64::<&str>(VAR_F64_NAME, &[]).unwrap();
    ///     data_set
    /// };
    ///
    /// let scalar_var_i8: &Variable = data_set.get_var(VAR_I8_NAME).unwrap();
    /// let scalar_var_u8: &Variable = data_set.get_var(VAR_U8_NAME).unwrap();
    /// let scalar_var_i16: &Variable = data_set.get_var(VAR_I16_NAME).unwrap();
    /// let scalar_var_i32: &Variable = data_set.get_var(VAR_I32_NAME).unwrap();
    /// let scalar_var_f32: &Variable = data_set.get_var(VAR_F32_NAME).unwrap();
    /// let scalar_var_f64: &Variable = data_set.get_var(VAR_F64_NAME).unwrap();
    ///
    /// assert_eq!(4,           scalar_var_i8.chunk_size());
    /// assert_eq!(4,           scalar_var_u8.chunk_size());
    /// assert_eq!(4,           scalar_var_i16.chunk_size());
    /// assert_eq!(4,           scalar_var_i32.chunk_size());
    /// assert_eq!(4,           scalar_var_f32.chunk_size());
    /// assert_eq!(8,           scalar_var_f64.chunk_size());
    /// ```
    pub fn chunk_size(&self) -> usize {
        let mut chunk_size = self.chunk_len() * self.data_type.size_of();
        // append the bytes of the zero padding, if necessary
        chunk_size += compute_padding_size(chunk_size);
        chunk_size
    }

    /// Returns the number of chunks.
    pub fn num_chunks(&self) -> usize {
        match self.dims.first() {
            None => 1, // Case : a scalar *fixed-size* variable
            Some(first_dim) => match &first_dim.size {
                DimensionSize::Fixed(_) => 1,
                DimensionSize::Unlimited(size) => *size.borrow(),
            },
        }
    }

    /// Returns all attributs defined in the dataset or in the variable.
    pub fn get_attrs(&self) -> Vec<&Attribute> {
        self.attrs.iter().collect()
    }

    /// Returns all attributs defined in the dataset or in the variable.
    pub fn get_attr_names(&self) -> Vec<String> {
        self.attrs
            .iter()
            .map(|attr: &Attribute| attr.name().to_string())
            .collect()
    }

    /// Returns a reference counter to the named attribute, return an error if
    /// the attribute is not already defined.
    pub fn get_attr(&self, attr_name: &str) -> Option<&Attribute> {
        self.find_attr_from_name(attr_name)
            .map(|result: (usize, &Attribute)| result.1)
            .ok()
    }

    /// Returns the attribute value as a `&[i8]`.
    ///
    /// Also see the method [Attribute::get_i8](struct.Attribute.html#method.get_i8).
    pub fn get_attr_i8(&self, attr_name: &str) -> Option<&[i8]> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_i8()
    }

    /// Returns the attribute value as a `&[u8]`.
    ///
    /// Also see the method [Attribute::get_u8](struct.Attribute.html#method.get_u8).
    pub fn get_attr_u8(&self, attr_name: &str) -> Option<&[u8]> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_u8()
    }

    /// Returns the attribute value as a `String`.
    ///
    /// Also see the method [Attribute::get_as_string](struct.Attribute.html#method.get_as_string).
    pub fn get_attr_as_string(&self, attr_name: &str) -> Option<String> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_as_string()
    }

    /// Returns the attribute value as a `&[i16]`.
    ///
    /// Also see the method [Attribute::get_i16](struct.Attribute.html#method.get_i16).
    pub fn get_attr_i16(&self, attr_name: &str) -> Option<&[i16]> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_i16()
    }

    /// Returns the attribute value as a `&[i32]`.
    ///
    /// Also see the method [Attribute::get_i32](struct.Attribute.html#method.get_i32).
    pub fn get_attr_i32(&self, attr_name: &str) -> Option<&[i32]> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_i32()
    }

    /// Returns the attribute value as a `&[f32]`.
    ///
    /// Also see the method [Attribute::get_f32](struct.Attribute.html#method.get_f32).
    pub fn get_attr_f32(&self, attr_name: &str) -> Option<&[f32]> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_f32()
    }

    /// Returns the attribute value as a `&[f64]`.
    ///
    /// Also see the method [Attribute::get_f64](struct.Attribute.html#method.get_f64).
    pub fn get_attr_f64(&self, attr_name: &str) -> Option<&[f64]> {
        let attr: &Attribute = self.get_attr(attr_name)?;
        attr.get_f64()
    }

    /// Appends a new attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    fn add_attr(&mut self, new_attr: Attribute) -> Result<(), InvalidDataSet> {
        // Check if an other same name attribute already exists.
        if self.find_attr_from_name(&new_attr.name).is_ok() {
            return Err(InvalidDataSet::VariableAttributeAlreadyExists {
                var_name: self.name.to_string(),
                attr_name: new_attr.name.to_string(),
            });
        }
        // append the new attribute
        self.attrs.push(new_attr);
        Ok(())
    }

    /// Append a new `i8` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_i8(&mut self, attr_name: &str, i8_data: Vec<i8>) -> Result<(), InvalidDataSet> {
        let attr: Attribute =
            Attribute::new_i8(attr_name, i8_data).map_err(|var_attr_name: String| {
                InvalidDataSet::VariableAttributeNameNotValid {
                    var_name: self.name.to_string(),
                    attr_name: var_attr_name,
                }
            })?;
        self.add_attr(attr)?;
        Ok(())
    }

    /// Append a new `u8` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_u8(&mut self, attr_name: &str, u8_data: Vec<u8>) -> Result<(), InvalidDataSet> {
        let attr: Attribute =
            Attribute::new_u8(attr_name, u8_data).map_err(|var_attr_name: String| {
                InvalidDataSet::VariableAttributeNameNotValid {
                    var_name: self.name.to_string(),
                    attr_name: var_attr_name,
                }
            })?;
        self.add_attr(attr)?;
        Ok(())
    }

    /// Append a new `u8` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_string<T: AsRef<str>>(
        &mut self,
        attr_name: &str,
        str_data: T,
    ) -> Result<(), InvalidDataSet> {
        self.add_attr_u8(attr_name, String::from(str_data.as_ref()).into_bytes())
    }

    /// Append a new `i16` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_i16(
        &mut self,
        attr_name: &str,
        i16_data: Vec<i16>,
    ) -> Result<(), InvalidDataSet> {
        let attr: Attribute =
            Attribute::new_i16(attr_name, i16_data).map_err(|var_attr_name: String| {
                InvalidDataSet::VariableAttributeNameNotValid {
                    var_name: self.name.to_string(),
                    attr_name: var_attr_name,
                }
            })?;
        self.add_attr(attr)?;
        Ok(())
    }

    /// Append a new `i32` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_i32(
        &mut self,
        attr_name: &str,
        i32_data: Vec<i32>,
    ) -> Result<(), InvalidDataSet> {
        let attr: Attribute =
            Attribute::new_i32(attr_name, i32_data).map_err(|var_attr_name: String| {
                InvalidDataSet::VariableAttributeNameNotValid {
                    var_name: self.name.to_string(),
                    attr_name: var_attr_name,
                }
            })?;
        self.add_attr(attr)?;
        Ok(())
    }

    /// Append a new `f32` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_f32(
        &mut self,
        attr_name: &str,
        f32_data: Vec<f32>,
    ) -> Result<(), InvalidDataSet> {
        let attr: Attribute =
            Attribute::new_f32(attr_name, f32_data).map_err(|var_attr_name: String| {
                InvalidDataSet::VariableAttributeNameNotValid {
                    var_name: self.name.to_string(),
                    attr_name: var_attr_name,
                }
            })?;
        self.add_attr(attr)?;
        Ok(())
    }

    /// Append a new `f64` attribute.
    ///
    /// An error is returned if an other attribute with the same name has already been added.
    pub fn add_attr_f64(
        &mut self,
        attr_name: &str,
        f64_data: Vec<f64>,
    ) -> Result<(), InvalidDataSet> {
        let attr: Attribute =
            Attribute::new_f64(attr_name, f64_data).map_err(|var_attr_name: String| {
                InvalidDataSet::VariableAttributeNameNotValid {
                    var_name: self.name.to_string(),
                    attr_name: var_attr_name,
                }
            })?;
        self.add_attr(attr)?;
        Ok(())
    }

    /// Rename an existing attribute.
    ///
    /// An error is returned :
    ///  - the `old_attr_name`is not a valid NetCDF-3 name
    ///  - the `old_attr_name` attribute doesn't exist
    ///  - an other `new_attr_name` attribute already exist
    pub(in crate::data_set) fn rename_attr(
        &mut self,
        old_attr_name: &str,
        new_attr_name: &str,
    ) -> Result<(), InvalidDataSet> {
        if old_attr_name == new_attr_name {
            return Ok(());
        }
        // Check if the `old_attr_name` attribute exists
        let renamed_attr_index: usize = self.find_attr_from_name(old_attr_name)?.0;
        // Check if an other `new_attr_name` attribute already exist
        if self.find_attr_from_name(new_attr_name).is_ok() {
            return Err(InvalidDataSet::VariableAttributeAlreadyExists {
                var_name: self.name.to_string(),
                attr_name: new_attr_name.to_string(),
            });
        }

        // Check that `new_attr_name`is a valid NetCDF-3 name
        Attribute::check_attr_name(new_attr_name).map_err(|var_attr_name: String| {
            InvalidDataSet::VariableAttributeNameNotValid {
                var_name: self.name.to_string(),
                attr_name: var_attr_name.to_string(),
            }
        })?;
        let renamed_attr: &mut Attribute = &mut self.attrs[renamed_attr_index];
        renamed_attr.name = new_attr_name.to_string();
        Ok(())
    }

    // Remove the attribute.
    pub fn remove_attr(&mut self, attr_name: &str) -> Result<Attribute, InvalidDataSet> {
        let removed_attr_index: usize = self.find_attr_from_name(attr_name)?.0;
        let removed_attr: Attribute = self.attrs.remove(removed_attr_index);
        Ok(removed_attr)
    }

    /// Find a dataset's attribute from is name.
    pub(in crate::data_set) fn find_attr_from_name(
        &self,
        attr_name: &str,
    ) -> Result<(usize, &Attribute), InvalidDataSet> {
        self.attrs
            .iter()
            .position(|attr| {
                // First find the position
                attr.name() == attr_name
            })
            .map(|index| {
                // Then get the referance to the attribute
                (index, &self.attrs[index])
            })
            .ok_or(InvalidDataSet::VariableAttributeNotDefined {
                var_name: self.name.to_string(),
                attr_name: attr_name.to_string(),
            })
    }

    pub(super) fn check_var_name(var_name: &str) -> Result<(), InvalidDataSet> {
        match is_valid_name(var_name) {
            true => Ok(()),
            false => Err(InvalidDataSet::VariableNameNotValid(var_name.to_string())),
        }
    }

    fn check_dims_validity(var_name: &str, dims: &[Rc<Dimension>]) -> Result<(), InvalidDataSet> {
        if dims.is_empty() {
            return Ok(());
        }
        // Check that the optional unlimited dimension is defined at first
        if let Some(unlim_dim) = dims
            .iter()
            .skip(1)
            .find(|dim: &&Rc<Dimension>| dim.is_unlimited())
        {
            let dim_names: Vec<String> =
                dims.iter().map(|dim: &Rc<Dimension>| dim.name()).collect();
            return Err(InvalidDataSet::UnlimitedDimensionMustBeDefinedFirst {
                var_name: var_name.to_string(),
                unlim_dim_name: unlim_dim.name(),
                get_dim_names: dim_names,
            });
        }
        // Check that the same dimension is not used multiple times by the variable
        let mut repeated_dim_names: Vec<String> = vec![];
        for (i, ref_dim_1) in dims.iter().enumerate().skip(1) {
            let i32ernal_repeated_dim_names: Vec<String> = dims
                .iter()
                .take(i)
                .filter(|ref_dim_2: &&Rc<Dimension>| Rc::ptr_eq(ref_dim_1, ref_dim_2))
                .map(|ref_dim_2: &Rc<Dimension>| ref_dim_2.name())
                .collect();
            repeated_dim_names.extend(i32ernal_repeated_dim_names.into_iter());
        }
        let repeated_dim_names = HashSet::<String>::from_iter(repeated_dim_names);
        if !repeated_dim_names.is_empty() {
            let dim_names: Vec<String> =
                dims.iter().map(|dim: &Rc<Dimension>| dim.name()).collect();
            return Err(InvalidDataSet::DimensionsUsedMultipleTimes {
                var_name: var_name.to_string(),
                get_dim_names: dim_names,
            });
        }
        if dims.len() > NC_MAX_VAR_DIMS {
            return Err(InvalidDataSet::MaximumDimensionsPerVariableExceeded {
                var_name: var_name.to_string(),
                num_dims: dims.len(),
            });
        }
        Ok(())
    }
}