hdf5-types 0.8.1

Native Rust equivalents of HDF5 types.
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
use std::fmt::{self, Debug, Display};
use std::mem;
use std::ptr;
use std::slice;

use crate::h5type::{hvl_t, CompoundType, EnumType, FloatSize, H5Type, IntSize, TypeDescriptor};
use crate::string::{VarLenAscii, VarLenUnicode};

fn read_raw<T: Copy>(buf: &[u8]) -> T {
    debug_assert_eq!(mem::size_of::<T>(), buf.len());
    unsafe { *(buf.as_ptr() as *const T) }
}

fn write_raw<T: Copy>(out: &mut [u8], value: T) {
    debug_assert_eq!(mem::size_of::<T>(), out.len());
    unsafe {
        *(out.as_mut_ptr() as *mut T) = value;
    }
}

unsafe trait DynDrop {
    fn dyn_drop(&mut self) {}
}

unsafe trait DynClone {
    fn dyn_clone(&mut self, out: &mut [u8]);
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum DynInteger {
    Int8(i8),
    Int16(i16),
    Int32(i32),
    Int64(i64),
    UInt8(u8),
    UInt16(u16),
    UInt32(u32),
    UInt64(u64),
}

impl DynInteger {
    pub(self) fn read(buf: &[u8], signed: bool, size: IntSize) -> Self {
        use DynInteger::*;
        match (signed, size) {
            (true, IntSize::U1) => Int8(read_raw(buf)),
            (true, IntSize::U2) => Int16(read_raw(buf)),
            (true, IntSize::U4) => Int32(read_raw(buf)),
            (true, IntSize::U8) => Int64(read_raw(buf)),
            (false, IntSize::U1) => UInt8(read_raw(buf)),
            (false, IntSize::U2) => UInt16(read_raw(buf)),
            (false, IntSize::U4) => UInt32(read_raw(buf)),
            (false, IntSize::U8) => UInt64(read_raw(buf)),
        }
    }

    pub(self) fn as_u64(self) -> u64 {
        use DynInteger::*;
        match self {
            Int8(x) => x as _,
            Int16(x) => x as _,
            Int32(x) => x as _,
            Int64(x) => x as _,
            UInt8(x) => x as _,
            UInt16(x) => x as _,
            UInt32(x) => x as _,
            UInt64(x) => x as _,
        }
    }
}

unsafe impl DynClone for DynInteger {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        use DynInteger::*;
        match self {
            Int8(x) => write_raw(out, *x),
            Int16(x) => write_raw(out, *x),
            Int32(x) => write_raw(out, *x),
            Int64(x) => write_raw(out, *x),
            UInt8(x) => write_raw(out, *x),
            UInt16(x) => write_raw(out, *x),
            UInt32(x) => write_raw(out, *x),
            UInt64(x) => write_raw(out, *x),
        }
    }
}

impl Debug for DynInteger {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use DynInteger::*;
        match *self {
            Int8(x) => Debug::fmt(&x, f),
            Int16(x) => Debug::fmt(&x, f),
            Int32(x) => Debug::fmt(&x, f),
            Int64(x) => Debug::fmt(&x, f),
            UInt8(x) => Debug::fmt(&x, f),
            UInt16(x) => Debug::fmt(&x, f),
            UInt32(x) => Debug::fmt(&x, f),
            UInt64(x) => Debug::fmt(&x, f),
        }
    }
}

impl Display for DynInteger {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl From<DynInteger> for DynScalar {
    fn from(value: DynInteger) -> Self {
        DynScalar::Integer(value)
    }
}

impl From<DynInteger> for DynValue<'_> {
    fn from(value: DynInteger) -> Self {
        DynScalar::Integer(value).into()
    }
}

#[derive(Copy, Clone, PartialEq)]
pub enum DynScalar {
    Integer(DynInteger),
    Float32(f32),
    Float64(f64),
    Boolean(bool),
}

unsafe impl DynClone for DynScalar {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        use DynScalar::*;
        match self {
            Integer(x) => x.dyn_clone(out),
            Float32(x) => write_raw(out, *x),
            Float64(x) => write_raw(out, *x),
            Boolean(x) => write_raw(out, *x),
        }
    }
}

impl Debug for DynScalar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use DynScalar::*;
        match self {
            Integer(x) => Debug::fmt(&x, f),
            Float32(x) => Debug::fmt(&x, f),
            Float64(x) => Debug::fmt(&x, f),
            Boolean(x) => Debug::fmt(&x, f),
        }
    }
}

