oxiphysics-io 0.1.1

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

//! HDF5-inspired binary format for simulation checkpoints and time series data.
//!
//! The `OxiFile` format stores hierarchical groups of typed datasets with
//! attributes, serialized to a compact binary representation.
#![allow(missing_docs)]
#![allow(dead_code)]

use std::fs;
use std::io::Write;

// ---------------------------------------------------------------------------
// DataType
// ---------------------------------------------------------------------------

/// Supported element types for datasets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataType {
    Float32,
    Float64,
    Int32,
    Int64,
    UInt8,
    UInt32,
}

impl DataType {
    /// Returns the byte size of a single element of this type.
    pub fn size_bytes(&self) -> usize {
        match self {
            DataType::Float32 => 4,
            DataType::Float64 => 8,
            DataType::Int32 => 4,
            DataType::Int64 => 8,
            DataType::UInt8 => 1,
            DataType::UInt32 => 4,
        }
    }

    fn tag(&self) -> u8 {
        match self {
            DataType::Float32 => 0,
            DataType::Float64 => 1,
            DataType::Int32 => 2,
            DataType::Int64 => 3,
            DataType::UInt8 => 4,
            DataType::UInt32 => 5,
        }
    }

    fn from_tag(tag: u8) -> Result<Self, String> {
        match tag {
            0 => Ok(DataType::Float32),
            1 => Ok(DataType::Float64),
            2 => Ok(DataType::Int32),
            3 => Ok(DataType::Int64),
            4 => Ok(DataType::UInt8),
            5 => Ok(DataType::UInt32),
            _ => Err(format!("Unknown DataType tag: {}", tag)),
        }
    }
}

// ---------------------------------------------------------------------------
// DatasetShape
// ---------------------------------------------------------------------------

/// Describes the shape (dimensions) of a dataset.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DatasetShape {
    pub dims: Vec<usize>,
}

impl DatasetShape {
    /// Creates a new shape from a list of dimensions.
    pub fn new(dims: Vec<usize>) -> Self {
        Self { dims }
    }

    /// Total number of elements (product of all dimensions).
    pub fn total_elements(&self) -> usize {
        if self.dims.is_empty() {
            return 1; // scalar
        }
        self.dims.iter().product()
    }

    /// Returns `true` if the shape represents a scalar (no dimensions).
    pub fn is_scalar(&self) -> bool {
        self.dims.is_empty()
    }

    /// Number of dimensions.
    pub fn rank(&self) -> usize {
        self.dims.len()
    }
}

// ---------------------------------------------------------------------------
// Attribute / AttributeValue
// ---------------------------------------------------------------------------

/// A named metadata attribute attached to a dataset or group.
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
    pub name: String,
    pub value: AttributeValue,
}

impl Attribute {
    /// Creates a new attribute with the given name and value.
    pub fn new(name: impl Into<String>, value: AttributeValue) -> Self {
        Self {
            name: name.into(),
            value,
        }
    }
}

/// Possible values for an attribute.
#[derive(Debug, Clone, PartialEq)]
pub enum AttributeValue {
    Int(i64),
    Float(f64),
    Text(String),
    IntArray(Vec<i64>),
    FloatArray(Vec<f64>),
}

impl AttributeValue {
    fn tag(&self) -> u8 {
        match self {
            AttributeValue::Int(_) => 0,
            AttributeValue::Float(_) => 1,
            AttributeValue::Text(_) => 2,
            AttributeValue::IntArray(_) => 3,
            AttributeValue::FloatArray(_) => 4,
        }
    }
}

// ---------------------------------------------------------------------------
// Dataset
// ---------------------------------------------------------------------------

/// A named, typed, shaped array of raw bytes with optional attributes.
#[derive(Debug, Clone)]
pub struct Dataset {
    pub name: String,
    pub dtype: DataType,
    pub shape: DatasetShape,
    /// Raw little-endian bytes of the dataset contents.
    pub data: Vec<u8>,
    pub attributes: Vec<Attribute>,
}

impl Dataset {
    /// Constructs a dataset from a slice of `f64` values.
    pub fn from_f64_slice(name: &str, data: &[f64], shape: DatasetShape) -> Self {
        let mut bytes = Vec::with_capacity(data.len() * 8);
        for &v in data {
            bytes.extend_from_slice(&v.to_le_bytes());
        }
        Self {
            name: name.to_string(),
            dtype: DataType::Float64,
            shape,
            data: bytes,
            attributes: Vec::new(),
        }
    }

    /// Constructs a dataset from a slice of `f32` values.
    pub fn from_f32_slice(name: &str, data: &[f32], shape: DatasetShape) -> Self {
        let mut bytes = Vec::with_capacity(data.len() * 4);
        for &v in data {
            bytes.extend_from_slice(&v.to_le_bytes());
        }
        Self {
            name: name.to_string(),
            dtype: DataType::Float32,
            shape,
            data: bytes,
            attributes: Vec::new(),
        }
    }

    /// Constructs a dataset from a slice of `i32` values.
    pub fn from_i32_slice(name: &str, data: &[i32], shape: DatasetShape) -> Self {
        let mut bytes = Vec::with_capacity(data.len() * 4);
        for &v in data {
            bytes.extend_from_slice(&v.to_le_bytes());
        }
        Self {
            name: name.to_string(),
            dtype: DataType::Int32,
            shape,
            data: bytes,
            attributes: Vec::new(),
        }
    }

    /// Decodes the raw bytes back into a `Vec`f64`.
    pub fn to_f64_vec(&self) -> Result<Vec<f64>, String> {
        if self.dtype != DataType::Float64 {
            return Err(format!("Expected Float64, got {:?}", self.dtype));
        }
        let n = self.shape.total_elements();
        if self.data.len() != n * 8 {
            return Err(format!(
                "Data length mismatch: {} bytes for {} f64 elements",
                self.data.len(),
                n
            ));
        }
        Ok((0..n)
            .map(|i| {
                f64::from_le_bytes(
                    self.data[i * 8..i * 8 + 8]
                        .try_into()
                        .expect("slice length must match"),
                )
            })
            .collect())
    }

