dicom_parser/stateful/
decode.rs

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
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
//! Module holding a stateful DICOM data decoding abstraction,
//! which also supports text decoding.

use crate::util::n_times;
use dicom_core::dictionary::VirtualVr;
use dicom_core::header::{DataElementHeader, HasLength, Length, SequenceItemHeader, Tag, VR};
use dicom_core::value::deserialize::{
    parse_date_partial, parse_datetime_partial, parse_time_partial,
};
use dicom_core::value::PrimitiveValue;
use dicom_dictionary_std::StandardDataDictionary;
use dicom_encoding::decode::basic::{BasicDecoder, LittleEndianBasicDecoder};
use dicom_encoding::decode::explicit_le::ExplicitVRLittleEndianDecoder;
use dicom_encoding::decode::{BasicDecode, DecodeFrom};
use dicom_encoding::text::{
    validate_da, validate_dt, validate_tm, DefaultCharacterSetCodec, SpecificCharacterSet,
    TextCodec, TextValidationOutcome,
};
use dicom_encoding::transfer_syntax::{DynDecoder, TransferSyntax};
use smallvec::smallvec;
use snafu::{Backtrace, OptionExt, ResultExt, Snafu};
use std::io::Read;
use std::{fmt::Debug, io::Seek, io::SeekFrom};

#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum Error {
    #[snafu(display("Decoding in transfer syntax {} is unsupported", ts))]
    UnsupportedTransferSyntax {
        ts: &'static str,
        backtrace: Backtrace,
    },

    #[snafu(display("Unsupported character set {:?}", charset))]
    UnsupportedCharacterSet {
        charset: SpecificCharacterSet,
        backtrace: Backtrace,
    },

    #[snafu(display("Attempted to read non-primitive value at position {}", position))]
    NonPrimitiveType { position: u64, backtrace: Backtrace },

    #[snafu(display(
        "Undefined value length of element tagged {} at position {}",
        tag,
        position
    ))]
    UndefinedValueLength {
        tag: Tag,
        position: u64,
        backtrace: Backtrace,
    },

    #[snafu(display("Could not decode element header at position {}", position))]
    DecodeElementHeader {
        position: u64,
        #[snafu(backtrace)]
        source: dicom_encoding::decode::Error,
    },

    #[snafu(display("Could not decode element header at position {}", position))]
    DecodeItemHeader {
        position: u64,
        #[snafu(backtrace)]
        source: dicom_encoding::decode::Error,
    },

    #[snafu(display("Could not decode text at position {}", position))]
    DecodeText {
        position: u64,
        #[snafu(backtrace)]
        source: dicom_encoding::text::DecodeTextError,
    },

    #[snafu(display("Could not read value from source at position {}", position))]
    ReadValueData {
        position: u64,
        source: std::io::Error,
        backtrace: Backtrace,
    },

    #[snafu(display(
        "Could not move source cursor from position {} to {}",
        position,
        new_position
    ))]
    SeekReader {
        position: u64,
        new_position: u64,
        source: std::io::Error,
        backtrace: Backtrace,
    },

    #[snafu(display("Failed value deserialization at position {}", position))]
    DeserializeValue {
        position: u64,
        source: dicom_core::value::deserialize::Error,
    },

    #[snafu(display("Invalid integer value at position {}", position))]
    ReadInt {
        position: u64,
        source: std::num::ParseIntError,
    },

    #[snafu(display("Invalid float value at position {}", position))]
    ReadFloat {
        position: u64,
        source: std::num::ParseFloatError,
    },

    #[snafu(display("Invalid Date value element `{}` at position {}", string, position))]
    InvalidDateValue {
        position: u64,
        string: String,
        backtrace: Backtrace,
    },

    #[snafu(display("Invalid Time value element `{}` at position {}", string, position))]
    InvalidTimeValue {
        position: u64,
        string: String,
        backtrace: Backtrace,
    },

    #[snafu(display("Invalid DateTime value element `{}` at position {}", string, position))]
    InvalidDateTimeValue {
        position: u64,
        string: String,
        backtrace: Backtrace,
    },
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

pub trait StatefulDecode {
    type Reader: Read;

    /// Same as `Decode::decode_header` over the bound source.
    fn decode_header(&mut self) -> Result<DataElementHeader>;

    /// Same as `Decode::decode_item_header` over the bound source.
    fn decode_item_header(&mut self) -> Result<SequenceItemHeader>;