impl Display for DynScalar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl From<DynScalar> for DynValue<'static> {
    fn from(value: DynScalar) -> Self {
        DynValue::Scalar(value)
    }
}

#[derive(Copy, Clone)]
pub struct DynEnum<'a> {
    tp: &'a EnumType,
    value: DynInteger,
}

impl<'a> DynEnum<'a> {
    pub fn new(tp: &'a EnumType, value: DynInteger) -> Self {
        Self { tp, value }
    }

    pub fn name(&self) -> Option<&str> {
        let value = self.value.as_u64();
        for member in &self.tp.members {
            if member.value == value {
                return Some(&member.name);
            }
        }
        None
    }
}

unsafe impl DynClone for DynEnum<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        self.value.dyn_clone(out)
    }
}

impl PartialEq for DynEnum<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl Eq for DynEnum<'_> {}

impl Debug for DynEnum<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.name() {
            Some(name) => f.write_str(name),
            None => Debug::fmt(&self.value, f),
        }
    }
}

impl Display for DynEnum<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl<'a> From<DynEnum<'a>> for DynValue<'a> {
    fn from(value: DynEnum<'a>) -> Self {
        DynValue::Enum(value)
    }
}

pub struct DynCompound<'a> {
    tp: &'a CompoundType,
    buf: &'a [u8],
}

impl<'a> DynCompound<'a> {
    pub fn new(tp: &'a CompoundType, buf: &'a [u8]) -> Self {
        Self { tp, buf }
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, DynValue)> {
        self.tp.fields.iter().map(move |field| {
            (
                field.name.as_ref(),
                DynValue::new(&field.ty, &self.buf[field.offset..(field.offset + field.ty.size())]),
            )
        })
    }
}

unsafe impl DynDrop for DynCompound<'_> {
    fn dyn_drop(&mut self) {
        for (_, mut value) in self.iter() {
            value.dyn_drop();
        }
    }
}

unsafe impl DynClone for DynCompound<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        debug_assert_eq!(out.len(), self.tp.size);
        for (i, (_, mut value)) in self.iter().enumerate() {
            let field = &self.tp.fields[i];
            value.dyn_clone(&mut out[field.offset..(field.offset + field.ty.size())]);
        }
    }
}

impl PartialEq for DynCompound<'_> {
    fn eq(&self, other: &Self) -> bool {
        let (mut it1, mut it2) = (self.iter(), other.iter());
        loop {
            match (it1.next(), it2.next()) {
                (Some(v1), Some(v2)) => {
                    if v1 != v2 {
                        return false;
                    }
                }
                (None, None) => return true,
                _ => return false,
            }
        }
    }
}

struct RawStr<'a>(&'a str);

impl Debug for RawStr<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.0)
    }
}

impl Debug for DynCompound<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut b = f.debug_map();
        for (name, value) in self.iter() {
            b.entry(&RawStr(name), &value);
        }
        b.finish()
    }
}

impl Display for DynCompound<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl<'a> From<DynCompound<'a>> for DynValue<'a> {
    fn from(value: DynCompound<'a>) -> Self {
        DynValue::Compound(value)
    }
}

pub struct DynArray<'a> {
    tp: &'a TypeDescriptor,
    buf: &'a [u8],
    len: Option<usize>,
}

impl<'a> DynArray<'a> {
    pub fn new(tp: &'a TypeDescriptor, buf: &'a [u8], len: Option<usize>) -> Self {
        Self { tp, buf, len }
    }

    fn get_ptr(&self) -> *const u8 {
        match self.len {
            Some(_) => self.buf.as_ptr(),
            None => read_raw::<hvl_t>(self.buf).ptr as *const u8,
        }
    }