    /// Decodes the raw bytes back into a `Vec`f32`.
    pub fn to_f32_vec(&self) -> Result<Vec<f32>, String> {
        if self.dtype != DataType::Float32 {
            return Err(format!("Expected Float32, got {:?}", self.dtype));
        }
        let n = self.shape.total_elements();
        if self.data.len() != n * 4 {
            return Err(format!(
                "Data length mismatch: {} bytes for {} f32 elements",
                self.data.len(),
                n
            ));
        }
        Ok((0..n)
            .map(|i| {
                f32::from_le_bytes(
                    self.data[i * 4..i * 4 + 4]
                        .try_into()
                        .expect("slice length must match"),
                )
            })
            .collect())
    }

    /// Decodes the raw bytes back into a `Vec`i32`.
    pub fn to_i32_vec(&self) -> Result<Vec<i32>, String> {
        if self.dtype != DataType::Int32 {
            return Err(format!("Expected Int32, got {:?}", self.dtype));
        }
        let n = self.shape.total_elements();
        if self.data.len() != n * 4 {
            return Err(format!(
                "Data length mismatch: {} bytes for {} i32 elements",
                self.data.len(),
                n
            ));
        }
        Ok((0..n)
            .map(|i| {
                i32::from_le_bytes(
                    self.data[i * 4..i * 4 + 4]
                        .try_into()
                        .expect("slice length must match"),
                )
            })
            .collect())
    }

    /// Appends an attribute to this dataset.
    pub fn add_attribute(&mut self, attr: Attribute) {
        self.attributes.push(attr);
    }

    /// Looks up an attribute by name.
    pub fn get_attribute(&self, name: &str) -> Option<&Attribute> {
        self.attributes.iter().find(|a| a.name == name)
    }
}

// ---------------------------------------------------------------------------
// Group
// ---------------------------------------------------------------------------

/// A named container that holds datasets, subgroups, and attributes.
#[derive(Debug, Clone)]
pub struct Group {
    pub name: String,
    pub datasets: Vec<Dataset>,
    pub subgroups: Vec<Group>,
    pub attributes: Vec<Attribute>,
}

impl Group {
    /// Creates an empty group with the given name.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            datasets: Vec::new(),
            subgroups: Vec::new(),
            attributes: Vec::new(),
        }
    }

    /// Adds a dataset to this group.
    pub fn add_dataset(&mut self, ds: Dataset) {
        self.datasets.push(ds);
    }

    /// Adds a subgroup to this group.
    pub fn add_subgroup(&mut self, g: Group) {
        self.subgroups.push(g);
    }

    /// Looks up a dataset by name.
    pub fn get_dataset(&self, name: &str) -> Option<&Dataset> {
        self.datasets.iter().find(|d| d.name == name)
    }

    /// Looks up a direct subgroup by name.
    pub fn get_subgroup(&self, name: &str) -> Option<&Group> {
        self.subgroups.iter().find(|g| g.name == name)
    }

    /// Appends an attribute to this group.
    pub fn add_attribute(&mut self, attr: Attribute) {
        self.attributes.push(attr);
    }

    /// Looks up an attribute by name.
    pub fn get_attribute(&self, name: &str) -> Option<&Attribute> {
        self.attributes.iter().find(|a| a.name == name)
    }
}

// ---------------------------------------------------------------------------
// OxiFile
// ---------------------------------------------------------------------------

const MAGIC: &[u8; 8] = b"OXIPHY01";

/// Root container for the OxiPhy binary file format.
///
/// Binary layout:
/// - 8 bytes magic: `OXIPHY01`
/// - 4 bytes version: `u32` little-endian
/// - Recursively serialized root group
#[derive(Debug, Clone)]
pub struct OxiFile {
    pub version: u32,
    pub root: Group,
}

impl OxiFile {
    /// Creates a new empty `OxiFile` at version 1.
    pub fn new() -> Self {
        Self {
            version: 1,
            root: Group::new("/"),
        }
    }

    /// Serializes the entire file to a byte vector.
    pub fn write_to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(MAGIC);
        write_u32(&mut buf, self.version);
        serialize_group(&mut buf, &self.root);
        buf
    }

    /// Deserializes an `OxiFile` from a byte slice.
    pub fn read_from_bytes(data: &[u8]) -> Result<Self, String> {
        if data.len() < 12 {
            return Err("Data too short to be a valid OxiFile".to_string());
        }
        if &data[0..8] != MAGIC {
            return Err("Invalid magic bytes: not an OxiFile".to_string());
        }
        let mut pos = 8usize;
        let version = read_u32(data, &mut pos)?;
        let root = deserialize_group(data, &mut pos)?;
        Ok(Self { version, root })
    }

    /// Writes the file to disk at the given path.
    pub fn save(&self, path: &str) -> Result<(), String> {
        let bytes = self.write_to_bytes();
        let mut f =
            fs::File::create(path).map_err(|e| format!("Cannot create file '{}': {}", path, e))?;
        f.write_all(&bytes)
            .map_err(|e| format!("Write error: {}", e))?;
        Ok(())
    }

    /// Loads an `OxiFile` from disk.
    pub fn load(path: &str) -> Result<Self, String> {
        let bytes = fs::read(path).map_err(|e| format!("Cannot read file '{}': {}", path, e))?;
        Self::read_from_bytes(&bytes)
    }
}