    /// Eagerly read the following data in the source as a primitive data
    /// value. When reading values in text form, a conversion to a more
    /// maleable type is attempted. Namely, numbers in text form (IS, DS) are
    /// converted to the corresponding binary number types, and date/time
    /// instances are decoded into binary date/time objects of types defined in
    /// the `chrono` crate. To avoid this conversion, see
    /// `read_value_preserved`.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O problems, or if the header VR describes a
    /// sequence, which in that case this method should not be used.
    fn read_value(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue>;

    /// Eagerly read the following data in the source as a primitive data
    /// value. Unlike `read_value`, this method will preserve the DICOM value's
    /// original format: numbers saved as text, as well as dates and times, are
    /// read as strings.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O problems, or if the header VR describes a
    /// sequence, which in that case this method should not be used.
    fn read_value_preserved(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue>;

    /// Eagerly read the following data in the source as a primitive data
    /// value as bytes, regardless of its value representation.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O problems, or if the header VR describes a
    /// sequence, which in that case this method should not be used.
    fn read_value_bytes(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue>;

    /// Read the following number of bytes into a vector.
    fn read_to_vec(&mut self, length: u32, vec: &mut Vec<u8>) -> Result<()>;

    /// Read the following number of bytes
    /// as a sequence of unsigned 32 bit integers
    /// into a vector.
    fn read_u32_to_vec(&mut self, length: u32, vec: &mut Vec<u32>) -> Result<()>;

    /// Read the following number of bytes into a generic writer.
    fn read_to<W>(&mut self, length: u32, out: W) -> Result<()>
    where
        Self: Sized,
        W: std::io::Write;

    /// Skip the following bytes into a vector,
    /// counting them as if they were read.
    fn skip_bytes(&mut self, length: u32) -> Result<()>;

    /// Reposition the reader so that it starts reading
    /// at the reader's given position.
    ///
    /// The number of bytes read is not expected to be modified.
    fn seek(&mut self, position: u64) -> Result<()>
    where
        Self::Reader: Seek;

    /// Retrieve the known position of the inner reader source.
    /// If the stateful decoder was constructed at the beginning of the reader,
    /// this equals to the number of bytes read so far.
    fn position(&self) -> u64;
}

/// Alias for a dynamically resolved DICOM stateful decoder. Although the data
/// source may be known at compile time, the required decoder may vary
/// according to an object's transfer syntax.
pub type DynStatefulDecoder<S> = StatefulDecoder<DynDecoder<S>, S>;

/// The initial capacity of the `DicomParser` buffer.
const PARSER_BUFFER_CAPACITY: usize = 2048;

/// A stateful abstraction for the full DICOM content reading process.
/// This type encapsulates the necessary codecs in order
/// to be as autonomous as possible in the DICOM content reading
/// process.
/// `S` is the generic parameter type for the original source,
/// `D` is the parameter type that the decoder interprets as,
/// whereas `DB` is the parameter type for the basic decoder.
/// `TC` defines the text codec used underneath.
#[derive(Debug)]
pub struct StatefulDecoder<D, S, BD = BasicDecoder, TC = SpecificCharacterSet> {
    from: S,
    decoder: D,
    basic: BD,
    text: TC,
    buffer: Vec<u8>,
    /// the assumed position of the reader source
    position: u64,
    signed_pixeldata: Option<bool>,
}

impl<S> StatefulDecoder<DynDecoder<S>, S> {
    /// Create a new DICOM parser for the given transfer syntax, character set,
    /// and assumed position of the reader source.
    pub fn new_with(
        from: S,
        ts: &TransferSyntax,
        charset: SpecificCharacterSet,
        position: u64,
    ) -> Result<Self>
    where
        S: Read,
    {
        let basic = ts.basic_decoder();
        let decoder = ts
            .decoder_for::<S>()
            .context(UnsupportedTransferSyntaxSnafu { ts: ts.name() })?;

        Ok(StatefulDecoder::new_with_position(
            from, decoder, basic, charset, position,
        ))
    }

    /// Create a new DICOM parser for the given transfer syntax
    /// and assumed position of the reader source.
    ///
    /// The default character set is assumed
    /// until a _Specific Character Set_ attribute is found.
    pub fn new_with_ts(from: S, ts: &TransferSyntax, position: u64) -> Result<Self>
    where
        S: Read,
    {
        Self::new_with(from, ts, SpecificCharacterSet::default(), position)
    }
}

/// Type alias for the DICOM parser of a file's Meta group.
pub type FileHeaderParser<S> = StatefulDecoder<
    ExplicitVRLittleEndianDecoder,
    S,
    LittleEndianBasicDecoder,
    DefaultCharacterSetCodec,
>;

impl<S> FileHeaderParser<S>
where
    S: Read,
{
    /// Create a new DICOM stateful decoder for reading the file meta header,
    /// which is always in _Explicit VR Little Endian_.
    pub fn file_header_parser(from: S) -> Self {
        Self {
            from,
            basic: LittleEndianBasicDecoder,
            decoder: ExplicitVRLittleEndianDecoder::default(),
            text: DefaultCharacterSetCodec,
            buffer: Vec::with_capacity(PARSER_BUFFER_CAPACITY),
            position: 0,
            signed_pixeldata: None,
        }
    }
}

impl<D, S, BD, TC> StatefulDecoder<D, S, BD, TC>
where
    BD: BasicDecode,
    TC: TextCodec,
{
    /// Create a new DICOM stateful decoder from its parts.
    #[inline]
    pub fn new(from: S, decoder: D, basic: BD, text: TC) -> StatefulDecoder<D, S, BD, TC> {
        Self::new_with_position(from, decoder, basic, text, 0)
    }

    /// Create a new DICOM stateful decoder from its parts,
    /// while assuming a base reading position.
    ///
    /// `position` should be calculated with care.
    /// Decoding or parsing errors may occur
    /// if this position does not match the real position of the reader.
    #[inline]
    pub fn new_with_position(from: S, decoder: D, basic: BD, text: TC, position: u64) -> Self {
        Self {
            from,
            basic,
            decoder,
            text,
            buffer: Vec::with_capacity(PARSER_BUFFER_CAPACITY),
            position,
            signed_pixeldata: None,
        }
    }
}

impl<D, S, BD, TC> StatefulDecoder<D, S, BD, TC>
where
    S: Seek,
    BD: BasicDecode,
    TC: TextCodec,
{
    /// Create a new DICOM stateful decoder from its parts,
    /// while determining the data source's current position via `seek`.
    pub fn new_positioned(
        mut from: S,
        decoder: D,
        basic: BD,
        text: TC,
    ) -> Result<Self, std::io::Error> {
        let position = from.stream_position()?;
        Ok(Self::new_with_position(
            from, decoder, basic, text, position,
        ))
    }
}

impl<D, S, BD, TC> StatefulDecoder<D, S, BD, TC>
where
    D: DecodeFrom<S>,
    BD: BasicDecode,
    S: Read,
    TC: TextCodec,
{
    // ---------------- private methods ---------------------

    fn require_known_length(&self, header: &DataElementHeader) -> Result<usize> {
        header
            .length()
            .get()
            .map(|len| len as usize)
            .context(UndefinedValueLengthSnafu {
                position: self.position,
                tag: header.tag,
            })
    }

    fn read_value_tag(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;

        // tags
        let ntags = len >> 2;
        let parts: Result<_> = n_times(ntags)
            .map(|_| {
                self.basic
                    .decode_tag(&mut self.from)
                    .context(ReadValueDataSnafu {
                        position: self.position,
                    })
            })
            .collect();
        self.position += len as u64;
        Ok(PrimitiveValue::Tags(parts?))
    }

    fn read_value_ob(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        // Note: this function always expects a defined length OB value
        // (pixel sequence detection needs to be done by the caller)
        let len = self.require_known_length(header)?;

        // sequence of 8-bit integers (or arbitrary byte data)
        let mut buf = smallvec![0u8; len];
        self.from.read_exact(&mut buf).context(ReadValueDataSnafu {
            position: self.position,
        })?;
        self.position += len as u64;
        Ok(PrimitiveValue::U8(buf))
    }

    fn read_value_strs(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of strings
        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;

        let parts: Result<_> = match header.vr() {
            VR::AE | VR::CS | VR::AS => self
                .buffer
                .split(|v| *v == b'\\')
                .map(|slice| {
                    DefaultCharacterSetCodec
                        .decode(slice)
                        .context(DecodeTextSnafu {
                            position: self.position,
                        })
                })
                .collect(),
            _ => self
                .buffer
                .split(|v| *v == b'\\')
                .map(|slice| {
                    self.text.decode(slice).context(DecodeTextSnafu {
                        position: self.position,
                    })
                })
                .collect(),
        };

        self.position += len as u64;
        Ok(PrimitiveValue::Strs(parts?))
    }

    fn read_value_str(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;

        // a single string
        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::Str(
            self.text
                .decode(&self.buffer[..])
                .context(DecodeTextSnafu {
                    position: self.position,
                })?,
        ))
    }

    fn read_value_ss(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        // sequence of 16-bit signed integers
        let len = self.require_known_length(header)?;

        let n = len >> 1;
        let mut vec = smallvec![0; n];
        self.basic
            .decode_ss_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;

        self.position += len as u64;
        Ok(PrimitiveValue::I16(vec))
    }

    fn read_value_fl(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 32-bit floats
        let n = len >> 2;
        let mut vec = smallvec![0.; n];
        self.basic
            .decode_fl_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::F32(vec))
    }

    fn read_value_da(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of dates

        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        let buf = trim_trail_empty_bytes(&self.buffer);
        if buf.is_empty() {
            return Ok(PrimitiveValue::Empty);
        }

        if validate_da(buf) != TextValidationOutcome::Ok {
            let lossy_str = DefaultCharacterSetCodec
                .decode(buf)
                .unwrap_or_else(|_| "[byte stream]".to_string());
            return InvalidDateValueSnafu {
                position: self.position,
                string: lossy_str,
            }
            .fail();
        }
        let vec: Result<_> = buf
            .split(|b| *b == b'\\')
            .map(|part| {
                parse_date_partial(part)
                    .map(|t| t.0)
                    .context(DeserializeValueSnafu {
                        position: self.position,
                    })
            })
            .collect();
        self.position += len as u64;
        Ok(PrimitiveValue::Date(vec?))
    }

    fn read_value_ds(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of doubles in text form

        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        let buf = trim_trail_empty_bytes(&self.buffer);
        if buf.is_empty() {
            return Ok(PrimitiveValue::Empty);
        }

        let parts: Result<_> = buf
            .split(|b| *b == b'\\')
            .map(|slice| {
                let codec = DefaultCharacterSetCodec;
                let txt = codec.decode(slice).context(DecodeTextSnafu {
                    position: self.position,
                })?;
                let txt = txt.trim();
                txt.parse::<f64>().context(ReadFloatSnafu {
                    position: self.position,
                })
            })
            .collect();
        self.position += len as u64;
        Ok(PrimitiveValue::F64(parts?))
    }

    fn read_value_dt(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of datetimes

        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        let buf = trim_trail_empty_bytes(&self.buffer);
        if buf.is_empty() {
            return Ok(PrimitiveValue::Empty);
        }

        if validate_dt(buf) != TextValidationOutcome::Ok {
            let lossy_str = DefaultCharacterSetCodec
                .decode(buf)
                .unwrap_or_else(|_| "[byte stream]".to_string());
            return InvalidDateTimeValueSnafu {
                position: self.position,
                string: lossy_str,
            }
            .fail();
        }
        let vec: Result<_> = buf
            .split(|b| *b == b'\\')
            .map(|part| {
                parse_datetime_partial(part).context(DeserializeValueSnafu {
                    position: self.position,
                })
            })
            .collect();

        self.position += len as u64;
        Ok(PrimitiveValue::DateTime(vec?))
    }

    fn read_value_is(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of signed integers in text form
        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        let buf = trim_trail_empty_bytes(&self.buffer);
        if buf.is_empty() {
            return Ok(PrimitiveValue::Empty);
        }

        let parts: Result<_> = buf
            .split(|v| *v == b'\\')
            .map(|slice| {
                let codec = DefaultCharacterSetCodec;
                let txt = codec.decode(slice).context(DecodeTextSnafu {
                    position: self.position,
                })?;
                let txt = txt.trim();
                txt.parse::<i32>().context(ReadIntSnafu {
                    position: self.position,
                })
            })
            .collect();
        self.position += len as u64;
        Ok(PrimitiveValue::I32(parts?))
    }

    fn read_value_tm(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of time instances

        self.buffer.resize_with(len, Default::default);
        self.from
            .read_exact(&mut self.buffer)
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        let buf = trim_trail_empty_bytes(&self.buffer);
        if buf.is_empty() {
            return Ok(PrimitiveValue::Empty);
        }

        if validate_tm(buf) != TextValidationOutcome::Ok {
            let lossy_str = DefaultCharacterSetCodec
                .decode(buf)
                .unwrap_or_else(|_| "[byte stream]".to_string());
            return InvalidTimeValueSnafu {
                position: self.position,
                string: lossy_str,
            }
            .fail();
        }
        let vec: std::result::Result<_, _> = buf
            .split(|b| *b == b'\\')
            .map(|part| {
                parse_time_partial(part)
                    .map(|t| t.0)
                    .context(DeserializeValueSnafu {
                        position: self.position,
                    })
            })
            .collect();
        self.position += len as u64;
        Ok(PrimitiveValue::Time(vec?))
    }

    fn read_value_od(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 64-bit floats
        let n = len >> 3;
        let mut vec = smallvec![0.; n];
        self.basic
            .decode_fd_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::F64(vec))
    }

