Skip to main content

dicom_encoding/decode/
mod.rs

1//! This module contains all DICOM data element decoding logic.
2
3use self::explicit_le::ExplicitVRLittleEndianDecoder;
4use self::implicit_le::{ImplicitVRLittleEndianDecoder, StandardImplicitVRLittleEndianDecoder};
5use byteordered::Endianness;
6use dicom_core::Tag;
7use dicom_core::header::{DataElementHeader, SequenceItemHeader};
8use snafu::{Backtrace, Snafu};
9use std::io::{self, Read};
10
11pub mod adaptive_le;
12pub mod basic;
13pub mod explicit_be;
14pub mod explicit_le;
15pub mod implicit_le;
16
17/// Module-level error type:
18/// for errors which may occur while decoding DICOM data.
19#[derive(Debug, Snafu)]
20#[non_exhaustive]
21pub enum Error {
22    #[snafu(display("Failed to read the beginning (tag) of the header"))]
23    ReadHeaderTag {
24        backtrace: Option<Backtrace>,
25        source: io::Error,
26    },
27    #[snafu(display("Failed to read the item header"))]
28    ReadItemHeader {
29        backtrace: Backtrace,
30        source: io::Error,
31    },
32    #[snafu(display("Failed to read the header's item length field"))]
33    ReadItemLength {
34        backtrace: Backtrace,
35        source: io::Error,
36    },
37    #[snafu(display("Failed to read the header's tag field"))]
38    ReadTag {
39        backtrace: Backtrace,
40        source: io::Error,
41    },
42    #[snafu(display("Failed to read the header's reserved bytes"))]
43    ReadReserved {
44        backtrace: Backtrace,
45        source: io::Error,
46    },
47    #[snafu(display("Failed to read the header's element length field"))]
48    ReadLength {
49        backtrace: Backtrace,
50        source: io::Error,
51    },
52    #[snafu(display("Failed to read the header's value representation"))]
53    ReadVr {
54        backtrace: Backtrace,
55        source: io::Error,
56    },
57    #[snafu(display("Bad sequence item header"))]
58    BadSequenceHeader {
59        source: dicom_core::header::SequenceItemHeaderError,
60    },
61}
62
63pub type Result<T> = std::result::Result<T, Error>;
64
65/** Obtain the default data element decoder.
66 * According to the standard, data elements are encoded in Implicit
67 * VR Little Endian by default.
68 */
69pub fn default_reader() -> StandardImplicitVRLittleEndianDecoder {
70    ImplicitVRLittleEndianDecoder::default()
71}
72
73/** Obtain a data element decoder for reading the data elements in a DICOM
74 * file's Meta information. According to the standard, these are always
75 * encoded in Explicit VR Little Endian.
76 */
77pub fn file_header_decoder() -> ExplicitVRLittleEndianDecoder {
78    ExplicitVRLittleEndianDecoder::default()
79}
80
81/** Type trait for reading and decoding basic data values from a data source.
82 *
83 * This trait aims to provide methods for reading binary numbers based on the
84 * source's endianness. Unlike `Decode`, this trait is not object safe.
85 * However, it doesn't have to because there are, and only will be, two
86 * possible implementations (`LittleEndianBasicDecoder` and
87 * `BigEndianBasicDecoder`).
88 */
89pub trait BasicDecode {
90    /// Retrieve the source's endianness, as expected by this decoder.
91    fn endianness(&self) -> Endianness;
92
93    /// Decode an unsigned short value from the given source.
94    fn decode_us<S>(&self, source: S) -> io::Result<u16>
95    where
96        S: Read;
97
98    /// Decode a sequence of unsigned shorts value from the given source
99    /// into the given destination.
100    fn decode_us_into<S>(&self, mut source: S, dst: &mut [u16]) -> io::Result<()>
101    where
102        S: Read,
103    {
104        for v in dst.iter_mut() {
105            *v = self.decode_us(&mut source)?;
106        }
107
108        Ok(())
109    }
110
111    /// Decode an unsigned long value from the given source.
112    fn decode_ul<S>(&self, source: S) -> io::Result<u32>
113    where
114        S: Read;
115
116    /// Decode a sequence of unsigned long values from the given source
117    /// into the given destination.
118    fn decode_ul_into<S>(&self, mut source: S, dst: &mut [u32]) -> io::Result<()>
119    where
120        S: Read,
121    {
122        for v in dst.iter_mut() {
123            *v = self.decode_ul(&mut source)?;
124        }
125
126        Ok(())
127    }
128
129    /// Decode an unsigned very long value from the given source.
130    fn decode_uv<S>(&self, source: S) -> io::Result<u64>
131    where
132        S: Read;
133
134    /// Decode a sequence of unsigned very long values from the given source
135    /// into the given destination.
136    fn decode_uv_into<S>(&self, mut source: S, dst: &mut [u64]) -> io::Result<()>
137    where
138        S: Read,
139    {
140        for v in dst.iter_mut() {
141            *v = self.decode_uv(&mut source)?;
142        }
143
144        Ok(())
145    }
146
147    /// Decode a signed short value from the given source.
148    fn decode_ss<S>(&self, source: S) -> io::Result<i16>
149    where
150        S: Read;
151
152    /// Decode a sequence of signed short values from the given source
153    /// into the given destination.
154    fn decode_ss_into<S>(&self, mut source: S, dst: &mut [i16]) -> io::Result<()>
155    where
156        S: Read,
157    {
158        for v in dst.iter_mut() {
159            *v = self.decode_ss(&mut source)?;
160        }
161
162        Ok(())
163    }
164
165    /// Decode a signed long value from the given source.
166    fn decode_sl<S>(&self, source: S) -> io::Result<i32>
167    where
168        S: Read;
169
170    /// Decode a sequence of signed long values from the given source
171    /// into the given destination.
172    fn decode_sl_into<S>(&self, mut source: S, dst: &mut [i32]) -> io::Result<()>
173    where
174        S: Read,
175    {
176        for v in dst.iter_mut() {
177            *v = self.decode_sl(&mut source)?;
178        }
179
180        Ok(())
181    }
182
183    /// Decode a signed very long value from the given source.
184    fn decode_sv<S>(&self, source: S) -> io::Result<i64>
185    where
186        S: Read;
187
188    /// Decode a sequence of signed very long values from the given source
189    /// into the given destination.
190    fn decode_sv_into<S>(&self, mut source: S, dst: &mut [i64]) -> io::Result<()>
191    where
192        S: Read,
193    {
194        for v in dst.iter_mut() {
195            *v = self.decode_sv(&mut source)?;
196        }
197
198        Ok(())
199    }
200
201    /// Decode a single precision float value from the given source.
202    fn decode_fl<S>(&self, source: S) -> io::Result<f32>
203    where
204        S: Read;
205
206    /// Decode a sequence of single precision float values from the given source
207    /// into the given destination.
208    fn decode_fl_into<S>(&self, mut source: S, dst: &mut [f32]) -> io::Result<()>
209    where
210        S: Read,
211    {
212        for v in dst.iter_mut() {
213            *v = self.decode_fl(&mut source)?;
214        }
215
216        Ok(())
217    }
218
219    /// Decode a double precision float value from the given source.
220    fn decode_fd<S>(&self, source: S) -> io::Result<f64>
221    where
222        S: Read;
223
224    /// Decode a sequence of double precision float values from the given source
225    /// into the given destination.
226    fn decode_fd_into<S>(&self, mut source: S, dst: &mut [f64]) -> io::Result<()>
227    where
228        S: Read,
229    {
230        for v in dst.iter_mut() {
231            *v = self.decode_fd(&mut source)?;
232        }
233
234        Ok(())
235    }
236
237    /// Decode a DICOM attribute tag from the given source.
238    fn decode_tag<S>(&self, mut source: S) -> io::Result<Tag>
239    where
240        S: Read,
241    {
242        let g = self.decode_us(&mut source)?;
243        let e = self.decode_us(source)?;
244        Ok(Tag(g, e))
245    }
246}
247
248impl<T: ?Sized> BasicDecode for Box<T>
249where
250    T: BasicDecode,
251{
252    fn endianness(&self) -> Endianness {
253        (**self).endianness()
254    }
255
256    fn decode_us<S>(&self, source: S) -> io::Result<u16>
257    where
258        S: Read,
259    {
260        (**self).decode_us(source)
261    }
262
263    fn decode_us_into<S>(&self, source: S, dst: &mut [u16]) -> io::Result<()>
264    where
265        S: Read,
266    {
267        (**self).decode_us_into(source, dst)
268    }
269
270    fn decode_ul<S>(&self, source: S) -> io::Result<u32>
271    where
272        S: Read,
273    {
274        (**self).decode_ul(source)
275    }
276
277    fn decode_ul_into<S>(&self, source: S, dst: &mut [u32]) -> io::Result<()>
278    where
279        S: Read,
280    {
281        (**self).decode_ul_into(source, dst)
282    }
283
284    fn decode_uv<S>(&self, source: S) -> io::Result<u64>
285    where
286        S: Read,
287    {
288        (**self).decode_uv(source)
289    }
290
291    fn decode_uv_into<S>(&self, source: S, dst: &mut [u64]) -> io::Result<()>
292    where
293        S: Read,
294    {
295        (**self).decode_uv_into(source, dst)
296    }
297
298    fn decode_ss<S>(&self, source: S) -> io::Result<i16>
299    where
300        S: Read,
301    {
302        (**self).decode_ss(source)
303    }
304
305    fn decode_ss_into<S>(&self, source: S, dst: &mut [i16]) -> io::Result<()>
306    where
307        S: Read,
308    {
309        (**self).decode_ss_into(source, dst)
310    }
311
312    fn decode_sl<S>(&self, source: S) -> io::Result<i32>
313    where
314        S: Read,
315    {
316        (**self).decode_sl(source)
317    }
318
319    fn decode_sl_into<S>(&self, source: S, dst: &mut [i32]) -> io::Result<()>
320    where
321        S: Read,
322    {
323        (**self).decode_sl_into(source, dst)
324    }
325
326    fn decode_sv<S>(&self, source: S) -> io::Result<i64>
327    where
328        S: Read,
329    {
330        (**self).decode_sv(source)
331    }
332
333    fn decode_sv_into<S>(&self, source: S, dst: &mut [i64]) -> io::Result<()>
334    where
335        S: Read,
336    {
337        (**self).decode_sv_into(source, dst)
338    }
339
340    fn decode_fl<S>(&self, source: S) -> io::Result<f32>
341    where
342        S: Read,
343    {
344        (**self).decode_fl(source)
345    }
346
347    fn decode_fl_into<S>(&self, source: S, dst: &mut [f32]) -> io::Result<()>
348    where
349        S: Read,
350    {
351        (**self).decode_fl_into(source, dst)
352    }
353
354    fn decode_fd<S>(&self, source: S) -> io::Result<f64>
355    where
356        S: Read,
357    {
358        (**self).decode_fd(source)
359    }
360
361    fn decode_fd_into<S>(&self, source: S, dst: &mut [f64]) -> io::Result<()>
362    where
363        S: Read,
364    {
365        (**self).decode_fd_into(source, dst)
366    }
367
368    fn decode_tag<S>(&self, source: S) -> io::Result<Tag>
369    where
370        S: Read,
371    {
372        (**self).decode_tag(source)
373    }
374}
375
376impl<T: ?Sized> BasicDecode for &'_ T
377where
378    T: BasicDecode,
379{
380    fn endianness(&self) -> Endianness {
381        (**self).endianness()
382    }
383
384    fn decode_us<S>(&self, source: S) -> io::Result<u16>
385    where
386        S: Read,
387    {
388        (**self).decode_us(source)
389    }
390
391    fn decode_us_into<S>(&self, source: S, dst: &mut [u16]) -> io::Result<()>
392    where
393        S: Read,
394    {
395        (**self).decode_us_into(source, dst)
396    }
397
398    fn decode_ul<S>(&self, source: S) -> io::Result<u32>
399    where
400        S: Read,
401    {
402        (**self).decode_ul(source)
403    }
404
405    fn decode_ul_into<S>(&self, source: S, dst: &mut [u32]) -> io::Result<()>
406    where
407        S: Read,
408    {
409        (**self).decode_ul_into(source, dst)
410    }
411
412    fn decode_uv<S>(&self, source: S) -> io::Result<u64>
413    where
414        S: Read,
415    {
416        (**self).decode_uv(source)
417    }
418
419    fn decode_uv_into<S>(&self, source: S, dst: &mut [u64]) -> io::Result<()>
420    where
421        S: Read,
422    {
423        (**self).decode_uv_into(source, dst)
424    }
425
426    fn decode_ss<S>(&self, source: S) -> io::Result<i16>
427    where
428        S: Read,
429    {
430        (**self).decode_ss(source)
431    }
432
433    fn decode_ss_into<S>(&self, source: S, dst: &mut [i16]) -> io::Result<()>
434    where
435        S: Read,
436    {
437        (**self).decode_ss_into(source, dst)
438    }
439
440    fn decode_sl<S>(&self, source: S) -> io::Result<i32>
441    where
442        S: Read,
443    {
444        (**self).decode_sl(source)
445    }
446
447    fn decode_sl_into<S>(&self, source: S, dst: &mut [i32]) -> io::Result<()>
448    where
449        S: Read,
450    {
451        (**self).decode_sl_into(source, dst)
452    }
453
454    fn decode_sv<S>(&self, source: S) -> io::Result<i64>
455    where
456        S: Read,
457    {
458        (**self).decode_sv(source)
459    }
460
461    fn decode_sv_into<S>(&self, source: S, dst: &mut [i64]) -> io::Result<()>
462    where
463        S: Read,
464    {
465        (**self).decode_sv_into(source, dst)
466    }
467
468    fn decode_fl<S>(&self, source: S) -> io::Result<f32>
469    where
470        S: Read,
471    {
472        (**self).decode_fl(source)
473    }
474
475    fn decode_fl_into<S>(&self, source: S, dst: &mut [f32]) -> io::Result<()>
476    where
477        S: Read,
478    {
479        (**self).decode_fl_into(source, dst)
480    }
481
482    fn decode_fd<S>(&self, source: S) -> io::Result<f64>
483    where
484        S: Read,
485    {
486        (**self).decode_fd(source)
487    }
488
489    fn decode_fd_into<S>(&self, source: S, dst: &mut [f64]) -> io::Result<()>
490    where
491        S: Read,
492    {
493        (**self).decode_fd_into(source, dst)
494    }
495
496    fn decode_tag<S>(&self, source: S) -> io::Result<Tag>
497    where
498        S: Read,
499    {
500        (**self).decode_tag(source)
501    }
502}
503
504/** Type trait for reading and decoding DICOM data elements.
505 *
506 * The specific behaviour of decoding, even when abstracted from the original source,
507 * may depend on the transfer syntax.
508 */
509pub trait Decode {
510    /** Fetch and decode the next data element header from the given source.
511     * This method returns only the header of the element. At the end of this operation, the source
512     * will be pointing at the element's value data, which should be read or skipped as necessary.
513     *
514     * Decoding an item or sequence delimiter is considered valid, and so should be properly handled
515     * by the decoder. The value representation in this case should be `UN`.
516     *
517     * Returns the expected header and the exact number of bytes read from the source.
518     */
519    fn decode_header<S>(&self, source: &mut S) -> Result<(DataElementHeader, usize)>
520    where
521        S: ?Sized + Read;
522
523    /** Fetch and decode the next sequence item head from the given source. It is a separate method
524     * because value representation is always implicit when reading item headers and delimiters.
525     * This method returns only the header of the item. At the end of this operation, the source
526     * will be pointing at the beginning of the item's data, which should be traversed if necessary.
527     */
528    fn decode_item_header<S>(&self, source: &mut S) -> Result<SequenceItemHeader>
529    where
530        S: ?Sized + Read;
531
532    /// Decode a DICOM attribute tag from the given source.
533    fn decode_tag<S>(&self, source: &mut S) -> Result<Tag>
534    where
535        S: ?Sized + Read;
536}
537
538impl<T: ?Sized> Decode for Box<T>
539where
540    T: Decode,
541{
542    fn decode_header<S>(&self, source: &mut S) -> Result<(DataElementHeader, usize)>
543    where
544        S: ?Sized + Read,
545    {
546        (**self).decode_header(source)
547    }
548
549    fn decode_item_header<S>(&self, source: &mut S) -> Result<SequenceItemHeader>
550    where
551        S: ?Sized + Read,
552    {
553        (**self).decode_item_header(source)
554    }
555
556    fn decode_tag<S>(&self, source: &mut S) -> Result<Tag>
557    where
558        S: ?Sized + Read,
559    {
560        (**self).decode_tag(source)
561    }
562}
563
564impl<T: ?Sized> Decode for &'_ T
565where
566    T: Decode,
567{
568    fn decode_header<S>(&self, source: &mut S) -> Result<(DataElementHeader, usize)>
569    where
570        S: ?Sized + Read,
571    {
572        (**self).decode_header(source)
573    }
574
575    fn decode_item_header<S>(&self, source: &mut S) -> Result<SequenceItemHeader>
576    where
577        S: ?Sized + Read,
578    {
579        (**self).decode_item_header(source)
580    }
581
582    fn decode_tag<S>(&self, source: &mut S) -> Result<Tag>
583    where
584        S: ?Sized + Read,
585    {
586        (**self).decode_tag(source)
587    }
588}
589
590/** Type trait for reading and decoding DICOM data elements from a specific source
591 * reader type.
592 *
593 * The specific behaviour of decoding, even when abstracted from the original source,
594 * may depend on the transfer syntax.
595 */
596pub trait DecodeFrom<S: ?Sized + Read> {
597    /** Fetch and decode the next data element header from the given source.
598     * This method returns only the header of the element. At the end of this operation, the source
599     * will be pointing at the element's value data, which should be read or skipped as necessary.
600     *
601     * Decoding an item or sequence delimiter is considered valid, and so should be properly handled
602     * by the decoder. The value representation in this case should be `UN`.
603     *
604     * Returns the expected header and the exact number of bytes read from the source.
605     */
606    fn decode_header(&self, source: &mut S) -> Result<(DataElementHeader, usize)>;
607
608    /** Fetch and decode the next sequence item head from the given source. It is a separate method
609     * because value representation is always implicit when reading item headers and delimiters.
610     * This method returns only the header of the item. At the end of this operation, the source
611     * will be pointing at the beginning of the item's data, which should be traversed if necessary.
612     */
613    fn decode_item_header(&self, source: &mut S) -> Result<SequenceItemHeader>;
614
615    /// Decode a DICOM attribute tag from the given source.
616    fn decode_tag(&self, source: &mut S) -> Result<Tag>;
617}
618
619impl<S: ?Sized, T: ?Sized> DecodeFrom<S> for &T
620where
621    S: Read,
622    T: DecodeFrom<S>,
623{
624    fn decode_header(&self, source: &mut S) -> Result<(DataElementHeader, usize)> {
625        (**self).decode_header(source)
626    }
627
628    fn decode_item_header(&self, source: &mut S) -> Result<SequenceItemHeader> {
629        (**self).decode_item_header(source)
630    }
631
632    fn decode_tag(&self, source: &mut S) -> Result<Tag> {
633        (**self).decode_tag(source)
634    }
635}
636
637impl<S: ?Sized, T: ?Sized> DecodeFrom<S> for Box<T>
638where
639    S: Read,
640    T: DecodeFrom<S>,
641{
642    fn decode_header(&self, source: &mut S) -> Result<(DataElementHeader, usize)> {
643        (**self).decode_header(source)
644    }
645
646    fn decode_item_header(&self, source: &mut S) -> Result<SequenceItemHeader> {
647        (**self).decode_item_header(source)
648    }
649
650    fn decode_tag(&self, source: &mut S) -> Result<Tag> {
651        (**self).decode_tag(source)
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    fn is_decode_from<T: DecodeFrom<dyn Read>>(_decoder: &T) {}
660
661    #[allow(unused)]
662    fn boxed_decoder_from_is_decoder_from<T>(decoder: T)
663    where
664        T: DecodeFrom<dyn Read>,
665    {
666        is_decode_from(&decoder);
667        let boxed = Box::new(decoder);
668        is_decode_from(&boxed);
669        let erased = boxed as Box<dyn DecodeFrom<dyn Read>>;
670        is_decode_from(&erased);
671    }
672}