impl Default for OxiFile {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Serialization helpers (public)
// ---------------------------------------------------------------------------

/// Appends a `u32` in little-endian format.
pub fn write_u32(buf: &mut Vec<u8>, v: u32) {
    buf.extend_from_slice(&v.to_le_bytes());
}

/// Appends a `u64` in little-endian format.
pub fn write_u64(buf: &mut Vec<u8>, v: u64) {
    buf.extend_from_slice(&v.to_le_bytes());
}

/// Appends a length-prefixed UTF-8 string (u32 length + bytes).
pub fn write_string(buf: &mut Vec<u8>, s: &str) {
    let bytes = s.as_bytes();
    write_u32(buf, bytes.len() as u32);
    buf.extend_from_slice(bytes);
}

/// Reads a `u32` in little-endian format, advancing `pos`.
pub fn read_u32(data: &[u8], pos: &mut usize) -> Result<u32, String> {
    if *pos + 4 > data.len() {
        return Err(format!("read_u32: unexpected end of data at pos {}", *pos));
    }
    let v = u32::from_le_bytes(
        data[*pos..*pos + 4]
            .try_into()
            .expect("slice length must match"),
    );
    *pos += 4;
    Ok(v)
}

/// Reads a `u64` in little-endian format, advancing `pos`.
pub fn read_u64(data: &[u8], pos: &mut usize) -> Result<u64, String> {
    if *pos + 8 > data.len() {
        return Err(format!("read_u64: unexpected end of data at pos {}", *pos));
    }
    let v = u64::from_le_bytes(
        data[*pos..*pos + 8]
            .try_into()
            .expect("slice length must match"),
    );
    *pos += 8;
    Ok(v)
}

/// Reads a length-prefixed UTF-8 string, advancing `pos`.
pub fn read_string(data: &[u8], pos: &mut usize) -> Result<String, String> {
    let len = read_u32(data, pos)? as usize;
    if *pos + len > data.len() {
        return Err(format!(
            "read_string: string body out of bounds at pos {}",
            *pos
        ));
    }
    let s = std::str::from_utf8(&data[*pos..*pos + len])
        .map_err(|e| format!("Invalid UTF-8: {}", e))?
        .to_string();
    *pos += len;
    Ok(s)
}

// ---------------------------------------------------------------------------
// Internal serialization helpers
// ---------------------------------------------------------------------------

fn write_i64(buf: &mut Vec<u8>, v: i64) {
    buf.extend_from_slice(&v.to_le_bytes());
}

fn read_i64(data: &[u8], pos: &mut usize) -> Result<i64, String> {
    if *pos + 8 > data.len() {
        return Err(format!("read_i64: unexpected end of data at pos {}", *pos));
    }
    let v = i64::from_le_bytes(
        data[*pos..*pos + 8]
            .try_into()
            .expect("slice length must match"),
    );
    *pos += 8;
    Ok(v)
}

fn write_f64(buf: &mut Vec<u8>, v: f64) {
    buf.extend_from_slice(&v.to_le_bytes());
}

fn read_f64(data: &[u8], pos: &mut usize) -> Result<f64, String> {
    if *pos + 8 > data.len() {
        return Err(format!("read_f64: unexpected end of data at pos {}", *pos));
    }
    let v = f64::from_le_bytes(
        data[*pos..*pos + 8]
            .try_into()
            .expect("slice length must match"),
    );
    *pos += 8;
    Ok(v)
}

// ---------------------------------------------------------------------------
// Attribute serialization
// ---------------------------------------------------------------------------

fn serialize_attribute(buf: &mut Vec<u8>, attr: &Attribute) {
    write_string(buf, &attr.name);
    buf.push(attr.value.tag());
    match &attr.value {
        AttributeValue::Int(v) => {
            write_i64(buf, *v);
        }
        AttributeValue::Float(v) => {
            write_f64(buf, *v);
        }
        AttributeValue::Text(s) => {
            write_string(buf, s);
        }
        AttributeValue::IntArray(arr) => {
            write_u64(buf, arr.len() as u64);
            for &v in arr {
                write_i64(buf, v);
            }
        }
        AttributeValue::FloatArray(arr) => {
            write_u64(buf, arr.len() as u64);
            for &v in arr {
                write_f64(buf, v);
            }
        }
    }
}

fn deserialize_attribute(data: &[u8], pos: &mut usize) -> Result<Attribute, String> {
    let name = read_string(data, pos)?;
    if *pos >= data.len() {
        return Err("deserialize_attribute: missing type tag".to_string());
    }
    let tag = data[*pos];
    *pos += 1;
    let value = match tag {
        0 => AttributeValue::Int(read_i64(data, pos)?),
        1 => AttributeValue::Float(read_f64(data, pos)?),
        2 => AttributeValue::Text(read_string(data, pos)?),
        3 => {
            let n = read_u64(data, pos)? as usize;
            let mut arr = Vec::with_capacity(n);
            for _ in 0..n {
                arr.push(read_i64(data, pos)?);
            }
            AttributeValue::IntArray(arr)
        }
        4 => {
            let n = read_u64(data, pos)? as usize;
            let mut arr = Vec::with_capacity(n);
            for _ in 0..n {
                arr.push(read_f64(data, pos)?);
            }
            AttributeValue::FloatArray(arr)
        }
        _ => return Err(format!("Unknown AttributeValue tag: {}", tag)),
    };
    Ok(Attribute { name, value })
}

// ---------------------------------------------------------------------------
// Dataset serialization
// ---------------------------------------------------------------------------

fn serialize_dataset(buf: &mut Vec<u8>, ds: &Dataset) {
    write_string(buf, &ds.name);
    buf.push(ds.dtype.tag());
    // shape
    write_u32(buf, ds.shape.dims.len() as u32);
    for &d in &ds.shape.dims {
        write_u64(buf, d as u64);
    }
    // raw data
    write_u64(buf, ds.data.len() as u64);
    buf.extend_from_slice(&ds.data);
    // attributes
    write_u32(buf, ds.attributes.len() as u32);
    for attr in &ds.attributes {
        serialize_attribute(buf, attr);
    }
}

fn deserialize_dataset(data: &[u8], pos: &mut usize) -> Result<Dataset, String> {
    let name = read_string(data, pos)?;
    if *pos >= data.len() {
        return Err("deserialize_dataset: missing dtype tag".to_string());
    }
    let dtype = DataType::from_tag(data[*pos])?;
    *pos += 1;
    let ndims = read_u32(data, pos)? as usize;
    let mut dims = Vec::with_capacity(ndims);
    for _ in 0..ndims {
        dims.push(read_u64(data, pos)? as usize);
    }
    let shape = DatasetShape { dims };
    let data_len = read_u64(data, pos)? as usize;
    if *pos + data_len > data.len() {
        return Err(format!(
            "deserialize_dataset: data body out of bounds at pos {}",
            *pos
        ));
    }
    let raw = data[*pos..*pos + data_len].to_vec();
    *pos += data_len;
    let n_attrs = read_u32(data, pos)? as usize;
    let mut attributes = Vec::with_capacity(n_attrs);
    for _ in 0..n_attrs {
        attributes.push(deserialize_attribute(data, pos)?);
    }
    Ok(Dataset {
        name,
        dtype,
        shape,
        data: raw,
        attributes,
    })
}

// ---------------------------------------------------------------------------
// Group serialization
// ---------------------------------------------------------------------------

fn serialize_group(buf: &mut Vec<u8>, group: &Group) {
    write_string(buf, &group.name);
    // attributes
    write_u32(buf, group.attributes.len() as u32);
    for attr in &group.attributes {
        serialize_attribute(buf, attr);
    }
    // datasets
    write_u32(buf, group.datasets.len() as u32);
    for ds in &group.datasets {
        serialize_dataset(buf, ds);
    }
    // subgroups (recursive)
    write_u32(buf, group.subgroups.len() as u32);
    for sg in &group.subgroups {
        serialize_group(buf, sg);
    }
}

fn deserialize_group(data: &[u8], pos: &mut usize) -> Result<Group, String> {
    let name = read_string(data, pos)?;
    let n_attrs = read_u32(data, pos)? as usize;
    let mut attributes = Vec::with_capacity(n_attrs);
    for _ in 0..n_attrs {
        attributes.push(deserialize_attribute(data, pos)?);
    }
    let n_datasets = read_u32(data, pos)? as usize;
    let mut datasets = Vec::with_capacity(n_datasets);
    for _ in 0..n_datasets {
        datasets.push(deserialize_dataset(data, pos)?);
    }
    let n_subgroups = read_u32(data, pos)? as usize;
    let mut subgroups = Vec::with_capacity(n_subgroups);
    for _ in 0..n_subgroups {
        subgroups.push(deserialize_group(data, pos)?);
    }
    Ok(Group {
        name,
        datasets,
        subgroups,
        attributes,
    })
}

// ---------------------------------------------------------------------------
// SimulationCheckpoint
// ---------------------------------------------------------------------------

/// High-level helper for writing physics simulation checkpoint data.
pub struct SimulationCheckpoint;

impl SimulationCheckpoint {
    /// Creates a fresh `OxiFile` ready for checkpoint data.
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> OxiFile {
        OxiFile::new()
    }