    fn read_value_ul(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 32-bit unsigned integers

        let n = len >> 2;
        let mut vec = smallvec![0u32; n];
        self.basic
            .decode_ul_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::U32(vec))
    }

    fn read_u32(&mut self, n: usize, vec: &mut Vec<u32>) -> Result<()> {
        let base = vec.len();
        vec.resize(base + n, 0);

        self.basic
            .decode_ul_into(&mut self.from, &mut vec[base..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += n as u64 * 4;
        Ok(())
    }

    fn read_value_us(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 16-bit unsigned integers

        let n = len >> 1;
        let mut vec = smallvec![0; n];
        self.basic
            .decode_us_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;

        self.position += len as u64;

        if header.tag == Tag(0x0028, 0x0103) {
            //Pixel Representation is not 0, so 2s complement (signed)
            self.signed_pixeldata = vec.first().map(|rep| *rep != 0);
        }

        Ok(PrimitiveValue::U16(vec))
    }

    fn read_value_uv(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 64-bit unsigned integers

        let n = len >> 3;
        let mut vec = smallvec![0; n];
        self.basic
            .decode_uv_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::U64(vec))
    }

    fn read_value_sl(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 32-bit signed integers

        let n = len >> 2;
        let mut vec = smallvec![0; n];
        self.basic
            .decode_sl_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::I32(vec))
    }

    fn read_value_sv(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let len = self.require_known_length(header)?;
        // sequence of 64-bit signed integers

        let n = len >> 3;
        let mut vec = smallvec![0; n];
        self.basic
            .decode_sv_into(&mut self.from, &mut vec[..])
            .context(ReadValueDataSnafu {
                position: self.position,
            })?;
        self.position += len as u64;
        Ok(PrimitiveValue::I64(vec))
    }
}

