mzdata 0.63.4

A library to read mass spectrometry data formats and a data model for mass spectra
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
use std::borrow::Cow;
use std::fmt::{self, Formatter};
use std::io::prelude::*;
use std::mem;

use base64_simd;
use bytemuck::Pod;
use flate2::write::{ZlibDecoder, ZlibEncoder};
use flate2::Compression;

use crate::params::{ParamList, Unit};

use super::encodings::{
    to_bytes, ArrayRetrievalError, ArrayType, BinaryCompressionType, BinaryDataArrayType,
    Bytes,
};
use super::traits::{ByteArrayView, ByteArrayViewMut};
#[allow(unused)]
use super::vec_as_bytes;

#[allow(unused)]
use super::encodings::{
    reverse_transpose_f32, reverse_transpose_f64, reverse_transpose_i32, reverse_transpose_i64,
    transpose_f32, transpose_f64, transpose_i32, transpose_i64,
};

/// Represents a data array that holds a byte buffer that may be compressed, base64 encoded,
/// or raw little endian bytes, and provides views of those bytes as a small range of supported
/// types.
///
/// This type is modeled after the `<binaryDataArray>` element in mzML.
///
/// # Note
/// This type tries to walk a fine line between convenience and performance and as such is easy
/// to misuse. All operations that view the byte buffer as arbitrary data need that data to be
/// decoded and decompressed in order to borrow it. If the byte buffer is not already stored
/// decoded, the operation will copy and decode the buffer in its entirety before performing any
/// other operation, so repeated method calls may incur excessive overhead. If this is happening,
/// please use [`DataArray::decode_and_store`] to store the decoded representation explicitly.
///
/// Normally, [`SpectrumSource`](crate::io::SpectrumSource)-implementing file readers will eagerly decode all arrays
/// as soon as they are ready. If they are operating in lazy mode, the buffers will need to be decoded
/// explicitly, again using [`DataArray::decode_and_store`] or operations should make as much use of the
/// copied arrays as possible instead.
#[derive(Default, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DataArray {
    pub data: Bytes,
    pub dtype: BinaryDataArrayType,
    pub compression: BinaryCompressionType,
    pub name: ArrayType,
    pub params: Option<Box<ParamList>>,
    pub unit: Unit,
    item_count: Option<usize>,
    data_processing_reference: Option<Box<str>>,
}

impl core::fmt::Debug for DataArray {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("DataArray")
            .field("name", &self.name)
            .field("data size", &self.data.len())
            .field("dtype", &self.dtype)
            .field("compression", &self.compression)
            .field("params", &self.params)
            .field("unit", &self.unit)
            .field("data_processing_ref", &self.data_processing_reference)
            .finish()
    }
}

const EMPTY_BUFFER: [u8; 0] = [];