    /// Flattens a slice of 3-vectors and stores them as a `(N, 3)` dataset.
    pub fn add_positions(file: &mut OxiFile, group: &str, positions: &[[f64; 3]]) {
        let flat: Vec<f64> = positions.iter().flat_map(|p| p.iter().copied()).collect();
        let shape = DatasetShape::new(vec![positions.len(), 3]);
        let ds = Dataset::from_f64_slice("positions", &flat, shape);
        Self::get_or_create_group(&mut file.root, group).add_dataset(ds);
    }

    /// Flattens a slice of 3-vectors and stores them as a `(N, 3)` dataset.
    pub fn add_velocities(file: &mut OxiFile, group: &str, velocities: &[[f64; 3]]) {
        let flat: Vec<f64> = velocities.iter().flat_map(|v| v.iter().copied()).collect();
        let shape = DatasetShape::new(vec![velocities.len(), 3]);
        let ds = Dataset::from_f64_slice("velocities", &flat, shape);
        Self::get_or_create_group(&mut file.root, group).add_dataset(ds);
    }

    /// Stores a 1-D scalar field as a `(N,)` dataset.
    pub fn add_scalar_field(file: &mut OxiFile, group: &str, name: &str, values: &[f64]) {
        let shape = DatasetShape::new(vec![values.len()]);
        let ds = Dataset::from_f64_slice(name, values, shape);
        Self::get_or_create_group(&mut file.root, group).add_dataset(ds);
    }

    /// Stores timestep metadata as attributes on the root group.
    pub fn add_timestep_metadata(file: &mut OxiFile, step: u64, time: f64, dt: f64) {
        file.root
            .add_attribute(Attribute::new("step", AttributeValue::Int(step as i64)));
        file.root
            .add_attribute(Attribute::new("time", AttributeValue::Float(time)));
        file.root
            .add_attribute(Attribute::new("dt", AttributeValue::Float(dt)));
    }

    // Returns a mutable reference to the named direct subgroup, creating it if absent.
    fn get_or_create_group<'a>(root: &'a mut Group, name: &str) -> &'a mut Group {
        if let Some(idx) = root.subgroups.iter().position(|g| g.name == name) {
            return &mut root.subgroups[idx];
        }
        root.subgroups.push(Group::new(name));
        root.subgroups
            .last_mut()
            .expect("collection should not be empty")
    }
}

impl Default for SimulationCheckpoint {
    fn default() -> Self {
        Self
    }
}

// ---------------------------------------------------------------------------
// Endianness handling
// ---------------------------------------------------------------------------

/// Which byte order a binary stream uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Endianness {
    /// Least-significant byte first (x86/arm default).
    Little,
    /// Most-significant byte first (network order, big-endian).
    Big,
}

impl Endianness {
    /// Detect the native byte order at runtime.
    pub fn native() -> Self {
        if cfg!(target_endian = "little") {
            Endianness::Little
        } else {
            Endianness::Big
        }
    }

    /// Convert a `u32` to bytes in this byte order.
    pub fn u32_to_bytes(self, v: u32) -> [u8; 4] {
        match self {
            Endianness::Little => v.to_le_bytes(),
            Endianness::Big => v.to_be_bytes(),
        }
    }