    fn get_len(&self) -> usize {
        match self.len {
            Some(len) => len,
            None => read_raw::<hvl_t>(self.buf).len,
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = DynValue> {
        let ptr = self.get_ptr();
        let len = self.get_len();
        let size = self.tp.size();
        let buf = if !ptr.is_null() && len != 0 {
            unsafe { slice::from_raw_parts(ptr, len * size) }
        } else {
            [].as_ref()
        };
        (0..len).map(move |i| DynValue::new(self.tp, &buf[(i * size)..((i + 1) * size)]))
    }
}

unsafe impl DynDrop for DynArray<'_> {
    fn dyn_drop(&mut self) {
        for mut value in self.iter() {
            value.dyn_drop();
        }
        if self.len.is_none() && !self.get_ptr().is_null() {
            unsafe {
                crate::free(self.get_ptr() as *mut _);
            }
        }
    }
}

unsafe impl DynClone for DynArray<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        let (len, ptr, size) = (self.get_len(), self.get_ptr(), self.tp.size());
        let out = if self.len.is_none() {
            debug_assert_eq!(out.len(), mem::size_of::<hvl_t>());
            if !self.get_ptr().is_null() {
                unsafe {
                    let dst = crate::malloc(len * size) as *mut u8;
                    ptr::copy_nonoverlapping(ptr, dst, len * size);
                    (*(out.as_mut_ptr() as *mut hvl_t)).ptr = dst as _;
                    slice::from_raw_parts_mut(dst, len * size)
                }
            } else {
                return;
            }
        } else {
            out
        };
        debug_assert_eq!(out.len(), len * size);
        for (i, mut value) in self.iter().enumerate() {
            value.dyn_clone(&mut out[(i * size)..((i + 1) * size)]);
        }
    }
}

impl PartialEq for DynArray<'_> {
    fn eq(&self, other: &Self) -> bool {
        let (mut it1, mut it2) = (self.iter(), other.iter());
        loop {
            match (it1.next(), it2.next()) {
                (Some(v1), Some(v2)) => {
                    if v1 != v2 {
                        return false;
                    }
                }
                (None, None) => return true,
                _ => return false,
            }
        }
    }
}

impl Debug for DynArray<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut b = f.debug_list();
        for value in self.iter() {
            b.entry(&value);
        }
        b.finish()
    }
}

impl Display for DynArray<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl<'a> From<DynArray<'a>> for DynValue<'a> {
    fn from(value: DynArray<'a>) -> Self {
        DynValue::Array(value)
    }
}

pub struct DynFixedString<'a> {
    buf: &'a [u8],
    unicode: bool,
}

impl<'a> DynFixedString<'a> {
    pub fn new(buf: &'a [u8], unicode: bool) -> Self {
        Self { buf, unicode }
    }

    pub fn raw_len(&self) -> usize {
        self.buf.iter().rev().skip_while(|&c| *c == 0).count()
    }

    pub fn get_buf(&self) -> &[u8] {
        &self.buf[..self.raw_len()]
    }
}

unsafe impl DynClone for DynFixedString<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        debug_assert_eq!(self.buf.len(), out.len());
        out.clone_from_slice(self.buf);
    }
}

impl PartialEq for DynFixedString<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.unicode == other.unicode && self.get_buf() == other.get_buf()
    }
}

impl Eq for DynFixedString<'_> {}

impl Debug for DynFixedString<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = unsafe { std::str::from_utf8_unchecked(self.get_buf()) };
        Debug::fmt(&s, f)
    }
}

impl Display for DynFixedString<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl<'a> From<DynFixedString<'a>> for DynString<'a> {
    fn from(value: DynFixedString<'a>) -> Self {
        DynString::Fixed(value)
    }
}

impl<'a> From<DynFixedString<'a>> for DynValue<'a> {
    fn from(value: DynFixedString<'a>) -> Self {
        DynString::Fixed(value).into()
    }
}

pub struct DynVarLenString<'a> {
    buf: &'a [u8],
    unicode: bool,
}

impl<'a> DynVarLenString<'a> {
    pub fn new(buf: &'a [u8], unicode: bool) -> Self {
        Self { buf, unicode }
    }

    fn get_ptr(&self) -> *const u8 {
        if self.unicode {
            self.as_unicode().as_ptr()
        } else {
            self.as_ascii().as_ptr()
        }
    }

    fn raw_len(&self) -> usize {
        if self.unicode {
            self.as_unicode().as_bytes().len()
        } else {
            self.as_ascii().as_bytes().len()
        }
    }

    fn as_ascii(&self) -> &VarLenAscii {
        unsafe { &*(self.buf.as_ptr() as *const VarLenAscii) }
    }

    fn as_unicode(&self) -> &VarLenUnicode {
        unsafe { &*(self.buf.as_ptr() as *const VarLenUnicode) }
    }
}

