1use 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
27pub type StandardAdaptiveVRLittleEndianDecoder =
29 AdaptiveVRLittleEndianDecoder<StandardDataDictionary>;
30
31#[derive(Debug, Copy, Clone, PartialEq, Eq)]
32enum VrState {
33 Unknown,
35 Explicit,
37 Implicit,
39}
40
41pub 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 pub fn with_std_dict() -> Self {
68 AdaptiveVRLittleEndianDecoder {
69 dict: StandardDataDictionary,
70 basic: LittleEndianBasicDecoder,
71 state: Cell::new(VrState::Unknown),
72 }
73 }
74
75 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 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 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
113fn 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 _ => 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 let Tag(group, element) = self
138 .basic
139 .decode_tag(&mut source)
140 .context(ReadHeaderTagSnafu)?;
141
142 let mut buf = [0u8; 4];
143
144 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 source.read_exact(&mut buf[0..2]).context(ReadVrSnafu)?;
168
169 if let Some(vr) = VR::from_binary([buf[0], buf[1]]) {
170 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 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 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 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
244fn 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
259fn 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
328fn 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 #[rustfmt::skip]
390 const RAW_EXPLICIT: &[u8] = &[
391 0x02, 0x00, 0x02, 0x00, b'U', b'I', 0x1A, 0x00, 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, b'U', b'I', 0x14, 0x00, 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 #[rustfmt::skip]
439 const RAW_IMPLICIT: &[u8] = &[
440 0x02, 0x00, 0x02, 0x00, 0x1A, 0x00, 0x00, 0x00, 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, 0x14, 0x00, 0x00, 0x00, 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 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 #[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 #[rustfmt::skip]
547 const RAW_EXPLICIT_THEN_DELIMITER: &[u8] = &[
548 0x08, 0x00, 0x60, 0x00,
550 b'C', b'S',
551 0x02, 0x00,
552 b'C', b'T',
553 0xFE, 0xFF, 0xDD, 0xE0, 0x00, 0x00, 0x00, 0x00,
555 ];
556
557 #[rustfmt::skip]
562 const RAW_IMPLICIT_VR_COLLISION: &[u8] = &[
563 0x08, 0x00, 0x60, 0x00,
567 0x55, 0x4E, 0x01, 0x00,
568 ];
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 assert_eq!(elem.vr(), VR::CS);
582 assert_eq!(elem.length(), Length(85589));
583 assert_eq!(bytes_read, 8);
584 }
585
586 #[test]
589 fn adaptive_reads_explicit_un_that_disagrees_with_the_dictionary() {
590 #[rustfmt::skip]
591 const RAW: &[u8] = &[
592 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 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}