    /// Convert a `u32` from bytes in this byte order.
    pub fn u32_from_bytes(self, b: [u8; 4]) -> u32 {
        match self {
            Endianness::Little => u32::from_le_bytes(b),
            Endianness::Big => u32::from_be_bytes(b),
        }
    }

    /// Convert a `f64` to bytes in this byte order.
    pub fn f64_to_bytes(self, v: f64) -> [u8; 8] {
        match self {
            Endianness::Little => v.to_le_bytes(),
            Endianness::Big => v.to_be_bytes(),
        }
    }

    /// Convert a `f64` from bytes in this byte order.
    pub fn f64_from_bytes(self, b: [u8; 8]) -> f64 {
        match self {
            Endianness::Little => f64::from_le_bytes(b),
            Endianness::Big => f64::from_be_bytes(b),
        }
    }

    /// Swap bytes of a `u32` from this endianness to native order.
    pub fn u32_to_native(self, v: u32) -> u32 {
        match self {
            Endianness::Little => u32::from_le_bytes(v.to_ne_bytes()),
            Endianness::Big => u32::from_be_bytes(v.to_ne_bytes()),
        }
    }
}

// ---------------------------------------------------------------------------
// Binary mesh format (simple triangle mesh)
// ---------------------------------------------------------------------------

/// A minimal binary triangle mesh representation.
///
/// Format:
/// - `u32` number of vertices
/// - `u32` number of triangles
/// - `3 * n_verts * f64` flat XYZ vertex positions
/// - `3 * n_tris * u32` triangle vertex indices
#[derive(Debug, Clone)]
pub struct BinaryMesh {
    /// Vertex positions stored as flat XYZ triples.
    pub vertices: Vec<[f64; 3]>,
    /// Triangle indices (0-based).
    pub triangles: Vec<[u32; 3]>,
}

impl BinaryMesh {
    /// Create an empty mesh.
    pub fn new() -> Self {
        Self {
            vertices: Vec::new(),
            triangles: Vec::new(),
        }
    }

    /// Serialize to bytes (little-endian).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        write_u32(&mut buf, self.vertices.len() as u32);
        write_u32(&mut buf, self.triangles.len() as u32);
        for v in &self.vertices {
            for k in 0..3 {
                buf.extend_from_slice(&v[k].to_le_bytes());
            }
        }
        for t in &self.triangles {
            for k in 0..3 {
                write_u32(&mut buf, t[k]);
            }
        }
        buf
    }

    /// Deserialize from bytes (little-endian).
    pub fn from_bytes(data: &[u8]) -> Result<Self, String> {
        let mut pos = 0usize;
        let n_verts = read_u32(data, &mut pos)? as usize;
        let n_tris = read_u32(data, &mut pos)? as usize;

        let mut vertices = Vec::with_capacity(n_verts);
        for _ in 0..n_verts {
            let mut xyz = [0.0_f64; 3];
            for k in 0..3 {
                if pos + 8 > data.len() {
                    return Err("BinaryMesh: vertex data truncated".to_string());
                }
                xyz[k] = f64::from_le_bytes(
                    data[pos..pos + 8]
                        .try_into()
                        .expect("slice length must match"),
                );
                pos += 8;
            }
            vertices.push(xyz);
        }

        let mut triangles = Vec::with_capacity(n_tris);
        for _ in 0..n_tris {
            let i0 = read_u32(data, &mut pos)?;
            let i1 = read_u32(data, &mut pos)?;
            let i2 = read_u32(data, &mut pos)?;
            triangles.push([i0, i1, i2]);
        }

        Ok(Self {
            vertices,
            triangles,
        })
    }

    /// Number of vertices.
    pub fn n_vertices(&self) -> usize {
        self.vertices.len()
    }

    /// Number of triangles.
    pub fn n_triangles(&self) -> usize {
        self.triangles.len()
    }
}

impl Default for BinaryMesh {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Binary particle data
// ---------------------------------------------------------------------------

/// Compact binary storage for particle data (positions + optional scalars).
///
/// Header: magic `b"OXIPART"` + u32 particle count + u32 field count.
/// Data: `n_particles * (3 + n_fields)` f64 values in row-major order.
#[derive(Debug, Clone)]
pub struct BinaryParticleData {
    /// Particle positions.
    pub positions: Vec<[f64; 3]>,
    /// Optional scalar fields (one Vec per field, each of length `n`).
    pub scalar_fields: Vec<Vec<f64>>,
    /// Field names corresponding to `scalar_fields`.
    pub field_names: Vec<String>,
}

const PARTICLE_MAGIC: &[u8; 7] = b"OXIPART";

impl BinaryParticleData {
    /// Create a new empty particle data container.
    pub fn new() -> Self {
        Self {
            positions: Vec::new(),
            scalar_fields: Vec::new(),
            field_names: Vec::new(),
        }
    }

    /// Add a scalar field by name.  Must have one value per particle.
    pub fn add_field(&mut self, name: &str, values: Vec<f64>) {
        assert_eq!(
            values.len(),
            self.positions.len(),
            "Field '{}' length {} != particle count {}",
            name,
            values.len(),
            self.positions.len()
        );
        self.field_names.push(name.to_string());
        self.scalar_fields.push(values);
    }

    /// Number of particles.
    pub fn n_particles(&self) -> usize {
        self.positions.len()
    }