/// A type to represent a base64-encoded, possibly compressed data
/// array of a fixed size, usually numeric, type. It can be decoded,
/// and it can
impl<'transient, 'lifespan: 'transient> DataArray {
    pub fn new() -> DataArray {
        DataArray {
            ..Default::default()
        }
    }

    pub fn from_name(name: &ArrayType) -> DataArray {
        DataArray {
            dtype: name.preferred_dtype(),
            name: name.clone(),
            compression: BinaryCompressionType::Decoded,
            ..Default::default()
        }
    }

    pub fn from_name_and_type(name: &ArrayType, dtype: BinaryDataArrayType) -> DataArray {
        DataArray {
            dtype,
            name: name.clone(),
            compression: BinaryCompressionType::Decoded,
            ..Default::default()
        }
    }

    pub fn from_name_type_size(
        name: &ArrayType,
        dtype: BinaryDataArrayType,
        size: usize,
    ) -> DataArray {
        DataArray {
            dtype,
            name: name.clone(),
            data: Bytes::with_capacity(size),
            compression: BinaryCompressionType::Decoded,
            ..Default::default()
        }
    }

    pub fn slice(&self, start: usize, end: usize) -> Result<DataArray, ArrayRetrievalError> {
        if end < start || (end - start) % self.dtype.size_of() != 0 {
            Err(ArrayRetrievalError::DataTypeSizeMismatch)
        } else {
            let data = self.decode()?;
            let slice = data[start..end].to_vec();
            let subset = Self::wrap(&self.name, self.dtype, slice);
            Ok(subset)
        }
    }

    pub fn slice_buffer(
        &self,
        start: usize,
        end: usize,
    ) -> Result<Cow<'_, [u8]>, ArrayRetrievalError> {
        if end < start || (end - start) % self.dtype.size_of() != 0 {
            Err(ArrayRetrievalError::DataTypeSizeMismatch)
        } else {
            let data = self.decode()?;
            match data {
                Cow::Borrowed(view) => Ok(Cow::Borrowed(&view[start..end])),
                Cow::Owned(view) => {
                    let data = &view[start..end];
                    Ok(Cow::Owned(data.to_owned()))
                }
            }
        }
    }

    pub fn wrap(name: &ArrayType, dtype: BinaryDataArrayType, data: Bytes) -> DataArray {
        DataArray {
            dtype,
            name: name.clone(),
            data,
            compression: BinaryCompressionType::Decoded,
            ..Default::default()
        }
    }

    fn set_buffer_of_type(&mut self, data_buffer: Vec<u8>) -> Result<usize, ArrayRetrievalError> {
        self.item_count = Some(data_buffer.len() / self.dtype().size_of());
        self.data = data_buffer;
        Ok(self.data.len())
    }

    /// Directly set the data buffer from a slice of a [`Pod`] type.
    ///
    /// This will return an error if `std::mem::size_of::<T>()` is not equal to
    /// the size of [`DataArray::dtype`].
    pub fn update_buffer<T: Pod>(
        &mut self,
        data_buffer: &[T],
    ) -> Result<usize, ArrayRetrievalError> {
        if self.dtype.size_of() != mem::size_of::<T>() {
            Err(ArrayRetrievalError::DataTypeSizeMismatch)
        } else {
            self.item_count = Some(data_buffer.len());
            self.data = to_bytes(data_buffer);
            Ok(self.data.len())
        }
    }

    /// Add the value of a [`Pod`] implementing type `T` to the array, converting it
    /// to native byte representation.
    ///
    /// This will return an error if `std::mem::size_of::<T>()` is not equal to
    /// the size of [`DataArray::dtype`].
    pub fn push<T: Pod>(&mut self, value: T) -> Result<(), ArrayRetrievalError> {
        if !matches!(self.compression, BinaryCompressionType::Decoded) {
            self.decode_and_store()?;
        };
        if self.dtype.size_of() != mem::size_of::<T>() {
            Err(ArrayRetrievalError::DataTypeSizeMismatch)
        } else {
            let data = bytemuck::bytes_of(&value);
            self.data.extend_from_slice(data);
            self.item_count = self.item_count.map(|i| i + 1);
            Ok(())
        }
    }

    /// Add the values from a slice of a [`Pod`] implementing type `T` to the array, converting the slice
    /// a slice of `T` in its native byte representation.
    ///
    /// This will return an error if `std::mem::size_of::<T>()` is not equal to
    /// the size of [`DataArray::dtype`].
    pub fn extend<T: Pod>(&mut self, values: &[T]) -> Result<(), ArrayRetrievalError> {
        if !matches!(self.compression, BinaryCompressionType::Decoded) {
            self.decode_and_store()?;
        };
        if self.dtype.size_of() != mem::size_of::<T>() {
            Err(ArrayRetrievalError::DataTypeSizeMismatch)
        } else {
            self.item_count = self.item_count.map(|i| i + values.len());
            let data = bytemuck::cast_slice(values);
            self.data.extend_from_slice(data);
            Ok(())
        }
    }

    /// Add the values from a buffer of bytes to the array directly.
    ///
    /// This will return an error if `values.len()` is not a multiple of
    /// the size of [`DataArray::dtype`].
    pub fn extend_raw(&mut self, values: &[u8]) -> Result<(), ArrayRetrievalError> {
        if values.len() % self.dtype.size_of() != 0 {
            Err(ArrayRetrievalError::DataTypeSizeMismatch)
        } else {
            self.data.extend_from_slice(values);
            Ok(())
        }
    }

    /// Add the values from an iterator over [`Pod`] type `T`.
    ///
    /// This is more efficient than repeated calls to [`DataArray::push`] or collecting
    /// to a `Vec` and then using [`DataArray::extend`], but equivalent to either.
    ///
    /// This will return an error if `std::mem::size_of::<T>()` is not equal to
    /// the size of [`DataArray::dtype`].
    pub fn extend_iter<T: Pod>(&mut self, iter: impl IntoIterator<Item=T>) -> Result<(), ArrayRetrievalError> {
        if mem::size_of::<T>() != self.dtype.size_of() {
            return Err(ArrayRetrievalError::DataTypeSizeMismatch)
        }
        for val in iter.into_iter() {
            self.data.extend_from_slice(bytemuck::bytes_of(&val));
        }
        Ok(())
    }

    /// Encode the data buffer to a byte array using the requested [`BinaryCompressionType`] to
    /// compress it and then base64 encode it.
    pub fn encode_bytestring(&self, compression: BinaryCompressionType) -> Bytes {
        if self.compression == compression {
            log::trace!("Fast-path encoding {}:{}", self.name, self.dtype);
            return self.data.clone();
        }
        let bytestring = match self.compression {
            BinaryCompressionType::Decoded => Cow::Borrowed(self.data.as_slice()),
            _ => self.decode().expect("Failed to decode binary data"),
        };
        match compression {
            BinaryCompressionType::Decoded => panic!("Should never happen"),
            BinaryCompressionType::Zlib => {
                let compressed = Self::compress_zlib(&bytestring);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            BinaryCompressionType::NoCompression => {
                base64_simd::STANDARD.encode_type::<Bytes>(bytestring.as_ref())
            }
            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressLinear => {
                if self.dtype != BinaryDataArrayType::Float64 {
                    panic!("Cannot Numpress non-float64 data!");
                }
                if bytestring.is_empty() {
                    return base64_simd::STANDARD.encode_type::<Bytes>(&bytestring)
                }
                let compressed =
                    Self::compress_numpress_linear(bytemuck::cast_slice(&bytestring)).unwrap();
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressSLOF => {
                let compressed = match self.dtype {
                    BinaryDataArrayType::Float32 => {
                        Self::compress_numpress_slof(bytemuck::cast_slice::<u8, f32>(&bytestring)).unwrap()
                    },
                    BinaryDataArrayType::Float64 => {
                        Self::compress_numpress_slof(bytemuck::cast_slice::<u8, f64>(&bytestring)).unwrap()
                    },
                    _ => {
                        panic!("Cannot Numpress non-float data!");
                    }
                };
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressLinearZlib => {
                if self.dtype != BinaryDataArrayType::Float64 {
                    panic!("Cannot Numpress non-float64 data!");
                }
                if bytestring.is_empty() {
                    let compressed = Self::compress_zlib(&bytestring);
                    return base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
                }
                let compressed = Self::compress_numpress_linear(bytemuck::cast_slice(&bytestring))
                    .inspect_err(|e| {
                        log::error!("Failed to compress buffer with numpress: {e}");
                    })
                    .unwrap();
                let compressed = Self::compress_zlib(&compressed);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(all(feature = "numpress", feature = "zstd"))]
            BinaryCompressionType::NumpressLinearZstd => {
                if self.dtype != BinaryDataArrayType::Float64 {
                    panic!("Cannot Numpress non-float64 data!");
                }
                if bytestring.is_empty() {
                    let compressed = Self::compress_zstd(&bytestring, BinaryDataArrayType::Unknown, false);
                    return base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
                }
                let compressed = Self::compress_numpress_linear(bytemuck::cast_slice(&bytestring))
                    .inspect_err(|e| {
                        log::error!("Failed to compress buffer with numpress: {e}");
                    })
                    .unwrap();
                let compressed = Self::compress_zstd(&compressed, BinaryDataArrayType::Unknown, false);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressSLOFZlib => {
                if bytestring.is_empty() {
                    let bytestring = Self::compress_zlib(&bytestring);
                    return base64_simd::STANDARD.encode_type::<Bytes>(&bytestring)
                }
                let compressed = match self.dtype {
                    BinaryDataArrayType::Float32 => {
                        Self::compress_numpress_slof(bytemuck::cast_slice::<u8, f32>(&bytestring)).unwrap()
                    },
                    BinaryDataArrayType::Float64 => {
                        Self::compress_numpress_slof(bytemuck::cast_slice::<u8, f64>(&bytestring)).unwrap()
                    },
                    _ => {
                        panic!("Cannot Numpress non-float data!");
                    }
                };
                let bytestring = Self::compress_zlib(&compressed);
                base64_simd::STANDARD.encode_type::<Bytes>(&bytestring)
            }
            #[cfg(all(feature = "numpress", feature = "zstd"))]
            BinaryCompressionType::NumpressSLOFZstd => {
                if bytestring.is_empty() {
                    let bytestring = Self::compress_zstd(&bytestring, BinaryDataArrayType::Unknown, false);
                    return base64_simd::STANDARD.encode_type::<Bytes>(&bytestring)
                }
                let compressed = match self.dtype {
                    BinaryDataArrayType::Float32 => {
                        Self::compress_numpress_slof(bytemuck::cast_slice::<u8, f32>(&bytestring)).unwrap()
                    },
                    BinaryDataArrayType::Float64 => {
                        Self::compress_numpress_slof(bytemuck::cast_slice::<u8, f64>(&bytestring)).unwrap()
                    },
                    _ => {
                        panic!("Cannot Numpress non-float data!");
                    }
                };
                let bytestring = Self::compress_zstd(&compressed, BinaryDataArrayType::Unknown, false);
                base64_simd::STANDARD.encode_type::<Bytes>(&bytestring)
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::Zstd => {
                let compressed = Self::compress_zstd(&bytestring, self.dtype, false);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::ShuffleZstd => {
                let compressed = Self::compress_zstd(&bytestring, self.dtype, true);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::DeltaShuffleZstd => {
                let compressed = Self::compress_delta_zstd(&bytestring, self.dtype, true);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::ZstdDict => {
                let compressed = Self::compress_dict_zstd(&bytestring, self.dtype);
                base64_simd::STANDARD.encode_type::<Bytes>(&compressed)
            }
            _ => {
                panic!("Compresion type {:?} is unsupported", compression)
            }
        }
    }

    /// Decode the compressed data, if needed, and store that buffer in `self.data`. After
    /// decoding `self.compression` will always be [`BinaryCompressionType::Decoded`].
    ///
    /// The return value is the content of `self.compression` after decoding.
    ///
    /// This may fail if the decoding fails for any reason.
    pub fn decode_and_store(&mut self) -> Result<BinaryCompressionType, ArrayRetrievalError> {
        match self.decode() {
            Ok(data) => {
                match data {
                    // The only time this is a borrow is when the data are already
                    // decoded.
                    Cow::Borrowed(_view) => Ok(self.compression),
                    Cow::Owned(buffer) => {
                        self.item_count = Some(buffer.len() / self.dtype.size_of());
                        self.data = buffer;
                        self.compression = BinaryCompressionType::Decoded;
                        Ok(self.compression)
                    }
                }
            }
            Err(err) => Err(err),
        }
    }

    /// Decompress and base64-decode encoded bytes, and return the data.
    ///
    /// If the data were already decoded, the existing bytes are returned. Otherwise one or
    /// more buffers may be allocated to hold the decompressed and decoded bytes.
    pub fn decode(&'lifespan self) -> Result<Cow<'lifespan, [u8]>, ArrayRetrievalError> {
        if self.data.is_empty() {
            return Ok(Cow::Borrowed(&EMPTY_BUFFER));
        }

        macro_rules! base64_decode {
            () => {
                base64_simd::STANDARD
                    .decode_type::<Bytes>(&self.data)
                    .unwrap_or_else(|e| panic!("Failed to decode base64 array: {}", e))
            };
        }

        match self.compression {
            BinaryCompressionType::Decoded => Ok(Cow::Borrowed(self.data.as_slice())),
            BinaryCompressionType::NoCompression => {
                let bytestring = base64_decode!();
                Ok(Cow::Owned(bytestring))
            }
            BinaryCompressionType::Zlib => {
                let bytestring = base64_decode!();
                Ok(Cow::Owned(Self::decompress_zlib(&bytestring)))
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::Zstd => {
                let bytestring = base64_decode!();
                Ok(Cow::Owned(Self::decompress_zstd(
                    &bytestring,
                    self.dtype,
                    false,
                )))
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::ShuffleZstd => {
                let bytestring = base64_decode!();
                Ok(Cow::Owned(Self::decompress_zstd(
                    &bytestring,
                    self.dtype,
                    true,
                )))
            }
            #[cfg(feature = "zstd")]
            BinaryCompressionType::DeltaShuffleZstd => {
                let bytestring = base64_decode!();
                Ok(Cow::Owned(Self::decompress_delta_zstd(
                    &bytestring,
                    self.dtype,
                    true,
                )))
            }

            #[cfg(feature = "zstd")]
            BinaryCompressionType::ZstdDict => {
                let bytestring = base64_decode!();
                Ok(Cow::Owned(Self::decompress_dict_zstd(
                    &bytestring,
                    self.dtype,
                )))
            }
            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressLinear => match self.dtype {
                BinaryDataArrayType::Float64 => {
                    let bytestring = base64_decode!();
                    let decoded = Self::decompress_numpress_linear(&bytestring)?;
                    let view = vec_as_bytes(decoded);
                    Ok(Cow::Owned(view))
                }
                _ => Err(ArrayRetrievalError::DecompressionError(
                    self.compression.unsupported_msg(Some(
                        format!("Not compatible with {:?}", self.dtype).as_str(),
                    )),
                )),
            },

            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressSLOF => {
                let bytestring = base64_decode!();
                Self::decompress_numpress_slof(&bytestring, self.dtype)
            }

            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressLinearZlib => match self.dtype {
                BinaryDataArrayType::Float64 => {
                    let bytestring = base64_decode!();
                    let bytestring = Self::decompress_zlib(&bytestring);
                    let decoded = Self::decompress_numpress_linear(&bytestring)?;
                    let view = vec_as_bytes(decoded);
                    Ok(Cow::Owned(view))
                }
                _ => Err(ArrayRetrievalError::DecompressionError(
                    self.compression.unsupported_msg(Some(
                        format!("Not compatible with {:?}", self.dtype).as_str(),
                    )),
                )),
            },

            #[cfg(feature = "numpress")]
            BinaryCompressionType::NumpressSLOFZlib => {
                let bytestring = base64_decode!();
                let bytestring = Self::decompress_zlib(&bytestring);
                Self::decompress_numpress_slof(&bytestring, self.dtype)
            }

            #[cfg(all(feature = "numpress", feature = "zstd"))]
            BinaryCompressionType::NumpressLinearZstd => match self.dtype {
                BinaryDataArrayType::Float64 => {
                    let bytestring = base64_decode!();
                    let bytestring = Self::decompress_zstd(
                        &bytestring,
                        BinaryDataArrayType::Unknown,
                        false,
                    );
                    let decoded = Self::decompress_numpress_linear(&bytestring)?;
                    let view = vec_as_bytes(decoded);
                    Ok(Cow::Owned(view))
                }
                _ => Err(ArrayRetrievalError::DecompressionError(
                    self.compression.unsupported_msg(Some(
                        format!("Not compatible with {:?}", self.dtype).as_str(),
                    )),
                )),
            },

            #[cfg(all(feature = "numpress", feature = "zstd"))]
            BinaryCompressionType::NumpressSLOFZstd => {
                let bytestring = base64_decode!();
                let bytestring = Self::decompress_zstd(&bytestring, BinaryDataArrayType::Unknown, false);
                Self::decompress_numpress_slof(&bytestring, self.dtype)
            }

            mode => Err(ArrayRetrievalError::DecompressionError(format!(
                "Cannot decode array encoded with {:?}",
                mode
            ))),
        }
    }

    pub(crate) fn decoded_slice(
        &'lifespan self,
        start: usize,
        end: usize,
    ) -> Result<Cow<'lifespan, [u8]>, ArrayRetrievalError> {
        if start > end || (end - start) % self.dtype.size_of() != 0 {
            return Err(ArrayRetrievalError::DataTypeSizeMismatch);
        }
        match self.compression {
            BinaryCompressionType::Decoded => Ok(Cow::Borrowed(&self.data.as_slice()[start..end])),
            _ => {
                Ok(Cow::Owned(self.decode()?[start..end].to_vec()))
            }
        }
    }

    pub fn decode_mut(&'transient mut self) -> Result<&'transient mut Bytes, ArrayRetrievalError> {
        if self.data.is_empty() || matches!(self.compression, BinaryCompressionType::Decoded) {
            Ok(&mut self.data)
        } else {
            match self.decode()? {
                Cow::Borrowed(_) => {
                    Ok(&mut self.data)
                },
                Cow::Owned(owned) => {
                    self.data = owned;
                    self.compression = BinaryCompressionType::Decoded;
                    Ok(&mut self.data)
                },
            }
        }

    }

    pub fn clear(&mut self) {
        self.data.clear();
        self.params = None;
        self.item_count = None;
    }

    /// The reverse of [`DataArray::decode_and_store`], this method compresses `self.data` to the desired
    /// compression method and stores that buffer as `self.data`.
    pub fn store_compressed(
        &mut self,
        compression: BinaryCompressionType,
    ) -> Result<(), ArrayRetrievalError> {
        if self.compression == compression {
            Ok(())
        } else {
            self.item_count = self.data_len().ok();
            let bytes = self.encode_bytestring(compression);
            self.data = bytes;
            self.compression = compression;
            Ok(())
        }
    }

    /// Recode the stored data as the requested binary data type.
    pub fn store_as(&mut self, dtype: BinaryDataArrayType) -> Result<usize, ArrayRetrievalError> {
        if self.dtype == dtype {
            return Ok(self.data.len());
        }
        match dtype {
            BinaryDataArrayType::Float32 => {
                let view = self.to_f32()?;
                let recast = to_bytes(&view);
                self.dtype = dtype;
                self.set_buffer_of_type(recast)
            }
            BinaryDataArrayType::Float64 => {
                let view = self.to_f64()?;
                let recast = to_bytes(&view);
                self.dtype = dtype;
                self.set_buffer_of_type(recast)
            }
            BinaryDataArrayType::Int32 => {
                let view = self.to_i32()?;
                let recast = to_bytes(&view);
                self.dtype = dtype;
                self.set_buffer_of_type(recast)
            }
            BinaryDataArrayType::Int64 => {
                let view = self.to_i64()?;
                let recast = to_bytes(&view);
                self.dtype = dtype;
                self.set_buffer_of_type(recast)
            }
            _ => Ok(0),
        }
    }

    /// Test if the the array describes an ion mobility quantity.
    ///
    /// # See also
    /// [`ArrayType::is_ion_mobility`]
    pub const fn is_ion_mobility(&self) -> bool {
        self.name.is_ion_mobility()
    }

    /// The size of the raw byte buffer
    pub fn raw_len(&self) -> usize {
        self.data.len()
    }

    /// Get the identifier referencing a [`DataProcessing`](crate::meta::DataProcessing)
    pub fn data_processing_reference(&self) -> Option<&str> {
        self.data_processing_reference.as_deref()
    }

    /// Set the identifier referencing a [`DataProcessing`](crate::meta::DataProcessing)
    pub fn set_data_processing_reference(&mut self, data_processing_reference: Option<Box<str>>) {
        self.data_processing_reference = data_processing_reference;
    }
}


/// [`DataArray`] implements several compression codecs, some of which require additional dependencies.
impl DataArray {
    pub fn compress_zlib(bytestring: &[u8]) -> Bytes {
        let result = Bytes::new();
        let mut compressor = ZlibEncoder::new(result, Compression::best());
        compressor.write_all(bytestring).expect("Error compressing");
        compressor.finish().expect("Error compressing")
    }

    pub fn decompress_zlib(bytestring: &[u8]) -> Bytes {
        let result = Bytes::new();
        let mut decompressor = ZlibDecoder::new(result);
        decompressor
            .write_all(bytestring)
            .unwrap_or_else(|e| panic!("Decompression error: {}", e));
        decompressor
            .finish()
            .unwrap_or_else(|e| panic!("Decompression error: {}", e))
    }

    #[cfg(feature = "numpress")]
    pub fn compress_numpress_linear(data: &[f64]) -> Result<Bytes, ArrayRetrievalError> {
        if data.is_empty() {
            return Ok(Bytes::new());
        }
        let scaling = numpress::optimal_scaling(data);
        match numpress::numpress_compress(data, scaling) {
            Ok(data) => Ok(data),
            Err(e) => Err(ArrayRetrievalError::DecompressionError(e.to_string())),
        }
    }

    #[cfg(feature = "numpress")]
    pub fn compress_numpress_slof<T: numpress::AsFloat64>(data: &[T]) -> Result<Bytes, ArrayRetrievalError> {
        let scaling = numpress::optimal_slof_fixed_point(data);
        let mut buf = Bytes::new();
        match numpress::encode_slof(data, &mut buf, scaling) {
            Ok(_) => Ok(buf),
            Err(e) => Err(ArrayRetrievalError::DecompressionError(e.to_string())),
        }
    }

    #[cfg(feature = "numpress")]
    pub fn decompress_numpress_linear(data: &[u8]) -> Result<Vec<f64>, ArrayRetrievalError> {
        if data.is_empty() {
            return Ok(Vec::new())
        }
        match numpress::numpress_decompress(data) {
            Ok(data) => Ok(data),
            Err(e) => Err(ArrayRetrievalError::DecompressionError(e.to_string())),
        }
    }

    #[cfg(feature = "numpress")]
    pub fn decompress_numpress_slof(data: &[u8], dtype: BinaryDataArrayType) -> Result<Cow<'static, [u8]>, ArrayRetrievalError> {
        use log::trace;

        let mut buf = Vec::new();
        let decoded = match numpress::decode_slof(data, &mut buf) {
            Ok(_) => buf,
            Err(e) => return Err(ArrayRetrievalError::DecompressionError(e.to_string())),
        };
        trace!("Numpress SLOF decoded to {} points", decoded.len());
        match dtype {
            BinaryDataArrayType::Float64 => {
                let view = vec_as_bytes(decoded);
                Ok(Cow::Owned(view))
            },
            BinaryDataArrayType::Float32 => {
                let n = decoded.len() * BinaryDataArrayType::Float32.size_of();
                trace!("Mapping to {n} bytes for f32 storage");
                let mut view: Vec<u8> = Vec::with_capacity(n);
                for val in decoded {
                    let val = val as f32;
                    view.extend(bytemuck::bytes_of(&val))
                }
                Ok(Cow::Owned(view))
            },
            _ => {
                Err(ArrayRetrievalError::DecompressionError(
                    BinaryCompressionType::NumpressSLOF.unsupported_msg(Some(
                        format!("Not compatible with {:?}", dtype).as_str(),
                    )),
                ))
            }
        }
    }

    #[cfg(feature = "zstd")]
    pub(crate) fn compress_zstd(
        bytestring: &[u8],
        dtype: BinaryDataArrayType,
        shuffle: bool,
    ) -> Bytes {
        let level: i32 = std::env::var("MZDATA_ZSTD_LEVEL")
            .map(|v| v.parse())
            .unwrap_or(Ok(zstd::DEFAULT_COMPRESSION_LEVEL))
            .unwrap_or(zstd::DEFAULT_COMPRESSION_LEVEL);
        if !shuffle {
            return zstd::bulk::compress(bytestring, level).unwrap();
        }
        match dtype {
            BinaryDataArrayType::Unknown | BinaryDataArrayType::ASCII => {
                zstd::bulk::compress(bytestring, level).unwrap()
            }
            BinaryDataArrayType::Float64 => {
                zstd::bulk::compress(&transpose_f64(bytemuck::cast_slice(bytestring)), level)
                    .unwrap()
            }
            BinaryDataArrayType::Float32 => {
                zstd::bulk::compress(&transpose_f32(bytemuck::cast_slice(bytestring)), level)
                    .unwrap()
            }
            BinaryDataArrayType::Int64 => {
                zstd::bulk::compress(&transpose_i64(bytemuck::cast_slice(bytestring)), level)
                    .unwrap()
            }
            BinaryDataArrayType::Int32 => {
                zstd::bulk::compress(&transpose_i32(bytemuck::cast_slice(bytestring)), level)
                    .unwrap()
            }
        }
    }

    #[cfg(feature = "zstd")]
    pub(crate) fn compress_delta_zstd(
        bytestring: &[u8],
        dtype: BinaryDataArrayType,
        shuffle: bool,
    ) -> Bytes {
        use bytemuck::cast_slice;

        use super::delta_encoding;

        match dtype {
            BinaryDataArrayType::Unknown | BinaryDataArrayType::ASCII => {
                Self::compress_zstd(bytestring, dtype, shuffle)
            }
            BinaryDataArrayType::Float64 => {
                let mut buf = cast_slice::<_, f64>(bytestring).to_vec();
                delta_encoding(&mut buf);
                Self::compress_zstd(cast_slice(&buf), dtype, shuffle)
            }
            BinaryDataArrayType::Float32 => {
                let mut buf = cast_slice::<_, f32>(bytestring).to_vec();
                delta_encoding(&mut buf);
                Self::compress_zstd(cast_slice(&buf), dtype, shuffle)
            }
            BinaryDataArrayType::Int64 => {
                let mut buf = cast_slice::<_, i64>(bytestring).to_vec();
                delta_encoding(&mut buf);
                Self::compress_zstd(cast_slice(&buf), dtype, shuffle)
            }
            BinaryDataArrayType::Int32 => {
                let mut buf = cast_slice::<_, i32>(bytestring).to_vec();
                delta_encoding(&mut buf);
                Self::compress_zstd(cast_slice(&buf), dtype, shuffle)
            }
        }
    }

    #[cfg(feature = "zstd")]
    pub fn compress_dict_zstd(bytestring: &[u8], dtype: BinaryDataArrayType) -> Bytes {
        use super::encodings::dictionary_encoding;
        log::trace!("Dictionary encoding {} bytes as {dtype}", bytestring.len());
        if bytestring.is_empty() {
            return Self::compress_zstd(&bytestring, dtype, false);
        }
        match dtype {
            BinaryDataArrayType::Float64 => {
                let compressed =
                    dictionary_encoding(bytemuck::cast_slice::<u8, f64>(&bytestring))
                        .unwrap();
                let compressed = Self::compress_zstd(&compressed, dtype, false);
                compressed
            }
            BinaryDataArrayType::Float32 => {
                let compressed =
                    dictionary_encoding(bytemuck::cast_slice::<u8, f32>(&bytestring))
                        .unwrap();
                let compressed = Self::compress_zstd(&compressed, dtype, false);
                compressed
            }
            BinaryDataArrayType::Int64 => {
                let compressed =
                    dictionary_encoding(bytemuck::cast_slice::<u8, i64>(&bytestring))
                        .unwrap();
                let compressed = Self::compress_zstd(&compressed, dtype, false);
                compressed
            }
            BinaryDataArrayType::Int32 => {
                let compressed =
                    dictionary_encoding(bytemuck::cast_slice::<u8, i32>(&bytestring))
                        .unwrap();
                let compressed = Self::compress_zstd(&compressed, dtype, false);
                compressed
            }
            _ => {
                let compressed =
                    dictionary_encoding(bytemuck::cast_slice::<u8, u8>(&bytestring))
                        .unwrap();
                let compressed = Self::compress_zstd(&compressed, dtype, false);
                compressed
            }
        }
    }

    #[cfg(feature = "zstd")]
    pub(crate) fn decompress_zstd(data: &[u8], dtype: BinaryDataArrayType, shuffle: bool) -> Bytes {
        let mut decoder = zstd::Decoder::new(std::io::Cursor::new(data)).unwrap();
        let mut buf = Vec::new();
        decoder.read_to_end(&mut buf).unwrap();
        if !shuffle {
            return buf;
        }
        match dtype {
            BinaryDataArrayType::Unknown | BinaryDataArrayType::ASCII => buf,
            BinaryDataArrayType::Float64 => reverse_transpose_f64(&buf),
            BinaryDataArrayType::Float32 => reverse_transpose_f32(&buf),
            BinaryDataArrayType::Int64 => reverse_transpose_i64(&buf),
            BinaryDataArrayType::Int32 => reverse_transpose_i32(&buf),
        }
    }

    #[cfg(feature = "zstd")]
    pub(crate) fn decompress_delta_zstd(
        data: &[u8],
        dtype: BinaryDataArrayType,
        shuffle: bool,
    ) -> Bytes {
        use super::delta_decoding;

        let mut delta = Self::decompress_zstd(data, dtype, shuffle);
        match dtype {
            BinaryDataArrayType::Unknown | BinaryDataArrayType::ASCII => delta,
            BinaryDataArrayType::Float64 => {
                let buf = bytemuck::cast_slice_mut::<_, f64>(&mut delta);
                delta_decoding(buf);
                delta
            }
            BinaryDataArrayType::Float32 => {
                let buf = bytemuck::cast_slice_mut::<_, f32>(&mut delta);
                delta_decoding(buf);
                delta
            }
            BinaryDataArrayType::Int64 => {
                let buf = bytemuck::cast_slice_mut::<_, i64>(&mut delta);
                delta_decoding(buf);
                delta
            }
            BinaryDataArrayType::Int32 => {
                let buf = bytemuck::cast_slice_mut::<_, i32>(&mut delta);
                delta_decoding(buf);
                delta
            }
        }
    }

    #[cfg(feature = "zstd")]
    pub(crate) fn decompress_dict_zstd(bytestring: &[u8], dtype: BinaryDataArrayType) -> Bytes {
        use super::encodings::dictionary_decoding;

        let data = Self::decompress_zstd(bytestring, dtype, false);
        match dtype {
            BinaryDataArrayType::ASCII | BinaryDataArrayType::Unknown => dictionary_decoding(&data).unwrap(),
            BinaryDataArrayType::Float64 => {
                to_bytes(&dictionary_decoding::<f64>(&data).unwrap())
            },
            BinaryDataArrayType::Float32 => {
                to_bytes(&dictionary_decoding::<f32>(&data).unwrap())
            },
            BinaryDataArrayType::Int64 => {
                to_bytes(&dictionary_decoding::<i64>(&data).unwrap())
            },
            BinaryDataArrayType::Int32 => {
                to_bytes(&dictionary_decoding::<i32>(&data).unwrap())
            },
        }
    }
}

impl<'transient, 'lifespan: 'transient> ByteArrayView<'transient, 'lifespan> for DataArray {
    fn view(&'lifespan self) -> Result<Cow<'lifespan, [u8]>, ArrayRetrievalError> {
        self.decode()
    }

    fn dtype(&self) -> BinaryDataArrayType {
        self.dtype
    }

    fn data_len(&'lifespan self) -> Result<usize, ArrayRetrievalError> {
        if let Some(z) = self.item_count {
            Ok(z)
        } else {
            let view = self.view()?;
            let n = view.len();
            Ok(n / self.dtype().size_of())
        }
    }

    fn unit(&self) -> Unit {
        self.unit
    }

    fn data_processing_reference(&self) -> Option<&str> {
        self.data_processing_reference()
    }

    fn name(&self) -> &ArrayType {
        &self.name
    }
}

impl<'transient, 'lifespan: 'transient> ByteArrayViewMut<'transient, 'lifespan> for DataArray {
    fn view_mut(&'transient mut self) -> Result<&'transient mut Bytes, ArrayRetrievalError> {
        self.decode_mut()
    }

    fn unit_mut(&mut self) -> &mut Unit {
        &mut self.unit
    }

    fn set_data_processing_reference(&mut self, data_processing_reference: Option<Box<str>>) {
        self.set_data_processing_reference(data_processing_reference);
    }
}

impl_param_described_deferred!(DataArray);

/// Represent a slice of a [`DataArray`] that manages offsets and decoding automatically.
#[derive(Clone, Debug)]
pub struct DataArraySlice<'a> {
    source: &'a DataArray,
    pub start: usize,
    pub end: usize,
}

impl<'a> DataArraySlice<'a> {
    pub fn new(source: &'a DataArray, mut start: usize, mut end: usize) -> Self {
        if start > end {
            mem::swap(&mut start, &mut end);
        }
        Self { source, start, end }
    }

    pub fn decode(&'a self) -> Result<Cow<'a, [u8]>, ArrayRetrievalError> {
        self.source.decoded_slice(self.start, self.end)
    }

    pub const fn is_ion_mobility(&self) -> bool {
        self.source.is_ion_mobility()
    }
}

impl<'transient, 'lifespan: 'transient> ByteArrayView<'transient, 'lifespan>
    for DataArraySlice<'lifespan>
{
    fn view(&'lifespan self) -> Result<Cow<'lifespan, [u8]>, ArrayRetrievalError> {
        self.decode()
    }

    fn dtype(&self) -> BinaryDataArrayType {
        self.source.dtype()
    }

    fn unit(&self) -> Unit {
        self.source.unit
    }

    fn name(&self) -> &ArrayType {
        self.source.name()
    }

    fn data_processing_reference(&self) -> Option<&str> {
        self.source.data_processing_reference()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::fs;
    use std::io;

    use super::DataArray;

    fn make_array_from_file() -> io::Result<DataArray> {
        let mut fh = fs::File::open("./test/data/mz_f64_zlib_bas64.txt")?;
        let mut buf = String::new();
        fh.read_to_string(&mut buf)?;
        let bytes: Vec<u8> = buf.into();
        let mut da = DataArray::wrap(&ArrayType::MZArray, BinaryDataArrayType::Float64, bytes);
        da.compression = BinaryCompressionType::Zlib;
        *da.unit_mut() = Unit::MZ;
        assert_eq!(da.unit(), Unit::MZ);
        assert!(!da.is_ion_mobility());
        assert_eq!(da.name(), &ArrayType::MZArray);
        Ok(da)
    }

    #[cfg(feature = "zstd")]
    fn make_array_from_file_im_zstd() -> io::Result<DataArray> {
        let mut fh = fs::File::open("test/data/im_f64_zstd_base64.txt")?;
        let mut buf = String::new();
        fh.read_to_string(&mut buf)?;
        let bytes: Vec<u8> = buf.into();
        let mut da = DataArray::wrap(&ArrayType::MeanInverseReducedIonMobilityArray, BinaryDataArrayType::Float64, bytes);
        da.compression = BinaryCompressionType::Zstd;
        *da.unit_mut() = Unit::VoltSecondPerSquareCentimeter;
        assert_eq!(da.unit(), Unit::VoltSecondPerSquareCentimeter);
        assert!(da.is_ion_mobility());
        assert_eq!(da.name(), &ArrayType::MeanInverseReducedIonMobilityArray);
        Ok(da)
    }

    #[test]
    fn test_decode() -> io::Result<()> {
        let mut da = make_array_from_file()?;
        da.decode_and_store()?;
        let view = da.to_f64()?;
        assert_eq!(view.len(), 19800);
        Ok(())
    }

    #[test]
    fn test_decode_store() -> io::Result<()> {
        let mut da = make_array_from_file()?;
        da.decode_and_store()?;
        let back = da.clone();
        da.store_as(BinaryDataArrayType::Float32)?;
        let view = da.to_f64()?;
        assert_eq!(view.len(), 19800);
        for (a, b) in back.iter_f64()?.zip(view.iter().copied()) {
            let err = (a - b).abs();
            assert!((a - b).abs() < 1e-3, "{} - {} = {}", a, b, err);
        }
        for (a, b) in back.iter_f64()?.zip(da.iter_f32()?.map(|x| x as f64)) {
            let err = (a - b).abs();
            assert!((a - b).abs() < 1e-3, "{} - {} = {}", a, b, err);
        }
        da.store_as(BinaryDataArrayType::Float64)?;
        let view = da.to_f64()?;
        assert_eq!(view.len(), 19800);
        for (a, b) in back.iter_f64()?.zip(view.iter().copied()) {
            let err = (a - b).abs();
            assert!((a - b).abs() < 1e-3, "{} - {} = {}", a, b, err);
        }
        Ok(())
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn test_decode_delta_zstd() {
        let points: Vec<f64> = (0..200_000usize).map(|i| i as f64 * 0.01 + 100.0).collect();
        let mut da = DataArray::from_name(&ArrayType::MZArray);
        da.extend(&points).unwrap();

        let decoded_len = da.data.len();
        da.store_compressed(BinaryCompressionType::ShuffleZstd)
            .unwrap();
        let zstd_len = da.data.len();

        da.store_compressed(BinaryCompressionType::Zlib).unwrap();
        let zlib_len = da.data.len();

        da.decode_and_store().unwrap();

        da.store_compressed(BinaryCompressionType::DeltaShuffleZstd)
            .unwrap();
        let delta_zstd_len = da.data.len();
        eprintln!("decoded: {decoded_len};\nzlib: {zlib_len};\nzstd: {zstd_len};\ndelta-zstd: {delta_zstd_len}");
        da.decode_and_store().unwrap();
        let view = da.to_f64().unwrap();
        let err: f64 = points
            .iter()
            .zip(view.iter())
            .map(|(a, b)| {
                assert!((a - b).abs() < 1e-3, "{a} - {b} = {}", a - b);
                (a - b).abs()
            })
            .sum();
        let mean_err = err / (points.len() as f64);
        eprintln!("mean abs error: {mean_err:0.8}")
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn test_decode_zstd() -> io::Result<()> {
        let mut da = make_array_from_file()?;
        let zlib_len = da.data.len();
        da.decode_and_store()?;

        let decoded_len = da.data.len();

        da.store_compressed(BinaryCompressionType::ShuffleZstd)?;

        let zstd_len = da.data.len();

        eprintln!("zlib: {zlib_len};\ndecoded: {decoded_len};\nzstd: {zstd_len}");
        da.decode_and_store()?;

        let mut da_ref = make_array_from_file()?;
        da_ref.decode_and_store()?;
        assert_eq!(da.data, da_ref.data);
        Ok(())
    }

    #[cfg(feature = "numpress")]
    #[test]
    fn test_numpress_linear() -> io::Result<()> {
        let mut da = make_array_from_file()?;
        let zlib_len = da.data.len();
        da.decode_and_store()?;

        let decoded_len = da.data.len();

        da.store_compressed(BinaryCompressionType::NumpressLinear)?;
        let numpress_len = da.data.len();

        eprintln!("zlib: {zlib_len};\ndecoded: {decoded_len};\nnumpress: {numpress_len}");
        da.decode_and_store()?;

        let mut da_ref = make_array_from_file()?;
        da_ref.decode_and_store()?;
        for (a, b) in da.iter_f64()?.zip(da_ref.iter_f64()?) {
            assert!((a - b).abs() < 1e-3, "{a} - {b} = {} which is too large a deviation", (a - b).abs())
        }

        Ok(())
    }

    #[test]
    fn test_decode_roundtrip() -> io::Result<()> {
        let mut da = make_array_from_file()?;
        let compressed_size = da.data_len()?;
        da.decode_and_store()?;
        let view = da.to_f64()?;
        assert_eq!(view.len(), 19800);
        drop(view);
        da.store_compressed(BinaryCompressionType::Zlib)?;
        assert_eq!(da.compression, BinaryCompressionType::Zlib);
        assert_eq!(da.data_len()?, compressed_size);
        let view = da.to_f64()?;
        assert_eq!(view.len(), 19800);
        Ok(())
    }

    #[test]
    fn test_decode_empty() {
        let mut da = DataArray::wrap(
            &ArrayType::MZArray,
            BinaryDataArrayType::Float64,
            Vec::new(),
        );
        da.compression = BinaryCompressionType::Zlib;

        assert_eq!(da.data.len(), 0);
        assert_eq!(da.data_len().unwrap(), 0);
        assert_eq!(da.decode().unwrap().len(), 0);
        assert_eq!(da.to_f64().unwrap().len(), 0);
    }


    #[cfg(feature = "zstd")]
    #[test]
    fn test_dict_from_base64() -> io::Result<()> {
        let mut da = make_array_from_file_im_zstd()?;

        da.decode_and_store()?;
        assert_eq!(da.data_len()?, 221);

        da.store_compressed(BinaryCompressionType::ZstdDict)?;
        assert_eq!(da.data_len()?, 221);

        da.store_compressed(BinaryCompressionType::ShuffleZstd)?;
        assert_eq!(da.data_len()?, 221);

        Ok(())
    }
}