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