    /// Number of scalar fields.
    pub fn n_fields(&self) -> usize {
        self.scalar_fields.len()
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let n = self.positions.len();
        let nf = self.scalar_fields.len();
        let mut buf = Vec::new();
        buf.extend_from_slice(PARTICLE_MAGIC);
        write_u32(&mut buf, n as u32);
        write_u32(&mut buf, nf as u32);
        // Field names
        for name in &self.field_names {
            write_string(&mut buf, name);
        }
        // Positions
        for p in &self.positions {
            for k in 0..3 {
                buf.extend_from_slice(&p[k].to_le_bytes());
            }
        }
        // Scalar fields
        for field in &self.scalar_fields {
            for &v in field {
                buf.extend_from_slice(&v.to_le_bytes());
            }
        }
        buf
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Result<Self, String> {
        if data.len() < 7 {
            return Err("BinaryParticleData: too short".to_string());
        }
        if &data[..7] != PARTICLE_MAGIC {
            return Err("BinaryParticleData: bad magic".to_string());
        }
        let mut pos = 7usize;
        let n = read_u32(data, &mut pos)? as usize;
        let nf = read_u32(data, &mut pos)? as usize;

        let mut field_names = Vec::with_capacity(nf);
        for _ in 0..nf {
            field_names.push(read_string(data, &mut pos)?);
        }

        let mut positions = Vec::with_capacity(n);
        for _ in 0..n {
            let mut xyz = [0.0_f64; 3];
            for k in 0..3 {
                if pos + 8 > data.len() {
                    return Err("BinaryParticleData: positions truncated".to_string());
                }
                xyz[k] = f64::from_le_bytes(
                    data[pos..pos + 8]
                        .try_into()
                        .expect("slice length must match"),
                );
                pos += 8;
            }
            positions.push(xyz);
        }

        let mut scalar_fields = Vec::with_capacity(nf);
        for _ in 0..nf {
            let mut field = Vec::with_capacity(n);
            for _ in 0..n {
                if pos + 8 > data.len() {
                    return Err("BinaryParticleData: scalar field truncated".to_string());
                }
                let v = f64::from_le_bytes(
                    data[pos..pos + 8]
                        .try_into()
                        .expect("slice length must match"),
                );
                pos += 8;
                field.push(v);
            }
            scalar_fields.push(field);
        }

        Ok(Self {
            positions,
            scalar_fields,
            field_names,
        })
    }
}

impl Default for BinaryParticleData {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Compressed binary output (run-length encoding for f64 streams)
// ---------------------------------------------------------------------------

/// Very simple run-length compression for f64 arrays.
///
/// Consecutive equal values are stored as `(value, count)` pairs.
/// This is mainly useful for fields with large constant regions.
///
/// Format: `u32 n_runs || \[f64 value, u32 count\] × n_runs`
#[allow(dead_code)]
pub fn rle_compress_f64(values: &[f64]) -> Vec<u8> {
    if values.is_empty() {
        let mut buf = Vec::new();
        write_u32(&mut buf, 0);
        return buf;
    }

    let mut runs: Vec<(f64, u32)> = Vec::new();
    let mut cur = values[0];
    let mut cnt = 1u32;
    for &v in &values[1..] {
        if v.to_bits() == cur.to_bits() {
            cnt += 1;
        } else {
            runs.push((cur, cnt));
            cur = v;
            cnt = 1;
        }
    }
    runs.push((cur, cnt));

    let mut buf = Vec::new();
    write_u32(&mut buf, runs.len() as u32);
    for (val, count) in runs {
        buf.extend_from_slice(&val.to_le_bytes());
        write_u32(&mut buf, count);
    }
    buf
}

/// Decompress a run-length encoded f64 array.
#[allow(dead_code)]
pub fn rle_decompress_f64(data: &[u8]) -> Result<Vec<f64>, String> {
    let mut pos = 0usize;
    let n_runs = read_u32(data, &mut pos)? as usize;
    let mut result = Vec::new();
    for _ in 0..n_runs {
        if pos + 12 > data.len() {
            return Err("rle_decompress_f64: truncated".to_string());
        }
        let val = f64::from_le_bytes(
            data[pos..pos + 8]
                .try_into()
                .expect("slice length must match"),
        );
        pos += 8;
        let count = read_u32(data, &mut pos)? as usize;
        for _ in 0..count {
            result.push(val);
        }
    }
    Ok(result)
}

// ---------------------------------------------------------------------------
// Binary format versioning
// ---------------------------------------------------------------------------

/// Supported OxiFile format versions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatVersion {
    /// Version 1: initial release.
    V1 = 1,
    /// Version 2: added compression flags.
    V2 = 2,
}

impl FormatVersion {
    /// Parse from a `u32` tag.
    pub fn from_u32(v: u32) -> Result<Self, String> {
        match v {
            1 => Ok(FormatVersion::V1),
            2 => Ok(FormatVersion::V2),
            _ => Err(format!("Unknown format version: {v}")),
        }
    }

    /// Convert to a `u32` tag.
    pub fn to_u32(self) -> u32 {
        self as u32
    }

    /// Whether this version supports compression metadata.
    pub fn supports_compression(self) -> bool {
        matches!(self, FormatVersion::V2)
    }
}

// ---------------------------------------------------------------------------
// Extended OxiFile helpers
// ---------------------------------------------------------------------------

impl OxiFile {
    /// Create an OxiFile at a specific format version.
    pub fn with_version(version: FormatVersion) -> Self {
        Self {
            version: version.to_u32(),
            root: Group::new("/"),
        }
    }

    /// Return the parsed `FormatVersion` if recognised, else an error.
    pub fn format_version(&self) -> Result<FormatVersion, String> {
        FormatVersion::from_u32(self.version)
    }

    /// Store a `BinaryMesh` under the given group name.
    pub fn add_binary_mesh(&mut self, group: &str, mesh: &BinaryMesh) {
        let bytes = mesh.to_bytes();
        let shape = DatasetShape::new(vec![bytes.len()]);
        let mut ds = Dataset {
            name: "mesh_binary".to_string(),
            dtype: DataType::UInt8,
            shape,
            data: bytes,
            attributes: Vec::new(),
        };
        ds.add_attribute(Attribute::new(
            "n_vertices",
            AttributeValue::Int(mesh.n_vertices() as i64),
        ));
        ds.add_attribute(Attribute::new(
            "n_triangles",
            AttributeValue::Int(mesh.n_triangles() as i64),
        ));
        SimulationCheckpoint::get_or_create_group(&mut self.root, group).add_dataset(ds);
    }