impl<S, D, BD> StatefulDecoder<D, S, BD>
where
    D: DecodeFrom<S>,
    BD: BasicDecode,
    S: Read,
{
    fn set_character_set(&mut self, charset: SpecificCharacterSet) -> Result<()> {
        self.text = charset;
        Ok(())
    }

    /// Read a sequence of Code String values. Similar to `read_value_strs`, but also
    /// triggers a character set change when it finds the _SpecificCharacterSet_
    /// attribute.
    fn read_value_cs(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        let out = self.read_value_strs(header)?;

        let parts = match &out {
            PrimitiveValue::Strs(parts) => parts,
            _ => unreachable!(),
        };

        // if it's a Specific Character Set, update the decoder immediately.
        if header.tag == Tag(0x0008, 0x0005) {
            // Edge case handling strategies for
            // unsupported specific character sets should probably be considered
            // in the future. See #40 for discussion.
            if let Some(charset) = parts.first().map(|x| x.as_ref()).and_then(|name| {
                SpecificCharacterSet::from_code(name).or_else(|| {
                    tracing::warn!("Unsupported character set `{}`, ignoring", name);
                    None
                })
            }) {
                self.set_character_set(charset)?;
            }
        }

        Ok(out)
    }
}

impl<D> StatefulDecode for &'_ mut D
where
    D: StatefulDecode,
{
    type Reader = D::Reader;

    fn decode_header(&mut self) -> Result<DataElementHeader> {
        (**self).decode_header()
    }

    fn decode_item_header(&mut self) -> Result<SequenceItemHeader> {
        (**self).decode_item_header()
    }

    fn read_value(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        (**self).read_value(header)
    }

    fn read_value_preserved(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        (**self).read_value_preserved(header)
    }

    fn read_value_bytes(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        (**self).read_value_bytes(header)
    }

    fn read_to_vec(&mut self, length: u32, vec: &mut Vec<u8>) -> Result<()> {
        (**self).read_to_vec(length, vec)
    }

    fn read_u32_to_vec(&mut self, length: u32, vec: &mut Vec<u32>) -> Result<()> {
        (**self).read_u32_to_vec(length, vec)
    }

    fn read_to<W>(&mut self, length: u32, out: W) -> Result<()>
    where
        Self: Sized,
        W: std::io::Write,
    {
        (**self).read_to(length, out)
    }

    fn skip_bytes(&mut self, length: u32) -> Result<()> {
        (**self).skip_bytes(length)
    }

    fn position(&self) -> u64 {
        (**self).position()
    }

    fn seek(&mut self, position: u64) -> Result<()>
    where
        Self::Reader: Seek,
    {
        (**self).seek(position)
    }
}