unsafe impl DynDrop for DynVarLenString<'_> {
    fn dyn_drop(&mut self) {
        if !self.get_ptr().is_null() {
            unsafe {
                crate::free(self.get_ptr() as *mut _);
            }
        }
    }
}

unsafe impl DynClone for DynVarLenString<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        debug_assert_eq!(out.len(), mem::size_of::<usize>());
        if !self.get_ptr().is_null() {
            unsafe {
                let raw_len = self.raw_len();
                let dst = crate::malloc(raw_len + 1) as *mut _;
                ptr::copy_nonoverlapping(self.get_ptr(), dst, raw_len);
                *dst.add(raw_len) = 0;
                *(out.as_mut_ptr() as *mut *const u8) = dst as _;
            }
        }
    }
}

impl PartialEq for DynVarLenString<'_> {
    fn eq(&self, other: &Self) -> bool {
        match (self.unicode, other.unicode) {
            (true, true) => self.as_unicode() == other.as_unicode(),
            (false, false) => self.as_ascii() == other.as_ascii(),
            _ => false,
        }
    }
}

impl Eq for DynVarLenString<'_> {}

impl Debug for DynVarLenString<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.unicode {
            Debug::fmt(&self.as_unicode(), f)
        } else {
            Debug::fmt(&self.as_ascii(), f)
        }
    }
}

impl Display for DynVarLenString<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl<'a> From<DynVarLenString<'a>> for DynString<'a> {
    fn from(value: DynVarLenString<'a>) -> Self {
        DynString::VarLen(value)
    }
}

impl<'a> From<DynVarLenString<'a>> for DynValue<'a> {
    fn from(value: DynVarLenString<'a>) -> Self {
        DynString::VarLen(value).into()
    }
}

#[derive(PartialEq, Eq)]
pub enum DynString<'a> {
    Fixed(DynFixedString<'a>),
    VarLen(DynVarLenString<'a>),
}

unsafe impl DynDrop for DynString<'_> {
    fn dyn_drop(&mut self) {
        if let DynString::VarLen(string) = self {
            string.dyn_drop();
        }
    }
}

unsafe impl DynClone for DynString<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        use DynString::*;
        match self {
            Fixed(x) => x.dyn_clone(out),
            VarLen(x) => x.dyn_clone(out),
        }
    }
}

impl Debug for DynString<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use DynString::*;
        match self {
            Fixed(x) => Debug::fmt(&x, f),
            VarLen(x) => Debug::fmt(&x, f),
        }
    }
}

impl Display for DynString<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl<'a> From<DynString<'a>> for DynValue<'a> {
    fn from(value: DynString<'a>) -> Self {
        DynValue::String(value)
    }
}

#[derive(PartialEq)]
pub enum DynValue<'a> {
    Scalar(DynScalar),
    Enum(DynEnum<'a>),
    Compound(DynCompound<'a>),
    Array(DynArray<'a>),
    String(DynString<'a>),
}

impl<'a> DynValue<'a> {
    pub fn new(tp: &'a TypeDescriptor, buf: &'a [u8]) -> Self {
        use TypeDescriptor::*;
        debug_assert_eq!(tp.size(), buf.len());

        match tp {
            Integer(size) => DynInteger::read(buf, true, *size).into(),
            Unsigned(size) => DynInteger::read(buf, true, *size).into(),
            Float(FloatSize::U4) => DynScalar::Float32(read_raw(buf)).into(),
            Float(FloatSize::U8) => DynScalar::Float64(read_raw(buf)).into(),
            Boolean => DynScalar::Boolean(read_raw(buf)).into(),
            Enum(ref tp) => DynEnum::new(tp, DynInteger::read(buf, tp.signed, tp.size)).into(),
            Compound(ref tp) => DynCompound::new(tp, buf).into(),
            FixedArray(ref tp, n) => DynArray::new(tp, buf, Some(*n)).into(),
            VarLenArray(ref tp) => DynArray::new(tp, buf, None).into(),
            FixedAscii(_) => DynFixedString::new(buf, false).into(),
            FixedUnicode(_) => DynFixedString::new(buf, true).into(),
            VarLenAscii => DynVarLenString::new(buf, false).into(),
            VarLenUnicode => DynVarLenString::new(buf, true).into(),
        }
    }
}

unsafe impl DynDrop for DynValue<'_> {
    fn dyn_drop(&mut self) {
        use DynValue::*;
        match self {
            Compound(x) => x.dyn_drop(),
            Array(x) => x.dyn_drop(),
            String(x) => x.dyn_drop(),
            _ => (),
        }
    }
}

unsafe impl DynClone for DynValue<'_> {
    fn dyn_clone(&mut self, out: &mut [u8]) {
        use DynValue::*;
        match self {
            Scalar(x) => x.dyn_clone(out),
            Enum(x) => x.dyn_clone(out),
            Compound(x) => x.dyn_clone(out),
            Array(x) => x.dyn_clone(out),
            String(x) => x.dyn_clone(out),
        }
    }
}

impl Debug for DynValue<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use DynValue::*;
        match self {
            Scalar(x) => Debug::fmt(&x, f),
            Enum(x) => Debug::fmt(&x, f),
            Compound(x) => Debug::fmt(&x, f),
            Array(x) => Debug::fmt(&x, f),
            String(x) => Debug::fmt(&x, f),
        }
    }
}