    /// Retrieve and decode a `BinaryMesh` from the given group.
    pub fn get_binary_mesh(&self, group: &str) -> Result<BinaryMesh, String> {
        let grp = self
            .root
            .get_subgroup(group)
            .ok_or_else(|| format!("Group '{}' not found", group))?;
        let ds = grp
            .get_dataset("mesh_binary")
            .ok_or_else(|| "Dataset 'mesh_binary' not found".to_string())?;
        BinaryMesh::from_bytes(&ds.data)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dataset_f64_round_trip() {
        let original = vec![1.0_f64, 2.5, -3.125, 0.0, 1e10];
        let shape = DatasetShape::new(vec![original.len()]);
        let ds = Dataset::from_f64_slice("test", &original, shape);
        let recovered = ds.to_f64_vec().expect("to_f64_vec failed");
        assert_eq!(original, recovered);
    }

    #[test]
    fn test_dataset_f32_round_trip() {
        let original = vec![1.0_f32, 2.5, -3.125, 0.0];
        let shape = DatasetShape::new(vec![original.len()]);
        let ds = Dataset::from_f32_slice("f32ds", &original, shape);
        let recovered = ds.to_f32_vec().expect("to_f32_vec failed");
        assert_eq!(original, recovered);
    }

    #[test]
    fn test_dataset_i32_round_trip() {
        let original = vec![0_i32, -1, 42, i32::MAX, i32::MIN];
        let shape = DatasetShape::new(vec![original.len()]);
        let ds = Dataset::from_i32_slice("i32ds", &original, shape);
        let recovered = ds.to_i32_vec().expect("to_i32_vec failed");
        assert_eq!(original, recovered);
    }

    #[test]
    fn test_group_add_get_dataset() {
        let mut g = Group::new("particles");
        let ds = Dataset::from_f64_slice("energy", &[1.0, 2.0, 3.0], DatasetShape::new(vec![3]));
        g.add_dataset(ds);
        let found = g.get_dataset("energy").expect("dataset not found");
        assert_eq!(found.name, "energy");
        assert!(g.get_dataset("missing").is_none());
    }

    #[test]
    fn test_oxifile_round_trip() {
        let mut file = OxiFile::new();
        let ds = Dataset::from_f64_slice("x", &[1.0, 2.0, 3.0], DatasetShape::new(vec![3]));
        file.root.add_dataset(ds);

        let bytes = file.write_to_bytes();
        let loaded = OxiFile::read_from_bytes(&bytes).expect("round-trip failed");
        assert_eq!(loaded.version, 1);
        let ds2 = loaded
            .root
            .get_dataset("x")
            .expect("dataset missing after round-trip");
        let vals = ds2.to_f64_vec().unwrap();
        assert_eq!(vals, vec![1.0, 2.0, 3.0]);
    }

    #[test]
    fn test_read_from_bytes_invalid_magic() {
        let bad: Vec<u8> = b"BADMAGIC\x01\x00\x00\x00".to_vec();
        let result = OxiFile::read_from_bytes(&bad);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid magic bytes"));
    }

    #[test]
    fn test_dataset_shape_total_elements() {
        let s = DatasetShape::new(vec![3, 4, 5]);
        assert_eq!(s.total_elements(), 60);
        assert_eq!(s.rank(), 3);
        assert!(!s.is_scalar());

        let scalar = DatasetShape::new(vec![]);
        assert_eq!(scalar.total_elements(), 1);
        assert!(scalar.is_scalar());
        assert_eq!(scalar.rank(), 0);
    }

    #[test]
    fn test_attribute_get_set() {
        let mut ds = Dataset::from_f64_slice("d", &[1.0], DatasetShape::new(vec![1]));
        ds.add_attribute(Attribute::new(
            "units",
            AttributeValue::Text("meters".to_string()),
        ));
        ds.add_attribute(Attribute::new("count", AttributeValue::Int(42)));

        let attr = ds.get_attribute("units").expect("units not found");
        assert_eq!(attr.value, AttributeValue::Text("meters".to_string()));
        assert!(ds.get_attribute("nope").is_none());
    }

    #[test]
    fn test_simulation_checkpoint_positions() {
        let mut file = SimulationCheckpoint::new();
        let positions = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]];
        SimulationCheckpoint::add_positions(&mut file, "frame0", &positions);

        let grp = file.root.get_subgroup("frame0").expect("group missing");
        let ds = grp.get_dataset("positions").expect("positions missing");
        let vals = ds.to_f64_vec().expect("to_f64_vec failed");

        let expected: Vec<f64> = positions.iter().flat_map(|p| p.iter().copied()).collect();
        assert_eq!(vals, expected);
        assert_eq!(ds.shape.dims, vec![3, 3]);
    }

    #[test]
    fn test_simulation_checkpoint_round_trip() {
        let mut file = SimulationCheckpoint::new();
        let positions = [[0.1, 0.2, 0.3], [-1.0, 2.0, -3.0]];
        SimulationCheckpoint::add_positions(&mut file, "step1", &positions);
        SimulationCheckpoint::add_timestep_metadata(&mut file, 1, 0.01, 0.001);

        let bytes = file.write_to_bytes();
        let loaded = OxiFile::read_from_bytes(&bytes).expect("round-trip failed");

        let step_attr = loaded.root.get_attribute("step").expect("step missing");
        assert_eq!(step_attr.value, AttributeValue::Int(1));

        let grp = loaded.root.get_subgroup("step1").expect("subgroup missing");
        let ds = grp.get_dataset("positions").expect("dataset missing");
        let vals = ds.to_f64_vec().unwrap();
        let expected: Vec<f64> = positions.iter().flat_map(|p| p.iter().copied()).collect();
        assert_eq!(vals, expected);
    }

    // -----------------------------------------------------------------------
    // Endianness tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_endianness_u32_round_trip() {
        let v: u32 = 0xDEAD_BEEF;
        for end in [Endianness::Little, Endianness::Big] {
            let bytes = end.u32_to_bytes(v);
            let back = end.u32_from_bytes(bytes);
            assert_eq!(back, v, "Endianness {:?} u32 round-trip failed", end);
        }
    }