impl<D, S, BD> StatefulDecode for StatefulDecoder<D, S, BD>
where
    D: DecodeFrom<S>,
    BD: BasicDecode,
    S: Read,
{
    type Reader = S;

    fn decode_header(&mut self) -> Result<DataElementHeader> {
        let mut header = self
            .decoder
            .decode_header(&mut self.from)
            .context(DecodeElementHeaderSnafu {
                position: self.position,
            })
            .map(|(header, bytes_read)| {
                self.position += bytes_read as u64;
                header
            })
            .map_err(From::from)?;

        //If we are decoding the PixelPadding element, make sure the VR is the same as the pixel
        //representation (US by default, SS for signed data).
        if let Some(vr) = self.determine_vr_based_on_pixel_representation(header.tag) {
            header.vr = vr;
        }

        Ok(header)
    }

    fn decode_item_header(&mut self) -> Result<SequenceItemHeader> {
        self.decoder
            .decode_item_header(&mut self.from)
            .context(DecodeItemHeaderSnafu {
                position: self.position,
            })
            .map(|header| {
                self.position += 8;
                header
            })
            .map_err(From::from)
    }

    fn read_value(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        if header.length() == Length(0) {
            return Ok(PrimitiveValue::Empty);
        }

        match header.vr() {
            VR::SQ => {
                // sequence objects should not head over here, they are
                // handled at a higher level
                NonPrimitiveTypeSnafu {
                    position: self.position,
                }
                .fail()
            }
            VR::AT => self.read_value_tag(header),
            VR::AE | VR::AS | VR::PN | VR::SH | VR::LO | VR::UC | VR::UI => {
                self.read_value_strs(header)
            }
            VR::CS => self.read_value_cs(header),
            VR::UT | VR::ST | VR::UR | VR::LT => self.read_value_str(header),
            VR::UN | VR::OB => self.read_value_ob(header),
            VR::US | VR::OW => self.read_value_us(header),
            VR::SS => self.read_value_ss(header),
            VR::DA => self.read_value_da(header),
            VR::DT => self.read_value_dt(header),
            VR::TM => self.read_value_tm(header),
            VR::DS => self.read_value_ds(header),
            VR::FD | VR::OD => self.read_value_od(header),
            VR::FL | VR::OF => self.read_value_fl(header),
            VR::IS => self.read_value_is(header),
            VR::SL => self.read_value_sl(header),
            VR::SV => self.read_value_sv(header),
            VR::OL | VR::UL => self.read_value_ul(header),
            VR::OV | VR::UV => self.read_value_uv(header),
        }
    }

    fn read_value_preserved(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        if header.length() == Length(0) {
            return Ok(PrimitiveValue::Empty);
        }

        match header.vr() {
            VR::SQ => {
                // sequence objects... should not work
                NonPrimitiveTypeSnafu {
                    position: self.position,
                }
                .fail()
            }
            VR::AT => self.read_value_tag(header),
            VR::AE
            | VR::AS
            | VR::PN
            | VR::SH
            | VR::LO
            | VR::UC
            | VR::UI
            | VR::IS
            | VR::DS
            | VR::DA
            | VR::TM
            | VR::DT => self.read_value_strs(header),
            VR::CS => self.read_value_cs(header),
            VR::UT | VR::ST | VR::UR | VR::LT => self.read_value_str(header),
            VR::UN | VR::OB => self.read_value_ob(header),
            VR::US | VR::OW => self.read_value_us(header),
            VR::SS => self.read_value_ss(header),
            VR::FD | VR::OD => self.read_value_od(header),
            VR::FL | VR::OF => self.read_value_fl(header),
            VR::SL => self.read_value_sl(header),
            VR::OL | VR::UL => self.read_value_ul(header),
            VR::SV => self.read_value_sv(header),
            VR::OV | VR::UV => self.read_value_uv(header),
        }
    }

    fn read_value_bytes(&mut self, header: &DataElementHeader) -> Result<PrimitiveValue> {
        if header.length() == Length(0) {
            return Ok(PrimitiveValue::Empty);
        }

        match header.vr() {
            VR::SQ => {
                // sequence objects... should not work
                NonPrimitiveTypeSnafu {
                    position: self.position,
                }
                .fail()
            }
            _ => self.read_value_ob(header),
        }
    }

    fn position(&self) -> u64 {
        self.position
    }

    fn read_to_vec(&mut self, length: u32, vec: &mut Vec<u8>) -> Result<()> {
        self.read_to(length, vec)
    }

    fn read_u32_to_vec(&mut self, length: u32, vec: &mut Vec<u32>) -> Result<()> {
        self.read_u32((length >> 2) as usize, vec)
    }

    fn read_to<W>(&mut self, length: u32, mut out: W) -> Result<()>
    where
        Self: Sized,
        W: std::io::Write,
    {
        let length = u64::from(length);
        std::io::copy(&mut self.from.by_ref().take(length), &mut out).context(
            ReadValueDataSnafu {
                position: self.position,
            },
        )?;
        self.position += length;
        Ok(())
    }

    fn skip_bytes(&mut self, length: u32) -> Result<()> {
        std::io::copy(
            &mut self.from.by_ref().take(u64::from(length)),
            &mut std::io::sink(),
        )
        .context(ReadValueDataSnafu {
            position: self.position,
        })?;

        self.position += u64::from(length);
        Ok(())
    }

    fn seek(&mut self, position: u64) -> Result<()>
    where
        Self::Reader: Seek,
    {
        self.from
            .seek(SeekFrom::Start(position))
            .context(SeekReaderSnafu {
                position: self.position,
                new_position: position,
            })
            .map(|_| ())
    }
}