impl Display for DynValue<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

pub struct OwnedDynValue {
    tp: TypeDescriptor,
    buf: Box<[u8]>,
}

impl OwnedDynValue {
    pub fn new<T: H5Type>(value: T) -> Self {
        let ptr = &value as *const _ as *const u8;
        let len = mem::size_of_val(&value);
        let buf = unsafe { std::slice::from_raw_parts(ptr, len) };
        mem::forget(value);
        Self { tp: T::type_descriptor(), buf: buf.to_owned().into_boxed_slice() }
    }

    pub fn get(&self) -> DynValue {
        DynValue::new(&self.tp, &self.buf)
    }

    pub fn type_descriptor(&self) -> &TypeDescriptor {
        &self.tp
    }

    #[doc(hidden)]
    pub unsafe fn get_buf(&self) -> &[u8] {
        &self.buf
    }

    #[doc(hidden)]
    pub unsafe fn from_raw(tp: TypeDescriptor, buf: Box<[u8]>) -> Self {
        Self { tp, buf }
    }

    /// Cast to the concrete type
    ///
    /// Will fail if the type-descriptors are not equal
    pub fn cast<T: H5Type>(mut self) -> Result<T, Self> {
        use mem::MaybeUninit;
        if self.tp != T::type_descriptor() {
            return Err(self);
        }
        debug_assert_eq!(self.tp.size(), self.buf.len());
        let mut out = MaybeUninit::<T>::uninit();
        unsafe {
            ptr::copy_nonoverlapping(
                self.buf.as_ptr(),
                out.as_mut_ptr().cast::<u8>(),
                self.buf.len(),
            );
        }
        // For safety we must ensure any nested structures are not live at the same time,
        // as this could cause a double free in `dyn_drop`.
        // We must deallocate only the top level of Self

        // The zero-sized array has a special case to not drop ptr if len is zero,
        // so `dyn_drop` of `DynArray` is a nop
        self.tp = <[u8; 0]>::type_descriptor();
        // We must also swap out the buffer to ensure we can create the `DynValue`
        let mut b: Box<[u8]> = Box::new([]);
        mem::swap(&mut self.buf, &mut b);

        Ok(unsafe { out.assume_init() })
    }
}

impl<T: H5Type> From<T> for OwnedDynValue {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl Drop for OwnedDynValue {
    fn drop(&mut self) {
        self.get().dyn_drop()
    }
}

impl Clone for OwnedDynValue {
    fn clone(&self) -> Self {
        let mut buf = self.buf.clone();
        self.get().dyn_clone(&mut buf);
        Self { tp: self.tp.clone(), buf }
    }
}

impl PartialEq for OwnedDynValue {
    fn eq(&self, other: &Self) -> bool {
        self.get() == other.get()
    }
}

impl Debug for OwnedDynValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(&self.get(), f)
    }
}

