oxigdal-netcdf 0.1.6

NetCDF driver for OxiGDAL - Pure Rust NetCDF-3 with optional NetCDF-4 support
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
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

use crate::attribute::{Attribute, AttributeValue, Attributes};
use crate::dimension::{Dimension, Dimensions};
use crate::error::{NetCdfError, Result};
use crate::variable::{DataType, Variable, Variables};
use byteorder::{BigEndian, ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;

use super::functions::{
    HDF5_SIGNATURE, compress_deflate, decompress_deflate, fletcher32, shuffle_data, unshuffle_data,
};

/// HDF5 superblock version for format detection
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hdf5SuperblockVersion {
    /// Version 0 (HDF5 1.0)
    V0,
    /// Version 1 (HDF5 1.2)
    V1,
    /// Version 2 (HDF5 1.8)
    V2,
    /// Version 3 (HDF5 1.10+)
    V3,
}
impl Hdf5SuperblockVersion {
    /// Create from version byte
    pub(crate) fn from_byte(value: u8) -> Result<Self> {
        match value {
            0 => Ok(Self::V0),
            1 => Ok(Self::V1),
            2 => Ok(Self::V2),
            3 => Ok(Self::V3),
            _ => Err(NetCdfError::UnsupportedVersion {
                version: value,
                message: "Unsupported HDF5 superblock version".to_string(),
            }),
        }
    }
}
/// Chunk information for chunked datasets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkInfo {
    /// Chunk dimensions
    pub dims: Vec<usize>,
    /// Filter pipeline
    pub filters: Vec<CompressionFilter>,
    /// Chunk offsets in file (address map)
    pub chunk_offsets: HashMap<Vec<usize>, u64>,
}
impl ChunkInfo {
    /// Create new chunk info
    #[must_use]
    pub fn new(dims: Vec<usize>) -> Self {
        Self {
            dims,
            filters: Vec::new(),
            chunk_offsets: HashMap::new(),
        }
    }
    /// Add a filter to the pipeline
    pub fn add_filter(&mut self, filter: CompressionFilter) {
        self.filters.push(filter);
    }
    /// Check if compression is enabled
    #[must_use]
    pub fn is_compressed(&self) -> bool {
        self.filters
            .iter()
            .any(|f| matches!(f, CompressionFilter::Deflate(_)))
    }
    /// Calculate total number of chunks
    #[must_use]
    pub fn total_chunks(&self, dataset_dims: &[usize]) -> usize {
        if self.dims.is_empty() || dataset_dims.is_empty() {
            return 0;
        }
        self.dims
            .iter()
            .zip(dataset_dims.iter())
            .map(|(chunk_dim, data_dim)| {
                if *chunk_dim == 0 {
                    0
                } else {
                    (data_dim + chunk_dim - 1) / chunk_dim
                }
            })
            .product()
    }
    /// Get chunk indices for a given element position
    #[must_use]
    pub fn get_chunk_indices(&self, position: &[usize]) -> Vec<usize> {
        position
            .iter()
            .zip(self.dims.iter())
            .map(
                |(pos, chunk_dim)| {
                    if *chunk_dim == 0 { 0 } else { pos / chunk_dim }
                },
            )
            .collect()
    }
}
/// HDF5 object header message types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum Hdf5MessageType {
    /// NIL message
    Nil = 0x0000,
    /// Dataspace message
    Dataspace = 0x0001,
    /// Link info message
    LinkInfo = 0x0002,
    /// Datatype message
    Datatype = 0x0003,
    /// Fill value (old) message
    FillValueOld = 0x0004,
    /// Fill value message
    FillValue = 0x0005,
    /// Link message
    Link = 0x0006,
    /// External file list message
    ExternalFileList = 0x0007,
    /// Data layout message
    DataLayout = 0x0008,
    /// Bogus message
    Bogus = 0x0009,
    /// Group info message
    GroupInfo = 0x000A,
    /// Filter pipeline message
    FilterPipeline = 0x000B,
    /// Attribute message
    Attribute = 0x000C,
    /// Object comment message
    ObjectComment = 0x000D,
    /// Object modification time (old) message
    ObjectModTimeOld = 0x000E,
    /// Shared message table message
    SharedMessageTable = 0x000F,
    /// Object header continuation message
    ObjectHeaderContinuation = 0x0010,
    /// Symbol table message
    SymbolTable = 0x0011,
    /// Object modification time message
    ObjectModTime = 0x0012,
    /// B-tree K values message
    BTreeKValues = 0x0013,
    /// Driver info message
    DriverInfo = 0x0014,
    /// Attribute info message
    AttributeInfo = 0x0015,
    /// Object reference count message
    ObjectRefCount = 0x0016,
}
impl Hdf5MessageType {
    /// Create from u16 value
    pub(crate) fn from_u16(value: u16) -> Option<Self> {
        match value {
            0x0000 => Some(Self::Nil),
            0x0001 => Some(Self::Dataspace),
            0x0002 => Some(Self::LinkInfo),
            0x0003 => Some(Self::Datatype),
            0x0004 => Some(Self::FillValueOld),
            0x0005 => Some(Self::FillValue),
            0x0006 => Some(Self::Link),
            0x0007 => Some(Self::ExternalFileList),
            0x0008 => Some(Self::DataLayout),
            0x0009 => Some(Self::Bogus),
            0x000A => Some(Self::GroupInfo),
            0x000B => Some(Self::FilterPipeline),
            0x000C => Some(Self::Attribute),
            0x000D => Some(Self::ObjectComment),
            0x000E => Some(Self::ObjectModTimeOld),
            0x000F => Some(Self::SharedMessageTable),
            0x0010 => Some(Self::ObjectHeaderContinuation),
            0x0011 => Some(Self::SymbolTable),
            0x0012 => Some(Self::ObjectModTime),
            0x0013 => Some(Self::BTreeKValues),
            0x0014 => Some(Self::DriverInfo),
            0x0015 => Some(Self::AttributeInfo),
            0x0016 => Some(Self::ObjectRefCount),
            _ => None,
        }
    }
}
/// Extended variable information for NetCDF-4
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Nc4VariableInfo {
    /// Base variable
    pub variable: Variable,
    /// Chunk info (if chunked)
    pub chunk_info: Option<ChunkInfo>,
    /// Fill value
    pub fill_value: Option<AttributeValue>,
    /// Data offset in file
    pub data_offset: u64,
    /// Data size in bytes
    pub data_size: u64,
    /// Is compressed
    pub is_compressed: bool,
}
impl Nc4VariableInfo {
    /// Create new variable info
    pub fn new(variable: Variable) -> Self {
        Self {
            variable,
            chunk_info: None,
            fill_value: None,
            data_offset: 0,
            data_size: 0,
            is_compressed: false,
        }
    }
    /// Get variable name
    #[must_use]
    pub fn name(&self) -> &str {
        self.variable.name()
    }
    /// Get data type
    #[must_use]
    pub fn data_type(&self) -> DataType {
        self.variable.data_type()
    }
    /// Check if this is chunked storage
    #[must_use]
    pub fn is_chunked(&self) -> bool {
        self.chunk_info.is_some()
    }
}
/// Byte order for HDF5 data
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Hdf5ByteOrder {
    /// Little-endian
    #[default]
    LittleEndian,
    /// Big-endian
    BigEndian,
}
/// HDF5 superblock information
#[derive(Debug, Clone)]
pub struct Hdf5Superblock {
    /// Superblock version
    pub version: Hdf5SuperblockVersion,
    /// Size of offsets in bytes
    pub offset_size: u8,
    /// Size of lengths in bytes
    pub length_size: u8,
    /// Group leaf node K
    pub group_leaf_k: u16,
    /// Group internal node K
    pub group_internal_k: u16,
    /// Base address
    pub base_address: u64,
    /// Root group object header address
    pub root_group_address: u64,
    /// End of file address
    pub eof_address: u64,
}
impl Hdf5Superblock {
    /// Parse superblock from reader
    pub fn parse<R: Read + Seek>(reader: &mut R) -> Result<Self> {
        let mut signature = [0u8; 8];
        reader
            .read_exact(&mut signature)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        if signature != HDF5_SIGNATURE {
            return Err(NetCdfError::InvalidFormat(
                "Not a valid HDF5/NetCDF-4 file: invalid signature".to_string(),
            ));
        }
        let version_byte = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let version = Hdf5SuperblockVersion::from_byte(version_byte)?;
        match version {
            Hdf5SuperblockVersion::V0 | Hdf5SuperblockVersion::V1 => {
                Self::parse_v0_v1(reader, version)
            }
            Hdf5SuperblockVersion::V2 | Hdf5SuperblockVersion::V3 => {
                Self::parse_v2_v3(reader, version)
            }
        }
    }
    /// Parse superblock version 0 or 1
    fn parse_v0_v1<R: Read + Seek>(reader: &mut R, version: Hdf5SuperblockVersion) -> Result<Self> {
        let _free_space_version = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let _root_group_version = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let _reserved1 = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let _shared_header_version = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let offset_size = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let length_size = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let _reserved2 = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let group_leaf_k = reader
            .read_u16::<LittleEndian>()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let group_internal_k = reader
            .read_u16::<LittleEndian>()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let _file_consistency_flags = reader
            .read_u32::<LittleEndian>()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        if matches!(version, Hdf5SuperblockVersion::V1) {
            let _indexed_storage_k = reader
                .read_u16::<LittleEndian>()
                .map_err(|e| NetCdfError::Io(e.to_string()))?;
            let _reserved3 = reader
                .read_u16::<LittleEndian>()
                .map_err(|e| NetCdfError::Io(e.to_string()))?;
        }
        let base_address = Self::read_offset(reader, offset_size)?;
        let _free_space_address = Self::read_offset(reader, offset_size)?;
        let eof_address = Self::read_offset(reader, offset_size)?;
        let _driver_info_address = Self::read_offset(reader, offset_size)?;
        let _link_name_offset = Self::read_offset(reader, offset_size)?;
        let root_group_address = Self::read_offset(reader, offset_size)?;
        Ok(Self {
            version,
            offset_size,
            length_size,
            group_leaf_k,
            group_internal_k,
            base_address,
            root_group_address,
            eof_address,
        })
    }
    /// Parse superblock version 2 or 3
    fn parse_v2_v3<R: Read + Seek>(reader: &mut R, version: Hdf5SuperblockVersion) -> Result<Self> {
        let offset_size = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let length_size = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let _file_consistency_flags = reader
            .read_u8()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let base_address = Self::read_offset(reader, offset_size)?;
        let _sb_ext_address = Self::read_offset(reader, offset_size)?;
        let eof_address = Self::read_offset(reader, offset_size)?;
        let root_group_address = Self::read_offset(reader, offset_size)?;
        let _checksum = reader
            .read_u32::<LittleEndian>()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        Ok(Self {
            version,
            offset_size,
            length_size,
            group_leaf_k: 4,
            group_internal_k: 16,
            base_address,
            root_group_address,
            eof_address,
        })
    }
    /// Read offset value
    fn read_offset<R: Read>(reader: &mut R, size: u8) -> Result<u64> {
        match size {
            1 => Ok(u64::from(
                reader
                    .read_u8()
                    .map_err(|e| NetCdfError::Io(e.to_string()))?,
            )),
            2 => Ok(u64::from(
                reader
                    .read_u16::<LittleEndian>()
                    .map_err(|e| NetCdfError::Io(e.to_string()))?,
            )),
            4 => Ok(u64::from(
                reader
                    .read_u32::<LittleEndian>()
                    .map_err(|e| NetCdfError::Io(e.to_string()))?,
            )),
            8 => reader
                .read_u64::<LittleEndian>()
                .map_err(|e| NetCdfError::Io(e.to_string())),
            _ => Err(NetCdfError::InvalidFormat(format!(
                "Invalid offset size: {}",
                size
            ))),
        }
    }
    /// Read length value
    fn read_length<R: Read>(reader: &mut R, size: u8) -> Result<u64> {
        Self::read_offset(reader, size)
    }
}
/// A group in a NetCDF-4 file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Nc4Group {
    /// Group name
    name: String,
    /// Full path
    path: String,
    /// Dimensions defined in this group
    dimensions: Dimensions,
    /// Variables defined in this group
    variables: Variables,
    /// Attributes
    attributes: Attributes,
    /// Child groups
    groups: Vec<Nc4Group>,
}
impl Nc4Group {
    /// Create a new root group
    #[must_use]
    pub fn root() -> Self {
        Self {
            name: String::new(),
            path: "/".to_string(),
            dimensions: Dimensions::new(),
            variables: Variables::new(),
            attributes: Attributes::new(),
            groups: Vec::new(),
        }
    }
    /// Create a new named group
    pub fn new(name: impl Into<String>, parent_path: &str) -> Result<Self> {
        let name = name.into();
        if name.is_empty() {
            return Err(NetCdfError::InvalidFormat(
                "Group name cannot be empty".to_string(),
            ));
        }
        let path = if parent_path == "/" {
            format!("/{}", name)
        } else {
            format!("{}/{}", parent_path, name)
        };
        Ok(Self {
            name,
            path,
            dimensions: Dimensions::new(),
            variables: Variables::new(),
            attributes: Attributes::new(),
            groups: Vec::new(),
        })
    }
    /// Get group name
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
    /// Get full path
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }
    /// Get dimensions
    #[must_use]
    pub const fn dimensions(&self) -> &Dimensions {
        &self.dimensions
    }
    /// Get mutable dimensions
    pub fn dimensions_mut(&mut self) -> &mut Dimensions {
        &mut self.dimensions
    }
    /// Get variables
    #[must_use]
    pub const fn variables(&self) -> &Variables {
        &self.variables
    }
    /// Get mutable variables
    pub fn variables_mut(&mut self) -> &mut Variables {
        &mut self.variables
    }
    /// Get attributes
    #[must_use]
    pub const fn attributes(&self) -> &Attributes {
        &self.attributes
    }
    /// Get mutable attributes
    pub fn attributes_mut(&mut self) -> &mut Attributes {
        &mut self.attributes
    }
    /// Get child groups
    #[must_use]
    pub fn groups(&self) -> &[Nc4Group] {
        &self.groups
    }
    /// Add a child group
    pub fn add_group(&mut self, group: Nc4Group) {
        self.groups.push(group);
    }
    /// Find a group by path (relative to this group)
    #[must_use]
    pub fn find_group(&self, path: &str) -> Option<&Nc4Group> {
        let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        self.find_group_recursive(&parts)
    }
    fn find_group_recursive(&self, parts: &[&str]) -> Option<&Nc4Group> {
        if parts.is_empty() {
            return Some(self);
        }
        let first = parts[0];
        for group in &self.groups {
            if group.name == first {
                return group.find_group_recursive(&parts[1..]);
            }
        }
        None
    }
    /// Get all dimension names (including parent groups)
    #[must_use]
    pub fn all_dimension_names(&self) -> Vec<String> {
        self.dimensions
            .names()
            .iter()
            .map(|s| (*s).to_string())
            .collect()
    }
}
/// HDF5 datatype class
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Hdf5DatatypeClass {
    /// Fixed-point (integer)
    FixedPoint = 0,
    /// Floating-point
    FloatingPoint = 1,
    /// Time
    Time = 2,
    /// String
    String = 3,
    /// Bitfield
    Bitfield = 4,
    /// Opaque
    Opaque = 5,
    /// Compound
    Compound = 6,
    /// Reference
    Reference = 7,
    /// Enumeration
    Enum = 8,
    /// Variable-length
    VarLen = 9,
    /// Array
    Array = 10,
}
impl Hdf5DatatypeClass {
    /// Create from byte value
    pub(crate) fn from_byte(value: u8) -> Result<Self> {
        match value & 0x0F {
            0 => Ok(Self::FixedPoint),
            1 => Ok(Self::FloatingPoint),
            2 => Ok(Self::Time),
            3 => Ok(Self::String),
            4 => Ok(Self::Bitfield),
            5 => Ok(Self::Opaque),
            6 => Ok(Self::Compound),
            7 => Ok(Self::Reference),
            8 => Ok(Self::Enum),
            9 => Ok(Self::VarLen),
            10 => Ok(Self::Array),
            _ => Err(NetCdfError::InvalidFormat(format!(
                "Unknown HDF5 datatype class: {}",
                value
            ))),
        }
    }
}
/// Pure Rust NetCDF-4 file reader
pub struct Nc4Reader {
    /// File reader
    reader: BufReader<File>,
    /// HDF5 superblock
    superblock: Hdf5Superblock,
    /// Root group
    root_group: Nc4Group,
    /// Variable info cache
    variable_info: HashMap<String, Nc4VariableInfo>,
}
impl Nc4Reader {
    /// Open a NetCDF-4 file for reading
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::open(path.as_ref()).map_err(|_| NetCdfError::FileNotFound {
            path: path.as_ref().to_string_lossy().to_string(),
        })?;
        let mut reader = BufReader::new(file);
        let superblock = Hdf5Superblock::parse(&mut reader)?;
        let mut nc4_reader = Self {
            reader,
            superblock,
            root_group: Nc4Group::root(),
            variable_info: HashMap::new(),
        };
        nc4_reader.parse_root_group()?;
        Ok(nc4_reader)
    }
    /// Parse the root group structure
    fn parse_root_group(&mut self) -> Result<()> {
        self.reader
            .seek(SeekFrom::Start(self.superblock.root_group_address))
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.root_group = Nc4Group::root();
        Ok(())
    }
    /// Get the root group
    #[must_use]
    pub fn root_group(&self) -> &Nc4Group {
        &self.root_group
    }
    /// Get dimensions from root group
    #[must_use]
    pub fn dimensions(&self) -> &Dimensions {
        self.root_group.dimensions()
    }
    /// Get variables from root group
    #[must_use]
    pub fn variables(&self) -> &Variables {
        self.root_group.variables()
    }
    /// Get global attributes
    #[must_use]
    pub fn global_attributes(&self) -> &Attributes {
        self.root_group.attributes()
    }
    /// Get a group by path
    #[must_use]
    pub fn group(&self, path: &str) -> Option<&Nc4Group> {
        self.root_group.find_group(path)
    }
    /// Read variable data as f32
    pub fn read_f32(&mut self, var_name: &str) -> Result<Vec<f32>> {
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        self.reader
            .seek(SeekFrom::Start(info.data_offset))
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let mut raw_data = vec![0u8; info.data_size as usize];
        self.reader
            .read_exact(&mut raw_data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let data = if let Some(ref chunk_info) = info.chunk_info {
            self.decompress_data(&raw_data, chunk_info)?
        } else {
            raw_data
        };
        let n_elements = data.len() / 4;
        let mut result = Vec::with_capacity(n_elements);
        for chunk in data.chunks_exact(4) {
            result.push(LittleEndian::read_f32(chunk));
        }
        Ok(result)
    }
    /// Read variable data as f64
    pub fn read_f64(&mut self, var_name: &str) -> Result<Vec<f64>> {
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        self.reader
            .seek(SeekFrom::Start(info.data_offset))
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let mut raw_data = vec![0u8; info.data_size as usize];
        self.reader
            .read_exact(&mut raw_data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let data = if let Some(ref chunk_info) = info.chunk_info {
            self.decompress_data(&raw_data, chunk_info)?
        } else {
            raw_data
        };
        let n_elements = data.len() / 8;
        let mut result = Vec::with_capacity(n_elements);
        for chunk in data.chunks_exact(8) {
            result.push(LittleEndian::read_f64(chunk));
        }
        Ok(result)
    }
    /// Read variable data as i32
    pub fn read_i32(&mut self, var_name: &str) -> Result<Vec<i32>> {
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        self.reader
            .seek(SeekFrom::Start(info.data_offset))
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let mut raw_data = vec![0u8; info.data_size as usize];
        self.reader
            .read_exact(&mut raw_data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let data = if let Some(ref chunk_info) = info.chunk_info {
            self.decompress_data(&raw_data, chunk_info)?
        } else {
            raw_data
        };
        let n_elements = data.len() / 4;
        let mut result = Vec::with_capacity(n_elements);
        for chunk in data.chunks_exact(4) {
            result.push(LittleEndian::read_i32(chunk));
        }
        Ok(result)
    }
    /// Read a chunk of data
    pub fn read_chunk(&mut self, var_name: &str, chunk_indices: &[usize]) -> Result<Vec<u8>> {
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        let chunk_info = info
            .chunk_info
            .as_ref()
            .ok_or_else(|| NetCdfError::InvalidFormat("Variable is not chunked".to_string()))?;
        let chunk_key = chunk_indices.to_vec();
        let chunk_offset =
            chunk_info
                .chunk_offsets
                .get(&chunk_key)
                .ok_or_else(|| NetCdfError::InvalidShape {
                    message: format!("Chunk not found: {:?}", chunk_indices),
                })?;
        self.reader
            .seek(SeekFrom::Start(*chunk_offset))
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let element_size = info.data_type().size();
        let chunk_elements: usize = chunk_info.dims.iter().product();
        let chunk_size = chunk_elements * element_size;
        let mut data = vec![0u8; chunk_size];
        self.reader
            .read_exact(&mut data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.decompress_data(&data, chunk_info)
    }
    /// Decompress data based on filter pipeline
    fn decompress_data(&self, data: &[u8], chunk_info: &ChunkInfo) -> Result<Vec<u8>> {
        let mut result = data.to_vec();
        for filter in chunk_info.filters.iter().rev() {
            result = match filter {
                CompressionFilter::Deflate(_) => {
                    let uncompressed_size = chunk_info.dims.iter().product::<usize>() * 8;
                    decompress_deflate(&result, uncompressed_size)?
                }
                CompressionFilter::Shuffle => unshuffle_data(&result, 4),
                CompressionFilter::Fletcher32 => {
                    if result.len() >= 4 {
                        result.truncate(result.len() - 4);
                    }
                    result
                }
                _ => result,
            };
        }
        Ok(result)
    }
    /// Check if file is a valid NetCDF-4 file
    pub fn is_netcdf4<P: AsRef<Path>>(path: P) -> bool {
        if let Ok(file) = File::open(path) {
            let mut reader = BufReader::new(file);
            Hdf5Superblock::parse(&mut reader).is_ok()
        } else {
            false
        }
    }
}
/// Pure Rust NetCDF-4 file writer
pub struct Nc4Writer {
    /// File writer
    writer: BufWriter<File>,
    /// Superblock version to use
    superblock_version: Hdf5SuperblockVersion,
    /// Offset size
    offset_size: u8,
    /// Length size
    length_size: u8,
    /// Root group
    root_group: Nc4Group,
    /// Variable info
    variable_info: HashMap<String, Nc4VariableInfo>,
    /// Current file offset
    current_offset: u64,
    /// Is in define mode
    in_define_mode: bool,
}
impl Nc4Writer {
    /// Create a new NetCDF-4 file
    pub fn create<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::create(path.as_ref())
            .map_err(|e| NetCdfError::Io(format!("Failed to create file: {}", e)))?;
        let writer = BufWriter::new(file);
        Ok(Self {
            writer,
            superblock_version: Hdf5SuperblockVersion::V2,
            offset_size: 8,
            length_size: 8,
            root_group: Nc4Group::root(),
            variable_info: HashMap::new(),
            current_offset: 0,
            in_define_mode: true,
        })
    }
    /// Add a dimension
    pub fn add_dimension(&mut self, dim: Dimension) -> Result<()> {
        if !self.in_define_mode {
            return Err(NetCdfError::InvalidFormat(
                "Cannot add dimension in data mode".to_string(),
            ));
        }
        self.root_group.dimensions_mut().add(dim)
    }
    /// Add a variable
    pub fn add_variable(&mut self, var: Variable) -> Result<()> {
        if !self.in_define_mode {
            return Err(NetCdfError::InvalidFormat(
                "Cannot add variable in data mode".to_string(),
            ));
        }
        let var_info = Nc4VariableInfo::new(var.clone());
        self.variable_info.insert(var.name().to_string(), var_info);
        self.root_group.variables_mut().add(var)
    }
    /// Add a global attribute
    pub fn add_global_attribute(&mut self, attr: Attribute) -> Result<()> {
        self.root_group.attributes_mut().add(attr)
    }
    /// Add a variable attribute
    pub fn add_variable_attribute(&mut self, var_name: &str, attr: Attribute) -> Result<()> {
        let var = self
            .root_group
            .variables_mut()
            .get_mut(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?;
        var.attributes_mut().add(attr)
    }
    /// Set chunking for a variable
    pub fn set_chunking(&mut self, var_name: &str, chunk_dims: Vec<usize>) -> Result<()> {
        if !self.in_define_mode {
            return Err(NetCdfError::InvalidFormat(
                "Cannot set chunking in data mode".to_string(),
            ));
        }
        let info =
            self.variable_info
                .get_mut(var_name)
                .ok_or_else(|| NetCdfError::VariableNotFound {
                    name: var_name.to_string(),
                })?;
        info.chunk_info = Some(ChunkInfo::new(chunk_dims));
        Ok(())
    }
    /// Set compression for a variable
    pub fn set_compression(&mut self, var_name: &str, level: u8) -> Result<()> {
        if !self.in_define_mode {
            return Err(NetCdfError::InvalidFormat(
                "Cannot set compression in data mode".to_string(),
            ));
        }
        let info =
            self.variable_info
                .get_mut(var_name)
                .ok_or_else(|| NetCdfError::VariableNotFound {
                    name: var_name.to_string(),
                })?;
        if let Some(ref mut chunk_info) = info.chunk_info {
            chunk_info.add_filter(CompressionFilter::Deflate(level));
            info.is_compressed = true;
        } else {
            return Err(NetCdfError::InvalidFormat(
                "Must set chunking before compression".to_string(),
            ));
        }
        Ok(())
    }
    /// Enable shuffle filter for a variable
    pub fn set_shuffle(&mut self, var_name: &str) -> Result<()> {
        if !self.in_define_mode {
            return Err(NetCdfError::InvalidFormat(
                "Cannot set shuffle in data mode".to_string(),
            ));
        }
        let info =
            self.variable_info
                .get_mut(var_name)
                .ok_or_else(|| NetCdfError::VariableNotFound {
                    name: var_name.to_string(),
                })?;
        if let Some(ref mut chunk_info) = info.chunk_info {
            chunk_info.add_filter(CompressionFilter::Shuffle);
        } else {
            return Err(NetCdfError::InvalidFormat(
                "Must set chunking before shuffle".to_string(),
            ));
        }
        Ok(())
    }
    /// End define mode and write header
    pub fn end_define_mode(&mut self) -> Result<()> {
        if !self.in_define_mode {
            return Ok(());
        }
        self.write_superblock()?;
        self.write_root_group()?;
        self.in_define_mode = false;
        Ok(())
    }
    /// Write HDF5 superblock
    fn write_superblock(&mut self) -> Result<()> {
        self.writer
            .write_all(&HDF5_SIGNATURE)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.current_offset += 8;
        match self.superblock_version {
            Hdf5SuperblockVersion::V2 | Hdf5SuperblockVersion::V3 => {
                self.writer
                    .write_u8(2)
                    .map_err(|e| NetCdfError::Io(e.to_string()))?;
                self.writer
                    .write_u8(self.offset_size)
                    .map_err(|e| NetCdfError::Io(e.to_string()))?;
                self.writer
                    .write_u8(self.length_size)
                    .map_err(|e| NetCdfError::Io(e.to_string()))?;
                self.writer
                    .write_u8(0)
                    .map_err(|e| NetCdfError::Io(e.to_string()))?;
                self.write_offset(0)?;
                self.write_offset(u64::MAX)?;
                self.write_offset(0)?;
                let root_group_offset = 48u64;
                self.write_offset(root_group_offset)?;
                self.writer
                    .write_u32::<LittleEndian>(0)
                    .map_err(|e| NetCdfError::Io(e.to_string()))?;
                self.current_offset = 48;
            }
            _ => {
                return Err(NetCdfError::InvalidFormat(
                    "Only superblock version 2/3 supported for writing".to_string(),
                ));
            }
        }
        Ok(())
    }
    /// Write offset value
    fn write_offset(&mut self, value: u64) -> Result<()> {
        match self.offset_size {
            1 => self
                .writer
                .write_u8(value as u8)
                .map_err(|e| NetCdfError::Io(e.to_string()))?,
            2 => self
                .writer
                .write_u16::<LittleEndian>(value as u16)
                .map_err(|e| NetCdfError::Io(e.to_string()))?,
            4 => self
                .writer
                .write_u32::<LittleEndian>(value as u32)
                .map_err(|e| NetCdfError::Io(e.to_string()))?,
            8 => self
                .writer
                .write_u64::<LittleEndian>(value)
                .map_err(|e| NetCdfError::Io(e.to_string()))?,
            _ => {
                return Err(NetCdfError::InvalidFormat(format!(
                    "Invalid offset size: {}",
                    self.offset_size
                )));
            }
        }
        self.current_offset += u64::from(self.offset_size);
        Ok(())
    }
    /// Write root group structure
    fn write_root_group(&mut self) -> Result<()> {
        self.writer
            .write_all(b"OHDR")
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.writer
            .write_u8(2)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.writer
            .write_u8(0)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.writer
            .write_u16::<LittleEndian>(0)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.writer
            .write_u16::<LittleEndian>(0)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        let chunk_size = 64u32;
        self.writer
            .write_u32::<LittleEndian>(chunk_size)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        self.current_offset += 16;
        Ok(())
    }
    /// Write f32 data to a variable
    pub fn write_f32(&mut self, var_name: &str, data: &[f32]) -> Result<()> {
        if self.in_define_mode {
            self.end_define_mode()?;
        }
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        let mut raw_data = Vec::with_capacity(data.len() * 4);
        for &value in data {
            raw_data
                .write_f32::<LittleEndian>(value)
                .map_err(|e| NetCdfError::Io(e.to_string()))?;
        }
        let write_data = if let Some(ref chunk_info) = info.chunk_info {
            self.compress_data(&raw_data, chunk_info, 4)?
        } else {
            raw_data
        };
        self.writer
            .write_all(&write_data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        if let Some(var_info) = self.variable_info.get_mut(var_name) {
            var_info.data_offset = self.current_offset;
            var_info.data_size = write_data.len() as u64;
        }
        self.current_offset += write_data.len() as u64;
        Ok(())
    }
    /// Write f64 data to a variable
    pub fn write_f64(&mut self, var_name: &str, data: &[f64]) -> Result<()> {
        if self.in_define_mode {
            self.end_define_mode()?;
        }
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        let mut raw_data = Vec::with_capacity(data.len() * 8);
        for &value in data {
            raw_data
                .write_f64::<LittleEndian>(value)
                .map_err(|e| NetCdfError::Io(e.to_string()))?;
        }
        let write_data = if let Some(ref chunk_info) = info.chunk_info {
            self.compress_data(&raw_data, chunk_info, 8)?
        } else {
            raw_data
        };
        self.writer
            .write_all(&write_data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        if let Some(var_info) = self.variable_info.get_mut(var_name) {
            var_info.data_offset = self.current_offset;
            var_info.data_size = write_data.len() as u64;
        }
        self.current_offset += write_data.len() as u64;
        Ok(())
    }
    /// Write i32 data to a variable
    pub fn write_i32(&mut self, var_name: &str, data: &[i32]) -> Result<()> {
        if self.in_define_mode {
            self.end_define_mode()?;
        }
        let info = self
            .variable_info
            .get(var_name)
            .ok_or_else(|| NetCdfError::VariableNotFound {
                name: var_name.to_string(),
            })?
            .clone();
        let mut raw_data = Vec::with_capacity(data.len() * 4);
        for &value in data {
            raw_data
                .write_i32::<LittleEndian>(value)
                .map_err(|e| NetCdfError::Io(e.to_string()))?;
        }
        let write_data = if let Some(ref chunk_info) = info.chunk_info {
            self.compress_data(&raw_data, chunk_info, 4)?
        } else {
            raw_data
        };
        self.writer
            .write_all(&write_data)
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        if let Some(var_info) = self.variable_info.get_mut(var_name) {
            var_info.data_offset = self.current_offset;
            var_info.data_size = write_data.len() as u64;
        }
        self.current_offset += write_data.len() as u64;
        Ok(())
    }
    /// Compress data based on filter pipeline
    fn compress_data(
        &self,
        data: &[u8],
        chunk_info: &ChunkInfo,
        element_size: usize,
    ) -> Result<Vec<u8>> {
        let mut result = data.to_vec();
        for filter in &chunk_info.filters {
            result = match filter {
                CompressionFilter::Shuffle => shuffle_data(&result, element_size),
                CompressionFilter::Deflate(level) => compress_deflate(&result, *level)?,
                CompressionFilter::Fletcher32 => {
                    let checksum = fletcher32(&result);
                    result.extend_from_slice(&checksum.to_le_bytes());
                    result
                }
                _ => result,
            };
        }
        Ok(result)
    }
    /// Close the file
    pub fn close(mut self) -> Result<()> {
        if self.in_define_mode {
            self.end_define_mode()?;
        }
        self.writer
            .flush()
            .map_err(|e| NetCdfError::Io(e.to_string()))?;
        Ok(())
    }
    /// Add a new group
    pub fn add_group(&mut self, path: &str) -> Result<()> {
        if !self.in_define_mode {
            return Err(NetCdfError::InvalidFormat(
                "Cannot add group in data mode".to_string(),
            ));
        }
        let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        if parts.is_empty() {
            return Err(NetCdfError::InvalidFormat("Invalid group path".to_string()));
        }
        let mut current_path = String::new();
        for part in parts {
            let parent_path = if current_path.is_empty() {
                "/".to_string()
            } else {
                current_path.clone()
            };
            let new_group = Nc4Group::new(part, &parent_path)?;
            current_path = new_group.path().to_string();
            self.root_group.add_group(new_group);
        }
        Ok(())
    }
}
/// Compression filter type for NetCDF-4 data
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompressionFilter {
    /// No compression
    None,
    /// Deflate (zlib) compression with level 0-9
    Deflate(u8),
    /// Shuffle filter (byte reordering)
    Shuffle,
    /// Fletcher32 checksum
    Fletcher32,
    /// SZIP compression
    Szip,
    /// LZF compression
    Lzf,
    /// Blosc compression
    Blosc,
}
impl CompressionFilter {
    /// Get the HDF5 filter ID
    #[must_use]
    pub const fn filter_id(&self) -> u16 {
        match self {
            Self::None => 0,
            Self::Deflate(_) => 1,
            Self::Shuffle => 2,
            Self::Fletcher32 => 3,
            Self::Szip => 4,
            Self::Lzf => 32000,
            Self::Blosc => 32001,
        }
    }
}