impl<D, S, BD> StatefulDecoder<D, S, BD>
where
    D: DecodeFrom<S>,
    BD: BasicDecode,
    S: Read,
{
    /// The pixel representation affects the VR for several elements.
    /// Returns `Some(VR::SS)` if the vr needs to be modified to SS. Returns `None`
    /// if this element is not affected _or_ if we have Unsigned Pixel Representation.
    fn determine_vr_based_on_pixel_representation(&self, tag: Tag) -> Option<VR> {
        use dicom_core::dictionary::DataDictionary;

        if self.signed_pixeldata == Some(true)
            && StandardDataDictionary.by_tag(tag).map(|e| e.vr) == Some(VirtualVr::Xs)
        {
            Some(VR::SS)
        } else {
            None
        }
    }
}

/// Remove trailing spaces and null characters.
fn trim_trail_empty_bytes(mut x: &[u8]) -> &[u8] {
    while x.last() == Some(&b' ') || x.last() == Some(&b'\0') {
        x = &x[..x.len() - 1];
    }
    x
}

#[cfg(test)]
mod tests {
    use super::{StatefulDecode, StatefulDecoder};
    use dicom_core::header::{DataElementHeader, HasLength, Header, Length, SequenceItemHeader};
    use dicom_core::{Tag, VR};
    use dicom_encoding::decode::basic::LittleEndianBasicDecoder;
    use dicom_encoding::decode::{
        explicit_le::ExplicitVRLittleEndianDecoder, implicit_le::ImplicitVRLittleEndianDecoder,
    };
    use dicom_encoding::text::{SpecificCharacterSet, TextCodec};
    use std::io::{Cursor, Seek, SeekFrom};

