Skip to main content

dcmnorm_encoding/decode/
adaptive_le.rs

1//! Adaptive VR Little Endian syntax transfer implementation.
2//!
3//! This decoder handles non-conformant DICOM files that declare
4//! Explicit VR Little Endian in their transfer syntax but actually
5//! encode the dataset in Implicit VR. On the first non-meta,
6//! non-delimiter element, it probes the bytes after the tag to
7//! determine whether they form a valid VR code. If they do,
8//! it locks to explicit VR for the rest of the file; if not,
9//! it switches to implicit VR.
10
11use crate::decode::basic::LittleEndianBasicDecoder;
12use crate::decode::{
13    BadSequenceHeaderSnafu, BasicDecode, Decode, DecodeFrom, ReadHeaderTagSnafu,
14    ReadItemHeaderSnafu, ReadItemLengthSnafu, ReadLengthSnafu, ReadReservedSnafu, ReadTagSnafu,
15    ReadVrSnafu, Result,
16};
17use byteordered::byteorder::{ByteOrder, LittleEndian};
18use dcmnorm_core::dictionary::{DataDictionary, DataDictionaryEntry, VirtualVr};
19use dcmnorm_core::header::{DataElementHeader, Length, SequenceItemHeader};
20use dcmnorm_core::{Tag, VR};
21use dcmnorm_dictionary::StandardDataDictionary;
22use snafu::ResultExt;
23use std::cell::Cell;
24use std::fmt;
25use std::io::Read;
26
27/// An AdaptiveVRLittleEndianDecoder which uses the standard data dictionary.
28pub type StandardAdaptiveVRLittleEndianDecoder =
29    AdaptiveVRLittleEndianDecoder<StandardDataDictionary>;
30
31#[derive(Debug, Copy, Clone, PartialEq, Eq)]
32enum VrState {
33    /// Not yet determined — will probe on next non-delimiter element.
34    Unknown,
35    /// Locked to explicit VR.
36    Explicit,
37    /// Locked to implicit VR.
38    Implicit,
39}
40
41/// A data element decoder for Little Endian data that auto-detects
42/// whether the dataset uses explicit or implicit VR encoding.
43///
44/// This is intended for non-conformant files that declare Explicit VR LE
45/// in the transfer syntax but actually contain Implicit VR data.
46/// On the first non-meta element, the decoder probes the two bytes
47/// following the tag: if they form a recognized VR code, it proceeds
48/// as explicit VR; otherwise it falls back to implicit VR.
49pub struct AdaptiveVRLittleEndianDecoder<D> {
50    dict: D,
51    basic: LittleEndianBasicDecoder,
52    state: Cell<VrState>,
53}
54
55impl<D> fmt::Debug for AdaptiveVRLittleEndianDecoder<D> {
56    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57        f.debug_struct("AdaptiveVRLittleEndianDecoder")
58            .field("dict", &"«omitted»")
59            .field("basic", &self.basic)
60            .field("state", &self.state)
61            .finish()
62    }
63}
64
65impl AdaptiveVRLittleEndianDecoder<StandardDataDictionary> {
66    /// Retrieve this decoder using the standard data dictionary.
67    pub fn with_std_dict() -> Self {
68        AdaptiveVRLittleEndianDecoder {
69            dict: StandardDataDictionary,
70            basic: LittleEndianBasicDecoder,
71            state: Cell::new(VrState::Unknown),
72        }
73    }
74
75    /// Retrieve this decoder using the standard data dictionary.
76    pub fn new() -> Self {
77        Self::with_std_dict()
78    }
79}
80
81impl Default for AdaptiveVRLittleEndianDecoder<StandardDataDictionary> {
82    fn default() -> Self {
83        Self::with_std_dict()
84    }
85}
86
87impl<D> AdaptiveVRLittleEndianDecoder<D>
88where
89    D: DataDictionary,
90{
91    /// Retrieve this decoder using a custom data dictionary.
92    pub fn with_dict(dictionary: D) -> Self {
93        AdaptiveVRLittleEndianDecoder {
94            dict: dictionary,
95            basic: LittleEndianBasicDecoder,
96            state: Cell::new(VrState::Unknown),
97        }
98    }
99
100    /// Resolve VR for implicit mode using the data dictionary.
101    fn resolve_vr(&self, tag: Tag) -> VR {
102        if tag == Tag(0x7FE0, 0x0010) || (tag.0 >> 8 == 0x60 && tag.1 == 0x3000) {
103            VR::OW
104        } else {
105            self.dict
106                .by_tag(tag)
107                .map(|entry| entry.vr().relaxed())
108                .unwrap_or(VR::UN)
109        }
110    }
111}
112
113/// Check whether a probed VR is compatible with a dictionary VirtualVr.
114/// VirtualVr variants like Xs and Ox allow multiple concrete VRs.
115fn vr_compatible_with_virtual(probed: VR, dict_vr: VirtualVr) -> bool {
116    match dict_vr {
117        VirtualVr::Exact(vr) => probed == vr,
118        VirtualVr::Xs => matches!(probed, VR::US | VR::SS),
119        VirtualVr::Ox => matches!(probed, VR::OB | VR::OW),
120        VirtualVr::Px => matches!(probed, VR::OB | VR::OW),
121        VirtualVr::Lt => matches!(probed, VR::US | VR::OW),
122        // unknown variants: treat as incompatible to avoid
123        // false-positive explicit detection
124        _ => false,
125    }
126}
127
128impl<D> Decode for AdaptiveVRLittleEndianDecoder<D>
129where
130    D: DataDictionary,
131{
132    fn decode_header<S>(&self, mut source: &mut S) -> Result<(DataElementHeader, usize)>
133    where
134        S: ?Sized + Read,
135    {
136        // retrieve tag
137        let Tag(group, element) = self
138            .basic
139            .decode_tag(&mut source)
140            .context(ReadHeaderTagSnafu)?;
141
142        let mut buf = [0u8; 4];
143
144        // item delimiters never have VR or reserved fields
145        if group == 0xFFFE {
146            source.read_exact(&mut buf).context(ReadItemLengthSnafu)?;
147            let len = LittleEndian::read_u32(&buf);
148            return Ok((
149                DataElementHeader::new((group, element), VR::UN, Length(len)),
150                8,
151            ));
152        }
153
154        let tag = Tag(group, element);
155        let state = self.state.get();
156
157        match state {
158            VrState::Explicit => decode_explicit_header(&mut source, tag, &mut buf),
159            VrState::Implicit => {
160                let (vr, len, bytes) = decode_implicit_length(&mut source, tag, self, &mut buf)?;
161                Ok((DataElementHeader::new(tag, vr, Length(len)), bytes))
162            }
163            VrState::Unknown => {
164                // Probe: read the 2 bytes after the tag.
165                // If they form a valid VR, we're in explicit mode.
166                // Otherwise, they're the first half of a 4-byte length.
167                source.read_exact(&mut buf[0..2]).context(ReadVrSnafu)?;
168
169                if let Some(vr) = VR::from_binary([buf[0], buf[1]]) {
170                    // Cross-check against the data dictionary:
171                    // if the dictionary knows this tag and the probed VR
172                    // is incompatible, the bytes are actually
173                    // the start of a 4-byte implicit length.
174                    let dict_vvr = self.dict.by_tag(tag).map(|entry| entry.vr());
175                    let dict_disagrees =
176                        dict_vvr.is_some_and(|vvr| !vr_compatible_with_virtual(vr, vvr));
177                    if dict_disagrees && !has_short_length(vr) {
178                        // (dcmnorm) A long-form VR is followed by 2 reserved bytes that must be
179                        // zero, which settles it: as an implicit length, those bytes are its high
180                        // half. Zero means explicit unless the implicit length is exactly the VR's
181                        // own 2 bytes read as a number (16706-23130) - far less likely than an
182                        // explicit file whose first element disagrees with the dictionary, which
183                        // real writers produce (e.g. GDCM writing every element as UN).
184                        source
185                            .read_exact(&mut buf[2..4])
186                            .context(ReadReservedSnafu)?;
187                        if buf[2..4] != [0, 0] {
188                            self.state.set(VrState::Implicit);
189                            let len = LittleEndian::read_u32(&buf);
190                            let resolved = self.resolve_vr(tag);
191                            return Ok((DataElementHeader::new(tag, resolved, Length(len)), 8));
192                        }
193                        self.state.set(VrState::Explicit);
194                        source.read_exact(&mut buf).context(ReadLengthSnafu)?;
195                        let len = LittleEndian::read_u32(&buf);
196                        return Ok((DataElementHeader::new(tag, vr, Length(len)), 12));
197                    }
198                    if dict_disagrees {
199                        self.state.set(VrState::Implicit);
200                        source.read_exact(&mut buf[2..4]).context(ReadLengthSnafu)?;
201                        let len = LittleEndian::read_u32(&buf);
202                        let resolved = self.resolve_vr(tag);
203                        return Ok((DataElementHeader::new(tag, resolved, Length(len)), 8));
204                    }
205
206                    self.state.set(VrState::Explicit);
207                    let (len, bytes_read) = decode_explicit_length(&mut source, vr, &mut buf)?;
208                    Ok((DataElementHeader::new(tag, vr, Length(len)), bytes_read))
209                } else {
210                    self.state.set(VrState::Implicit);
211                    // The 2 bytes we read are the low half of the 4-byte length.
212                    // Read the remaining 2 bytes.
213                    source.read_exact(&mut buf[2..4]).context(ReadLengthSnafu)?;
214                    let len = LittleEndian::read_u32(&buf);
215                    let vr = self.resolve_vr(tag);
216                    Ok((DataElementHeader::new(tag, vr, Length(len)), 8))
217                }
218            }
219        }
220    }
221
222    fn decode_item_header<S>(&self, source: &mut S) -> Result<SequenceItemHeader>
223    where
224        S: ?Sized + Read,
225    {
226        // item headers are the same regardless of VR mode
227        let mut buf = [0u8; 8];
228        source.read_exact(&mut buf).context(ReadItemHeaderSnafu)?;
229        let group = LittleEndian::read_u16(&buf[0..2]);
230        let element = LittleEndian::read_u16(&buf[2..4]);
231        let len = LittleEndian::read_u32(&buf[4..8]);
232        SequenceItemHeader::new((group, element), Length(len)).context(BadSequenceHeaderSnafu)
233    }
234
235    #[inline]
236    fn decode_tag<S>(&self, source: &mut S) -> Result<Tag>
237    where
238        S: ?Sized + Read,
239    {
240        self.basic.decode_tag(source).context(ReadTagSnafu)
241    }
242}
243
244/// Decode an explicit VR element header after the tag has been read.
245fn decode_explicit_header<S>(
246    source: &mut S,
247    tag: Tag,
248    buf: &mut [u8; 4],
249) -> Result<(DataElementHeader, usize)>
250where
251    S: ?Sized + Read,
252{
253    source.read_exact(&mut buf[0..2]).context(ReadVrSnafu)?;
254    let vr = VR::from_binary([buf[0], buf[1]]).unwrap_or(VR::UN);
255    let (len, bytes_read) = decode_explicit_length(source, vr, buf)?;
256    Ok((DataElementHeader::new(tag, vr, Length(len)), bytes_read))
257}
258
259/// Read the length field for an explicit VR element.
260/// Returns (length, total_bytes_read_including_tag_and_vr).
261/// Whether an explicit VR element of this VR has a 2-byte length field (and no reserved bytes).
262fn has_short_length(vr: VR) -> bool {
263    matches!(
264        vr,
265        VR::AE
266            | VR::AS
267            | VR::AT
268            | VR::CS
269            | VR::DA
270            | VR::DS
271            | VR::DT
272            | VR::FL
273            | VR::FD
274            | VR::IS
275            | VR::LO
276            | VR::LT
277            | VR::PN
278            | VR::SH
279            | VR::SL
280            | VR::SS
281            | VR::ST
282            | VR::TM
283            | VR::UI
284            | VR::UL
285            | VR::US
286    )
287}
288
289fn decode_explicit_length<S>(source: &mut S, vr: VR, buf: &mut [u8; 4]) -> Result<(u32, usize)>
290where
291    S: ?Sized + Read,
292{
293    match vr {
294        VR::AE
295        | VR::AS
296        | VR::AT
297        | VR::CS
298        | VR::DA
299        | VR::DS
300        | VR::DT
301        | VR::FL
302        | VR::FD
303        | VR::IS
304        | VR::LO
305        | VR::LT
306        | VR::PN
307        | VR::SH
308        | VR::SL
309        | VR::SS
310        | VR::ST
311        | VR::TM
312        | VR::UI
313        | VR::UL
314        | VR::US => {
315            source.read_exact(&mut buf[0..2]).context(ReadLengthSnafu)?;
316            Ok((u32::from(LittleEndian::read_u16(&buf[0..2])), 8))
317        }
318        _ => {
319            source
320                .read_exact(&mut buf[0..2])
321                .context(ReadReservedSnafu)?;
322            source.read_exact(buf).context(ReadLengthSnafu)?;
323            Ok((LittleEndian::read_u32(buf), 12))
324        }
325    }
326}
327
328/// Read the length field for an implicit VR element (4 bytes)
329/// and resolve VR from the dictionary.
330fn decode_implicit_length<S, D>(
331    source: &mut S,
332    tag: Tag,
333    dec: &AdaptiveVRLittleEndianDecoder<D>,
334    buf: &mut [u8; 4],
335) -> Result<(VR, u32, usize)>
336where
337    S: ?Sized + Read,
338    D: DataDictionary,
339{
340    source.read_exact(buf).context(ReadLengthSnafu)?;
341    let len = LittleEndian::read_u32(buf);
342    let vr = dec.resolve_vr(tag);
343    Ok((vr, len, 8))
344}
345
346impl<S: ?Sized, D> DecodeFrom<S> for AdaptiveVRLittleEndianDecoder<D>
347where
348    S: Read,
349    D: DataDictionary,
350{
351    #[inline]
352    fn decode_header(&self, source: &mut S) -> Result<(DataElementHeader, usize)> {
353        Decode::decode_header(self, source)
354    }
355
356    #[inline]
357    fn decode_item_header(&self, source: &mut S) -> Result<SequenceItemHeader> {
358        Decode::decode_item_header(self, source)
359    }
360
361    #[inline]
362    fn decode_tag(&self, source: &mut S) -> Result<Tag> {
363        Decode::decode_tag(self, source)
364    }
365
366    #[inline]
367    fn is_explicit_vr(&self) -> bool {
368        self.state.get() == VrState::Explicit
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::AdaptiveVRLittleEndianDecoder;
375    use crate::decode::Decode;
376    use dcmnorm_core::dictionary::stub::StubDataDictionary;
377    use dcmnorm_core::header::{HasLength, Header, Length};
378    use dcmnorm_core::{Tag, VR};
379    use std::io::{Cursor, Read, Seek, SeekFrom};
380
381    // Explicit VR data: same structure as the explicit_le tests.
382    //   Tag: (0002,0002) Media Storage SOP Class UID
383    //   VR: UI, Length: 26
384    //   Value: "1.2.840.10008.5.1.4.1.1.1\0"
385    // --
386    //   Tag: (0002,0010) Transfer Syntax UID
387    //   VR: UI, Length: 20
388    //   Value: "1.2.840.10008.1.2.1\0"
389    #[rustfmt::skip]
390    const RAW_EXPLICIT: &[u8] = &[
391        0x02, 0x00, 0x02, 0x00,     // tag (0002,0002)
392            b'U', b'I',             // VR
393            0x1A, 0x00,             // length: 26
394            0x31, 0x2e, 0x32, 0x2e, 0x38, 0x34, 0x30, 0x2e,
395            0x31, 0x30, 0x30, 0x30, 0x38, 0x2e, 0x35, 0x2e,
396            0x31, 0x2e, 0x34, 0x2e, 0x31, 0x2e, 0x31, 0x2e,
397            0x31, 0x00,
398        0x02, 0x00, 0x10, 0x00,     // tag (0002,0010)
399            b'U', b'I',             // VR
400            0x14, 0x00,             // length: 20
401            0x31, 0x2e, 0x32, 0x2e, 0x38, 0x34, 0x30, 0x2e,
402            0x31, 0x30, 0x30, 0x30, 0x38, 0x2e, 0x31, 0x2e,
403            0x32, 0x2e, 0x31, 0x00,
404    ];
405
406    #[test]
407    fn adaptive_reads_explicit_vr() {
408        let reader = AdaptiveVRLittleEndianDecoder::with_std_dict();
409        let mut cursor = Cursor::new(RAW_EXPLICIT);
410        {
411            let (elem, bytes_read) = reader
412                .decode_header(&mut cursor)
413                .expect("should find an element");
414            assert_eq!(elem.tag(), Tag(0x0002, 0x0002));
415            assert_eq!(elem.vr(), VR::UI);
416            assert_eq!(elem.length(), Length(26));
417            assert_eq!(bytes_read, 8);
418            cursor.seek(SeekFrom::Current(26)).unwrap();
419        }
420        {
421            let (elem, _) = reader
422                .decode_header(&mut cursor)
423                .expect("should find an element");
424            assert_eq!(elem.tag(), Tag(0x0002, 0x0010));
425            assert_eq!(elem.vr(), VR::UI);
426            assert_eq!(elem.length(), Length(20));
427        }
428    }
429
430    // Implicit VR data: tag + 4-byte length, no VR bytes.
431    //   Tag: (0002,0002) Media Storage SOP Class UID
432    //   Length: 26
433    //   Value: "1.2.840.10008.5.1.4.1.1.1\0"
434    // --
435    //   Tag: (0002,0010) Transfer Syntax UID
436    //   Length: 20
437    //   Value: "1.2.840.10008.1.2.1\0"
438    #[rustfmt::skip]
439    const RAW_IMPLICIT: &[u8] = &[
440        0x02, 0x00, 0x02, 0x00,     // tag (0002,0002)
441            0x1A, 0x00, 0x00, 0x00, // length: 26
442            0x31, 0x2e, 0x32, 0x2e, 0x38, 0x34, 0x30, 0x2e,
443            0x31, 0x30, 0x30, 0x30, 0x38, 0x2e, 0x35, 0x2e,
444            0x31, 0x2e, 0x34, 0x2e, 0x31, 0x2e, 0x31, 0x2e,
445            0x31, 0x00,
446        0x02, 0x00, 0x10, 0x00,     // tag (0002,0010)
447            0x14, 0x00, 0x00, 0x00, // length: 20
448            0x31, 0x2e, 0x32, 0x2e, 0x38, 0x34, 0x30, 0x2e,
449            0x31, 0x30, 0x30, 0x30, 0x38, 0x2e, 0x31, 0x2e,
450            0x32, 0x2e, 0x31, 0x00,
451    ];
452
453    const DICT: &StubDataDictionary = &StubDataDictionary;
454
455    #[test]
456    fn adaptive_reads_implicit_vr() {
457        let reader = AdaptiveVRLittleEndianDecoder::with_dict(DICT);
458        let mut cursor = Cursor::new(RAW_IMPLICIT);
459        {
460            let (elem, bytes_read) = reader
461                .decode_header(&mut cursor)
462                .expect("should find an element");
463            assert_eq!(elem.tag(), Tag(0x0002, 0x0002));
464            // StubDataDictionary returns UN for unknown tags
465            assert_eq!(elem.vr(), VR::UN);
466            assert_eq!(elem.length(), Length(26));
467            assert_eq!(bytes_read, 8);
468            cursor.seek(SeekFrom::Current(26)).unwrap();
469        }
470        {
471            let (elem, _) = reader
472                .decode_header(&mut cursor)
473                .expect("should find an element");
474            assert_eq!(elem.tag(), Tag(0x0002, 0x0010));
475            assert_eq!(elem.vr(), VR::UN);
476            assert_eq!(elem.length(), Length(20));
477        }
478    }
479
480    #[test]
481    fn adaptive_reads_implicit_with_standard_dict() {
482        let reader = AdaptiveVRLittleEndianDecoder::with_std_dict();
483        let mut cursor = Cursor::new(RAW_IMPLICIT);
484        {
485            let (elem, _) = reader
486                .decode_header(&mut cursor)
487                .expect("should find an element");
488            assert_eq!(elem.tag(), Tag(0x0002, 0x0002));
489            assert_eq!(elem.vr(), VR::UI);
490            assert_eq!(elem.length(), Length(26));
491            cursor.seek(SeekFrom::Current(26)).unwrap();
492        }
493        {
494            let (elem, _) = reader
495                .decode_header(&mut cursor)
496                .expect("should find an element");
497            assert_eq!(elem.tag(), Tag(0x0002, 0x0010));
498            assert_eq!(elem.vr(), VR::UI);
499            assert_eq!(elem.length(), Length(20));
500        }
501    }
502
503    // Sequence/item delimiters — should work regardless of VR state.
504    //  Tag: (FFFE,E000) Item, Length: 0xFFFFFFFF
505    //  Tag: (FFFE,E00D) Item Delimitation, Length: 0
506    //  Tag: (FFFE,E0DD) Sequence Delimitation, Length: 0
507    #[rustfmt::skip]
508    const RAW_DELIMITERS: &[u8] = &[
509        0xFE, 0xFF, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF,
510        0xFE, 0xFF, 0x0D, 0xE0, 0x00, 0x00, 0x00, 0x00,
511        0xFE, 0xFF, 0xDD, 0xE0, 0x00, 0x00, 0x00, 0x00,
512    ];
513
514    #[test]
515    fn adaptive_reads_delimiters() {
516        let reader = AdaptiveVRLittleEndianDecoder::with_std_dict();
517        let mut cursor = Cursor::new(RAW_DELIMITERS);
518        {
519            let (elem, bytes_read) = reader
520                .decode_header(&mut cursor)
521                .expect("should find an element");
522            assert_eq!(elem.tag(), Tag(0xFFFE, 0xE000));
523            assert_eq!(elem.vr(), VR::UN);
524            assert!(elem.length().is_undefined());
525            assert_eq!(bytes_read, 8);
526        }
527        {
528            let (elem, _) = reader
529                .decode_header(&mut cursor)
530                .expect("should find an element");
531            assert_eq!(elem.tag(), Tag(0xFFFE, 0xE00D));
532            assert_eq!(elem.length(), Length(0));
533        }
534        {
535            let (elem, _) = reader
536                .decode_header(&mut cursor)
537                .expect("should find an element");
538            assert_eq!(elem.tag(), Tag(0xFFFE, 0xE0DD));
539            assert_eq!(elem.length(), Length(0));
540        }
541    }
542
543    // Mixed: explicit VR element followed by a sequence delimiter.
544    // Verifies the state is locked after the first probe
545    // and delimiters still work.
546    #[rustfmt::skip]
547    const RAW_EXPLICIT_THEN_DELIMITER: &[u8] = &[
548        // (0008,0060) Modality, VR: CS, Length: 2, Value: "CT"
549        0x08, 0x00, 0x60, 0x00,
550            b'C', b'S',
551            0x02, 0x00,
552            b'C', b'T',
553        // (FFFE,E0DD) Sequence Delimitation, Length: 0
554        0xFE, 0xFF, 0xDD, 0xE0, 0x00, 0x00, 0x00, 0x00,
555    ];
556
557    // Implicit VR data where the length field's low bytes happen to
558    // match a valid VR code ("UN" = 0x55 0x4E, length = 20053).
559    // The dictionary cross-check should catch the mismatch
560    // (Modality is CS, not UN) and correctly treat as implicit.
561    #[rustfmt::skip]
562    const RAW_IMPLICIT_VR_COLLISION: &[u8] = &[
563        // (0008,0060) Modality — implicit VR, length 85589 (0x00014E55)
564        // Low bytes of length: 0x55 0x4E = "UN"; the high half (0x0001)
565        // can't be UN's reserved bytes, which must be zero
566        0x08, 0x00, 0x60, 0x00,
567            0x55, 0x4E, 0x01, 0x00,
568            // (value bytes omitted — we only need to parse the header)
569    ];
570
571    #[test]
572    fn adaptive_rejects_false_positive_vr() {
573        let reader = AdaptiveVRLittleEndianDecoder::with_std_dict();
574        let mut cursor = Cursor::new(RAW_IMPLICIT_VR_COLLISION);
575        let (elem, bytes_read) = reader
576            .decode_header(&mut cursor)
577            .expect("should find an element");
578        assert_eq!(elem.tag(), Tag(0x0008, 0x0060));
579        // Dictionary says Modality is CS, probed bytes say UN:
580        // dictionary wins, implicit VR is used, CS resolved from dict
581        assert_eq!(elem.vr(), VR::CS);
582        assert_eq!(elem.length(), Length(85589));
583        assert_eq!(bytes_read, 8);
584    }
585
586    /// (dcmnorm) An explicit VR file whose first element is UN although the dictionary has a
587    /// specific VR for it - as GDCM writes, e.g. test/files/vr_un.dcm - is explicit, not implicit.
588    #[test]
589    fn adaptive_reads_explicit_un_that_disagrees_with_the_dictionary() {
590        #[rustfmt::skip]
591        const RAW: &[u8] = &[
592            // (0008,0005) SpecificCharacterSet, dictionary VR CS, written as UN, length 10
593            0x08, 0x00, 0x05, 0x00, b'U', b'N', 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00,
594                b'I', b'S', b'O', b'_', b'I', b'R', b' ', b'1', b'0', b'0',
595            // (0008,0060) Modality, short-form CS
596            0x08, 0x00, 0x60, 0x00, b'C', b'S', 0x02, 0x00, b'C', b'T',
597        ];
598        let reader = AdaptiveVRLittleEndianDecoder::with_std_dict();
599        let mut cursor = Cursor::new(RAW);
600        let (elem, bytes_read) = reader
601            .decode_header(&mut cursor)
602            .expect("should find an element");
603        assert_eq!(elem.tag(), Tag(0x0008, 0x0005));
604        assert_eq!(elem.vr(), VR::UN);
605        assert_eq!(elem.length(), Length(10));
606        assert_eq!(bytes_read, 12);
607        cursor.set_position(cursor.position() + 10);
608        let (elem, _) = reader
609            .decode_header(&mut cursor)
610            .expect("should find the next element");
611        assert_eq!(elem.tag(), Tag(0x0008, 0x0060));
612        assert_eq!(elem.vr(), VR::CS);
613        assert_eq!(elem.length(), Length(2));
614    }
615
616    #[test]
617    fn adaptive_explicit_then_delimiter() {
618        let reader = AdaptiveVRLittleEndianDecoder::with_std_dict();
619        let mut cursor = Cursor::new(RAW_EXPLICIT_THEN_DELIMITER);
620        {
621            let (elem, _) = reader
622                .decode_header(&mut cursor)
623                .expect("should find an element");
624            assert_eq!(elem.tag(), Tag(0x0008, 0x0060));
625            assert_eq!(elem.vr(), VR::CS);
626            assert_eq!(elem.length(), Length(2));
627            let mut val = vec![0u8; 2];
628            cursor.read_exact(&mut val).unwrap();
629            assert_eq!(&val, b"CT");
630        }
631        {
632            let (elem, _) = reader
633                .decode_header(&mut cursor)
634                .expect("should find delimiter");
635            assert_eq!(elem.tag(), Tag(0xFFFE, 0xE0DD));
636            assert_eq!(elem.length(), Length(0));
637        }
638    }
639}