    #[test]
    fn test_endianness_f64_round_trip() {
        let v = std::f64::consts::PI;
        for end in [Endianness::Little, Endianness::Big] {
            let bytes = end.f64_to_bytes(v);
            let back = end.f64_from_bytes(bytes);
            assert!(
                (back - v).abs() < 1e-15,
                "Endianness {:?} f64 round-trip failed",
                end
            );
        }
    }

    #[test]
    fn test_endianness_native() {
        let native = Endianness::native();
        assert!(native == Endianness::Little || native == Endianness::Big);
    }

    // -----------------------------------------------------------------------
    // BinaryMesh tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_binary_mesh_round_trip() {
        let mut mesh = BinaryMesh::new();
        mesh.vertices = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 1.0, 0.0]];
        mesh.triangles = vec![[0, 1, 2]];
        let bytes = mesh.to_bytes();
        let mesh2 = BinaryMesh::from_bytes(&bytes).expect("round-trip failed");
        assert_eq!(mesh2.n_vertices(), 3);
        assert_eq!(mesh2.n_triangles(), 1);
        assert!((mesh2.vertices[1][0] - 1.0).abs() < 1e-15);
        assert_eq!(mesh2.triangles[0], [0, 1, 2]);
    }

    #[test]
    fn test_binary_mesh_empty() {
        let mesh = BinaryMesh::new();
        let bytes = mesh.to_bytes();
        let mesh2 = BinaryMesh::from_bytes(&bytes).expect("empty mesh round-trip failed");
        assert_eq!(mesh2.n_vertices(), 0);
        assert_eq!(mesh2.n_triangles(), 0);
    }

    // -----------------------------------------------------------------------
    // BinaryParticleData tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_binary_particle_data_round_trip() {
        let mut pd = BinaryParticleData::new();
        pd.positions = vec![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];
        pd.add_field("density", vec![1000.0, 1200.0]);
        pd.add_field("pressure", vec![101325.0, 202650.0]);

        let bytes = pd.to_bytes();
        let pd2 = BinaryParticleData::from_bytes(&bytes).expect("round-trip failed");
        assert_eq!(pd2.n_particles(), 2);
        assert_eq!(pd2.n_fields(), 2);
        assert_eq!(pd2.field_names[0], "density");
        assert!((pd2.scalar_fields[0][1] - 1200.0).abs() < 1e-12);
        assert!((pd2.positions[1][2] - 6.0).abs() < 1e-15);
    }

    #[test]
    fn test_binary_particle_data_bad_magic() {
        let bad: Vec<u8> = b"BADMAGIC".to_vec();
        assert!(BinaryParticleData::from_bytes(&bad).is_err());
    }

    // -----------------------------------------------------------------------
    // RLE compression tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_rle_compress_decompress_round_trip() {
        let original = vec![1.0, 1.0, 1.0, 2.5, 2.5, 3.0, 1.0];
        let compressed = rle_compress_f64(&original);
        let decompressed = rle_decompress_f64(&compressed).expect("decompression failed");
        assert_eq!(original.len(), decompressed.len());
        for (a, b) in original.iter().zip(decompressed.iter()) {
            assert!((a - b).abs() < 1e-15);
        }
    }

    #[test]
    fn test_rle_compress_empty() {
        let compressed = rle_compress_f64(&[]);
        let decompressed = rle_decompress_f64(&compressed).expect("empty decompression failed");
        assert!(decompressed.is_empty());
    }

    #[test]
    fn test_rle_compresses_constant_field() {
        let original = vec![3.125; 1000];
        let compressed = rle_compress_f64(&original);
        // Should be much smaller than the raw 8000 bytes.
        assert!(
            compressed.len() < 100,
            "RLE should compress constant field significantly"
        );
        let decompressed = rle_decompress_f64(&compressed).unwrap();
        assert_eq!(decompressed.len(), 1000);
    }

    // -----------------------------------------------------------------------
    // FormatVersion tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_version_round_trip() {
        assert_eq!(FormatVersion::from_u32(1).unwrap(), FormatVersion::V1);
        assert_eq!(FormatVersion::from_u32(2).unwrap(), FormatVersion::V2);
        assert!(FormatVersion::from_u32(99).is_err());
    }

    #[test]
    fn test_format_version_supports_compression() {
        assert!(!FormatVersion::V1.supports_compression());
        assert!(FormatVersion::V2.supports_compression());
    }

    // -----------------------------------------------------------------------
    // OxiFile + BinaryMesh integration test
    // -----------------------------------------------------------------------

    #[test]
    fn test_oxifile_binary_mesh_store_retrieve() {
        let mut file = OxiFile::new();
        let mut mesh = BinaryMesh::new();
        mesh.vertices = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 1.0, 0.0]];
        mesh.triangles = vec![[0, 1, 2]];
        file.add_binary_mesh("geometry", &mesh);

        let mesh2 = file
            .get_binary_mesh("geometry")
            .expect("retrieve mesh failed");
        assert_eq!(mesh2.n_vertices(), 3);
        assert_eq!(mesh2.n_triangles(), 1);
    }

    #[test]
    fn test_oxifile_with_version() {
        let file = OxiFile::with_version(FormatVersion::V2);
        assert_eq!(file.version, 2);
        assert_eq!(file.format_version().unwrap(), FormatVersion::V2);
    }

    #[test]
    fn test_datatype_size_bytes() {
        assert_eq!(DataType::Float32.size_bytes(), 4);
        assert_eq!(DataType::Float64.size_bytes(), 8);
        assert_eq!(DataType::Int32.size_bytes(), 4);
        assert_eq!(DataType::Int64.size_bytes(), 8);
        assert_eq!(DataType::UInt8.size_bytes(), 1);
        assert_eq!(DataType::UInt32.size_bytes(), 4);
    }

    #[test]
    fn test_dataset_wrong_type_returns_err() {
        let ds = Dataset::from_f64_slice("d", &[1.0, 2.0], DatasetShape::new(vec![2]));
        assert!(ds.to_f32_vec().is_err());
        assert!(ds.to_i32_vec().is_err());
    }
}