    // manually crafting some DICOM data elements
    //  Tag: (0002,0002) Media Storage SOP Class UID
    //  VR: UI
    //  Length: 26
    //  Value: "1.2.840.10008.5.1.4.1.1.1\0"
    // --
    //  Tag: (0002,0010) Transfer Syntax UID
    //  VR: UI
    //  Length: 20
    //  Value: "1.2.840.10008.1.2.1\0" == ExplicitVRLittleEndian
    // --
    const RAW: &'static [u8; 62] = &[
        0x02, 0x00, 0x02, 0x00, 0x55, 0x49, 0x1a, 0x00, 0x31, 0x2e, 0x32, 0x2e, 0x38, 0x34, 0x30,
        0x2e, 0x31, 0x30, 0x30, 0x30, 0x38, 0x2e, 0x35, 0x2e, 0x31, 0x2e, 0x34, 0x2e, 0x31, 0x2e,
        0x31, 0x2e, 0x31, 0x00, 0x02, 0x00, 0x10, 0x00, 0x55, 0x49, 0x14, 0x00, 0x31, 0x2e, 0x32,
        0x2e, 0x38, 0x34, 0x30, 0x2e, 0x31, 0x30, 0x30, 0x30, 0x38, 0x2e, 0x31, 0x2e, 0x32, 0x2e,
        0x31, 0x00,
    ];

    fn is_stateful_decoder<T>(_: &T)
    where
        T: StatefulDecode,
    {
    }

    #[test]
    fn decode_data_elements() {
        let mut cursor = Cursor::new(&RAW[..]);
        let mut decoder = StatefulDecoder::new(
            &mut cursor,
            ExplicitVRLittleEndianDecoder::default(),
            LittleEndianBasicDecoder,
            SpecificCharacterSet::default(),
        );

        is_stateful_decoder(&decoder);

        {
            // read first element
            let elem = decoder.decode_header().expect("should find an element");
            assert_eq!(elem.tag(), Tag(2, 2));
            assert_eq!(elem.vr(), VR::UI);
            assert_eq!(elem.length(), Length(26));

            assert_eq!(decoder.position(), 8);

            // read value
            let value = decoder
                .read_value(&elem)
                .expect("value after element header");
            assert_eq!(value.multiplicity(), 1);
            assert_eq!(value.string(), Ok("1.2.840.10008.5.1.4.1.1.1\0"));

            assert_eq!(decoder.position(), 8 + 26);
        }
        {
            // read second element
            let elem = decoder.decode_header().expect("should find an element");
            assert_eq!(elem.tag(), Tag(2, 16));
            assert_eq!(elem.vr(), VR::UI);
            assert_eq!(elem.length(), Length(20));

            assert_eq!(decoder.position(), 8 + 26 + 8);

            // read value
            let value = decoder
                .read_value(&elem)
                .expect("value after element header");
            assert_eq!(value.multiplicity(), 1);
            assert_eq!(value.string(), Ok("1.2.840.10008.1.2.1\0"));

            assert_eq!(decoder.position(), 8 + 26 + 8 + 20);

            // rolling back to read the last value again
            decoder.seek(8 + 26 + 8).unwrap();

            // read value
            let value = decoder
                .read_value(&elem)
                .expect("value after element header");
            assert_eq!(value.multiplicity(), 1);
            assert_eq!(value.string(), Ok("1.2.840.10008.1.2.1\0"));

            assert_eq!(decoder.position(), 8 + 26 + 8 + 20 + 20);
        }
    }

    /// Test that the stateful decoder updates
    /// the active character set after reaching a Specific Character Set element
    /// with a supported text encoding.
    #[test]
    fn update_character_set() {
        const RAW: &'static [u8; 18] = &[
            // Tag: (0008,0005) Specific Character Set
            0x08, 0x00, 0x05, 0x00, // VR: CS
            b'C', b'S', // Length: 10
            0x0a, 0x00, // Value: "ISO_IR 192"
            b'I', b'S', b'O', b'_', b'I', b'R', b' ', b'1', b'9', b'2',
        ];

        let mut cursor = &RAW[..];
        let mut decoder = StatefulDecoder::new(
            &mut cursor,
            ExplicitVRLittleEndianDecoder::default(),
            LittleEndianBasicDecoder,
            SpecificCharacterSet::default(),
        );

        is_stateful_decoder(&decoder);

        let header = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(
            header,
            DataElementHeader {
                tag: Tag(0x0008, 0x0005),
                vr: VR::CS,
                len: Length(10),
            }
        );

        let value = decoder
            .read_value_preserved(&header)
            .expect("should read a value");

        assert_eq!(value.string(), Ok("ISO_IR 192"));
        assert_eq!(decoder.text.name(), "ISO_IR 192",);
    }

    #[test]
    fn decode_data_elements_with_position() {
        let data = {
            let mut x = vec![0; 128];
            x.extend(RAW);
            x
        };

        // have cursor start 128 bytes ahead
        let mut cursor = Cursor::new(&data[..]);
        cursor.seek(SeekFrom::Start(128)).unwrap();

        let mut decoder = StatefulDecoder::new_with_position(
            &mut cursor,
            ExplicitVRLittleEndianDecoder::default(),
            LittleEndianBasicDecoder,
            SpecificCharacterSet::default(),
            128,
        );

        is_stateful_decoder(&decoder);

        {
            // read first element
            let elem = decoder.decode_header().expect("should find an element");
            assert_eq!(elem.tag(), Tag(2, 2));
            assert_eq!(elem.vr(), VR::UI);
            assert_eq!(elem.length(), Length(26));

            assert_eq!(decoder.position(), 128 + 8);

            // read value
            let value = decoder
                .read_value(&elem)
                .expect("value after element header");
            assert_eq!(value.multiplicity(), 1);
            assert_eq!(value.string(), Ok("1.2.840.10008.5.1.4.1.1.1\0"));

            assert_eq!(decoder.position(), 128 + 8 + 26);
        }
        {
            // read second element
            let elem = decoder.decode_header().expect("should find an element");
            assert_eq!(elem.tag(), Tag(2, 16));
            assert_eq!(elem.vr(), VR::UI);
            assert_eq!(elem.length(), Length(20));

            assert_eq!(decoder.position(), 128 + 8 + 26 + 8);

            // read value
            let value = decoder
                .read_value(&elem)
                .expect("value after element header");
            assert_eq!(value.multiplicity(), 1);
            assert_eq!(value.string(), Ok("1.2.840.10008.1.2.1\0"));

            assert_eq!(decoder.position(), 128 + 8 + 26 + 8 + 20);

            // rolling back to read the last value again
            decoder.seek(128 + 8 + 26 + 8).unwrap();

            // read value
            let value = decoder
                .read_value(&elem)
                .expect("value after element header");
            assert_eq!(value.multiplicity(), 1);
            assert_eq!(value.string(), Ok("1.2.840.10008.1.2.1\0"));

            assert_eq!(decoder.position(), 128 + 8 + 26 + 8 + 20 + 20);
        }
    }

    #[test]
    fn decode_nested_datasets() {
        const RAW: &'static [u8; 138] = &[
            // 0: (2001, 9000) private sequence
            0x01, 0x20, 0x00, 0x90, //
            // length: undefined
            0xFF, 0xFF, 0xFF, 0xFF, //
            // 8: Item start
            0xFE, 0xFF, 0x00, 0xE0, //
            // Item length explicit (114)
            0x72, 0x00, 0x00, 0x00, //
            // 16: (0008,1115) ReferencedSeriesSequence
            0x08, 0x00, 0x15, 0x11, //
            // length: undefined
            0xFF, 0xFF, 0xFF, 0xFF, //
            // 24: Item start
            0xFE, 0xFF, 0x00, 0xE0, //
            // Item length undefined
            0xFF, 0xFF, 0xFF, 0xFF, //
            // 32: (0008,1140) ReferencedImageSequence
            0x08, 0x00, 0x40, 0x11, //
            // length: undefined
            0xFF, 0xFF, 0xFF, 0xFF, //
            // 40: Item start
            0xFE, 0xFF, 0x00, 0xE0, //
            // Item length undefined
            0xFF, 0xFF, 0xFF, 0xFF, //
            // 48: (0008,1150) ReferencedSOPClassUID
            0x08, 0x00, 0x50, 0x11, //
            // length: 26
            0x1a, 0x00, 0x00, 0x00, //
            // Value: "1.2.840.10008.5.1.4.1.1.7\0" (SecondaryCaptureImageStorage)
            b'1', b'.', b'2', b'.', b'8', b'4', b'0', b'.', b'1', b'0', b'0', b'0', b'8', b'.',
            b'5', b'.', b'1', b'.', b'4', b'.', b'1', b'.', b'1', b'.', b'7', b'\0',
            // 82: Item End (ReferencedImageSequence)
            0xFE, 0xFF, 0x0D, 0xE0, //
            0x00, 0x00, 0x00, 0x00, //
            // 90: Sequence End (ReferencedImageSequence)
            0xFE, 0xFF, 0xDD, 0xE0, //
            0x00, 0x00, 0x00, 0x00, //
            // 98: Item End (ReferencedSeriesSequence)
            0xFE, 0xFF, 0x0D, 0xE0, //
            0x00, 0x00, 0x00, 0x00, //
            // 106: Sequence End (ReferencedSeriesSequence)
            0xFE, 0xFF, 0xDD, 0xE0, //
            0x00, 0x00, 0x00, 0x00, //
            // 114: (2050,0020) PresentationLUTShape (CS)
            0x50, 0x20, 0x20, 0x00, //
            // length: 8
            0x08, 0x00, 0x00, 0x00, //
            b'I', b'D', b'E', b'N', b'T', b'I', b'T', b'Y', // 130: Sequence end
            0xFE, 0xFF, 0xDD, 0xE0, //
            0x00, 0x00, 0x00, 0x00, //
        ];

        let mut cursor = &RAW[..];
        let mut decoder = StatefulDecoder::new(
            &mut cursor,
            ImplicitVRLittleEndianDecoder::default(),
            LittleEndianBasicDecoder,
            SpecificCharacterSet::default(),
        );

        is_stateful_decoder(&decoder);

        let header = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(header.tag(), Tag(0x2001, 0x9000));
        assert_eq!(header.vr(), VR::UN);
        assert!(header.length().is_undefined());

        assert_eq!(decoder.position(), 8);

        let item_header = decoder
            .decode_item_header()
            .expect("should find an item header");
        assert_eq!(item_header, SequenceItemHeader::Item { len: Length(114) });

        assert_eq!(decoder.position(), 16);

        // enter ReferencedSeriesSequence
        let header = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(header.tag(), Tag(0x0008, 0x1115));
        assert_eq!(header.vr(), VR::SQ);
        assert!(header.length().is_undefined());

        assert_eq!(decoder.position(), 24);

        let item_header = decoder
            .decode_item_header()
            .expect("should find an item header (ReferencedSeriesSequence)");
        assert!(matches!(
            item_header,
            SequenceItemHeader::Item {
                len,
            } if len.is_undefined()
        ));

        assert_eq!(decoder.position(), 32);

        // enter ReferencedImageSequence
        let header = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(header.tag(), Tag(0x0008, 0x1140));
        assert_eq!(header.vr(), VR::SQ);
        assert!(header.length().is_undefined());

        assert_eq!(decoder.position(), 40);

        let item_header = decoder
            .decode_item_header()
            .expect("should find an item header (ReferencedImageSequence)");
        assert!(matches!(
            item_header,
            SequenceItemHeader::Item {
                len,
            } if len.is_undefined()
        ));

        assert_eq!(decoder.position(), 48);

        // read ReferencedSOPClassUID

        let header = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(header.tag(), Tag(0x0008, 0x1150));
        assert_eq!(header.vr(), VR::UI);
        assert_eq!(header.length(), Length(26));

        assert_eq!(decoder.position(), 56);

        let value = decoder
            .read_value(&header)
            .expect("should find a value after element header");
        assert_eq!(value.to_str(), "1.2.840.10008.5.1.4.1.1.7");

        assert_eq!(decoder.position(), 82);

        // exit ReferencedImageSequence

        let item_header = decoder
            .decode_item_header()
            .expect("should find item delimiter");
        assert_eq!(item_header, SequenceItemHeader::ItemDelimiter);

        assert_eq!(decoder.position(), 90);

        let item_header = decoder
            .decode_item_header()
            .expect("should find sequence delimiter");
        assert_eq!(item_header, SequenceItemHeader::SequenceDelimiter);

        assert_eq!(decoder.position(), 98);

        // exit ReferencedSeriesSequence

        let item_header = decoder
            .decode_item_header()
            .expect("should find item delimiter");
        assert_eq!(item_header, SequenceItemHeader::ItemDelimiter);

        assert_eq!(decoder.position(), 106);

        let item_header = decoder
            .decode_item_header()
            .expect("should find sequence delimiter");
        assert_eq!(item_header, SequenceItemHeader::SequenceDelimiter);

        assert_eq!(decoder.position(), 114);

        // read PresentationLUTShape

        let header = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(header.tag(), Tag(0x2050, 0x0020));
        assert_eq!(header.vr(), VR::CS);
        assert_eq!(header.length(), Length(8));

        assert_eq!(decoder.position(), 122);

        let value = decoder
            .read_value(&header)
            .expect("value after element header");
        assert_eq!(value.multiplicity(), 1);
        assert_eq!(value.to_str(), "IDENTITY");

        assert_eq!(decoder.position(), 130);

        // exit private sequence
        // (no item delimiter because length is explicit)

        let item_header = decoder
            .decode_item_header()
            .expect("should find an item header");
        assert_eq!(item_header, SequenceItemHeader::SequenceDelimiter);

        assert_eq!(decoder.position(), 138);
    }

    #[test]
    fn decode_and_use_pixel_representation() {
        const RAW: &'static [u8; 20] = &[
            0x28, 0x00, 0x03, 0x01, // Tag: (0023,0103) PixelRepresentation
            0x02, 0x00, 0x00, 0x00, // Length: 2
            0x01, 0x00, // Value: "1",
            0x28, 0x00, 0x20, 0x01, // Tag: (0023,0120) PixelPadding
            0x02, 0x00, 0x00, 0x00, // Length: 2
            0x01, 0x00, // Value: "1"
        ];

        let mut cursor = &RAW[..];
        let mut decoder = StatefulDecoder::new(
            &mut cursor,
            ImplicitVRLittleEndianDecoder::default(),
            LittleEndianBasicDecoder,
            SpecificCharacterSet::default(),
        );

        is_stateful_decoder(&decoder);

        let header_1 = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(
            header_1,
            DataElementHeader {
                tag: Tag(0x0028, 0x0103),
                vr: VR::US,
                len: Length(2),
            }
        );

        decoder
            .read_value(&header_1)
            .expect("Can read Pixel Representation");

        let header_2 = decoder
            .decode_header()
            .expect("should find an element header");
        assert_eq!(
            header_2,
            DataElementHeader {
                tag: Tag(0x0028, 0x0120),
                vr: VR::SS,
                len: Length(2),
            }
        );
    }
}