impl Display for OwnedDynValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use unindent::unindent;

    use crate::array::VarLenArray;
    use crate::h5type::{TypeDescriptor as TD, *};
    use crate::string::{FixedAscii, FixedUnicode, VarLenAscii, VarLenUnicode};

    use super::*;

    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    #[repr(i16)]
    enum Color {
        Red = -10_000,
        Green = 0,
        Blue = 10_000,
    }

    #[derive(Copy, Clone, Debug, PartialEq)]
    #[repr(C)]
    pub struct Point {
        coords: [f32; 2],
        color: Color,
        nice: bool,
    }

    #[derive(Clone, Debug, PartialEq)]
    #[repr(C)]
    struct Data {
        points: VarLenArray<Point>,
        fa: FixedAscii<5>,
        fu: FixedUnicode<5>,
        va: VarLenAscii,
        vu: VarLenUnicode,
    }

    #[derive(Clone, Debug, PartialEq)]
    #[repr(C)]
    struct BigStruct {
        ints: (i8, i16, i32, i64),
        uints: (u8, u16, u32, u64),
        floats: (f32, f64),
        data: Data,
    }

    fn td_color() -> TD {
        TD::Enum(EnumType {
            size: IntSize::U2,
            signed: true,
            members: vec![
                EnumMember { name: "Red".into(), value: -10_000i16 as _ },
                EnumMember { name: "Green".into(), value: 0 },
                EnumMember { name: "Blue".into(), value: 10_000 },
            ],
        })
    }

    fn td_point() -> TD {
        let coords = TD::FixedArray(Box::new(TD::Float(FloatSize::U4)), 2);
        TD::Compound(CompoundType {
            fields: Vec::from(
                [
                    CompoundField::new("coords", coords, 0, 0),
                    CompoundField::new("color", td_color(), 8, 1),
                    CompoundField::new("nice", TD::Boolean, 10, 2),
                ]
                .as_ref(),
            ),
            size: 12,
        })
    }

    fn td_data() -> TD {
        let points = TD::VarLenArray(Box::new(td_point()));
        TD::Compound(CompoundType {
            fields: Vec::from(
                [
                    CompoundField::new("points", points, 0, 0),
                    CompoundField::new("fa", TD::FixedAscii(5), 16, 1),
                    CompoundField::new("fu", TD::FixedUnicode(5), 21, 2),
                    CompoundField::new("va", TD::VarLenAscii, 32, 3),
                    CompoundField::new("vu", TD::VarLenUnicode, 40, 4),
                ]
                .as_ref(),
            ),
            size: 48,
        })
    }

    fn td_big_struct() -> TD {
        let ints = TD::Compound(CompoundType {
            fields: Vec::from(
                [
                    CompoundField::typed::<i32>("2", 0, 2),
                    CompoundField::typed::<i16>("1", 4, 1),
                    CompoundField::typed::<i8>("0", 6, 0),
                    CompoundField::typed::<i64>("3", 8, 3),
                ]
                .as_ref(),
            ),
            size: 16,
        });
        let uints = TD::Compound(CompoundType {
            fields: Vec::from(
                [
                    CompoundField::typed::<u32>("2", 0, 2),
                    CompoundField::typed::<u16>("1", 4, 1),
                    CompoundField::typed::<u8>("0", 6, 0),
                    CompoundField::typed::<u64>("3", 8, 3),
                ]
                .as_ref(),
            ),
            size: 16,
        });
        let floats = TD::Compound(CompoundType {
            fields: Vec::from(
                [CompoundField::typed::<f32>("0", 0, 0), CompoundField::typed::<f64>("1", 8, 1)]
                    .as_ref(),
            ),
            size: 16,
        });
        TD::Compound(CompoundType {
            fields: Vec::from(
                [
                    CompoundField::new("ints", ints, 0, 0),
                    CompoundField::new("uints", uints, 16, 1),
                    CompoundField::new("floats", floats, 32, 2),
                    CompoundField::new("data", td_data(), 48, 3),
                ]
                .as_ref(),
            ),
            size: 96,
        })
    }

    fn big_struct_1() -> BigStruct {
        BigStruct {
            ints: (-10, 20, -30, 40),
            uints: (30, 40, 50, 60),
            floats: (-3.14, 2.71),
            data: Data {
                points: VarLenArray::from_slice(
                    [
                        Point { coords: [-1.0, 2.0], color: Color::Red, nice: true },
                        Point { coords: [0.1, 0.], color: Color::Green, nice: false },
                        Point { coords: [10., 0.], color: Color::Blue, nice: true },
                    ]
                    .as_ref(),
                ),
                fa: FixedAscii::from_ascii(b"12345").unwrap(),
                fu: FixedUnicode::from_str("").unwrap(),
                va: VarLenAscii::from_ascii(b"wat").unwrap(),
                vu: VarLenUnicode::from_str("⨁∀").unwrap(),
            },
        }
    }

    fn big_struct_2() -> BigStruct {
        BigStruct {
            ints: (1, 2, 3, 4),
            uints: (3, 4, 5, 6),
            floats: (-1., 2.),
            data: Data {
                points: VarLenArray::from_slice([].as_ref()),
                fa: FixedAscii::from_ascii(b"").unwrap(),
                fu: FixedUnicode::from_str("").unwrap(),
                va: VarLenAscii::from_ascii(b"").unwrap(),
                vu: VarLenUnicode::from_str("").unwrap(),
            },
        }
    }

    unsafe impl crate::h5type::H5Type for BigStruct {
        fn type_descriptor() -> TypeDescriptor {
            td_big_struct()
        }
    }

    #[test]
    fn test_dyn_value_from() {
        assert_eq!(OwnedDynValue::from(-42i16), OwnedDynValue::new(-42i16));
        let s = big_struct_2();
        assert_eq!(OwnedDynValue::from(s.clone()), OwnedDynValue::new(s.clone()));
    }

    #[test]
    fn test_dyn_value_clone_drop() {
        let val1 = OwnedDynValue::new(big_struct_1());
        let val2 = OwnedDynValue::new(big_struct_2());

        assert_eq!(val1, val1);
        assert_eq!(val1.clone(), val1);
        assert_eq!(val1.clone(), val1.clone().clone());

        assert_eq!(val2, val2);
        assert_eq!(val2.clone(), val2);
        assert_eq!(val2.clone(), val2.clone().clone());

        assert_ne!(val1, val2);
        assert_ne!(val2, val1);
    }

    #[test]
    fn test_dyn_value_display() {
        let val1 = OwnedDynValue::new(big_struct_1());
        let val2 = OwnedDynValue::new(big_struct_2());

        let val1_flat = unindent(
            "\
             {ints: {2: -30, 1: 20, 0: -10, 3: 40}, \
             uints: {2: 50, 1: 40, 0: 30, 3: 60}, \
             floats: {0: -3.14, 1: 2.71}, \
             data: {points: [{coords: [-1.0, 2.0], color: Red, nice: true}, \
             {coords: [0.1, 0.0], color: Green, nice: false}, \
             {coords: [10.0, 0.0], color: Blue, nice: true}], \
             fa: \"12345\", fu: \"\", va: \"wat\", vu: \"⨁∀\"}}",
        );

        let val1_nice = unindent(
            r#"
        {
            ints: {
                2: -30,
                1: 20,
                0: -10,
                3: 40,
            },
            uints: {
                2: 50,
                1: 40,
                0: 30,
                3: 60,
            },
            floats: {
                0: -3.14,
                1: 2.71,
            },
            data: {
                points: [
                    {
                        coords: [
                            -1.0,
                            2.0,
                        ],
                        color: Red,
                        nice: true,
                    },
                    {
                        coords: [
                            0.1,
                            0.0,
                        ],
                        color: Green,
                        nice: false,
                    },
                    {
                        coords: [
                            10.0,
                            0.0,
                        ],
                        color: Blue,
                        nice: true,
                    },
                ],
                fa: "12345",
                fu: "∀",
                va: "wat",
                vu: "⨁∀",
            },
        }"#,
        );

        let val2_flat = unindent(
            "\
             {ints: {2: 3, 1: 2, 0: 1, 3: 4}, \
             uints: {2: 5, 1: 4, 0: 3, 3: 6}, \
             floats: {0: -1.0, 1: 2.0}, \
             data: {points: [], fa: \"\", fu: \"\", va: \"\", vu: \"\"}}",
        );

        let val2_nice = unindent(
            r#"
            {
                ints: {
                    2: 3,
                    1: 2,
                    0: 1,
                    3: 4,
                },
                uints: {
                    2: 5,
                    1: 4,
                    0: 3,
                    3: 6,
                },
                floats: {
                    0: -1.0,
                    1: 2.0,
                },
                data: {
                    points: [],
                    fa: "",
                    fu: "",
                    va: "",
                    vu: "",
                },
            }"#,
        );

        assert_eq!(format!("{}", val1), val1_flat);
        assert_eq!(format!("{:?}", val1), val1_flat);
        assert_eq!(format!("{:#?}", val1.clone()), val1_nice);

        assert_eq!(format!("{}", val2), val2_flat);
        assert_eq!(format!("{:?}", val2), val2_flat);
        assert_eq!(format!("{:#?}", val2.clone()), val2_nice);
    }
}