Skip to main content

dcmnorm_parser/stateful/
encode.rs

1//! Module holding a stateful DICOM data encoding abstraction.
2//!
3//! The [`StatefulEncoder`] supports encoding of binary data and text
4//! while applying the necessary padding to conform to DICOM encoding rules.
5
6use dcmnorm_core::{value::PrimitiveValue, DataElementHeader, Length, Tag, VR};
7use dcmnorm_encoding::transfer_syntax::DynEncoder;
8use dcmnorm_encoding::{
9    encode::EncodeTo,
10    text::{DefaultCharacterSetCodec, SpecificCharacterSet, TextCodec},
11    TransferSyntax,
12};
13use snafu::{Backtrace, OptionExt, ResultExt, Snafu};
14use std::io::Write;
15
16#[derive(Debug, Snafu)]
17#[non_exhaustive]
18pub enum Error {
19    #[snafu(display("Encoding in transfer syntax {} is unsupported", ts))]
20    UnsupportedTransferSyntax {
21        ts: &'static str,
22        backtrace: Backtrace,
23    },
24
25    #[snafu(display("Unsupported character set {:?}", charset))]
26    UnsupportedCharacterSet {
27        charset: SpecificCharacterSet,
28        backtrace: Backtrace,
29    },
30
31    #[snafu(display("Failed to encode a data piece at position {}", position))]
32    EncodeData {
33        position: u64,
34        source: dcmnorm_encoding::encode::Error,
35    },
36
37    #[snafu(display("Could not encode text at position {}", position))]
38    EncodeText {
39        position: u64,
40        source: dcmnorm_encoding::text::EncodeTextError,
41    },
42
43    #[snafu(display("Could not write value data at position {}", position))]
44    WriteValueData {
45        position: u64,
46        source: std::io::Error,
47        backtrace: Backtrace,
48    },
49}
50
51pub type Result<T> = std::result::Result<T, Error>;
52
53/// Also called a printer, this encoder type provides a stateful mid-level
54/// abstraction for writing DICOM content. Unlike `Encode`,
55/// the stateful encoder knows how to write text values and keeps track
56/// of how many bytes were written.
57/// `W` is the write target, `E` is the encoder, and `T` is the text codec.
58#[derive(Debug)]
59pub struct StatefulEncoder<W, E, T = SpecificCharacterSet> {
60    to: W,
61    encoder: E,
62    text: T,
63    bytes_written: u64,
64    buffer: Vec<u8>,
65}
66
67pub type DynStatefulEncoder<'w> = StatefulEncoder<Box<dyn Write + 'w>, DynEncoder<'w, dyn Write>>;
68
69impl<W, E, T> StatefulEncoder<W, E, T> {
70    pub fn new(to: W, encoder: E, text: T) -> Self {
71        StatefulEncoder {
72            to,
73            encoder,
74            text,
75            bytes_written: 0,
76            buffer: Vec::with_capacity(128),
77        }
78    }
79}
80
81impl<'s> DynStatefulEncoder<'s> {
82    pub fn from_transfer_syntax(
83        to: Box<dyn Write + 's>,
84        ts: TransferSyntax,
85        charset: SpecificCharacterSet,
86    ) -> Result<Self> {
87        let encoder = ts
88            .encoder()
89            .context(UnsupportedTransferSyntaxSnafu { ts: ts.uid() })?;
90        Ok(StatefulEncoder::new(to, encoder, charset))
91    }
92}
93
94impl<W, E> StatefulEncoder<W, E>
95where
96    W: Write,
97    E: EncodeTo<W>,
98{
99    /// Encode and write a data element header.
100    pub fn encode_element_header(&mut self, mut de: DataElementHeader) -> Result<()> {
101        if let Some(len) = de.len.get() {
102            de.len = Length(even_len(len))
103        }
104        let bytes = self
105            .encoder
106            .encode_element_header(&mut self.to, de)
107            .context(EncodeDataSnafu {
108                position: self.bytes_written,
109            })?;
110        self.bytes_written += bytes as u64;
111        Ok(())
112    }
113
114    /// Encode and write an item header,
115    /// where `len` is the specified length of the item
116    /// (can be `0xFFFF_FFFF` for undefined length).
117    pub fn encode_item_header(&mut self, len: u32) -> Result<()> {
118        let len = if len == 0xFFFF_FFFF {
119            len
120        } else {
121            even_len(len)
122        };
123        self.encoder
124            .encode_item_header(&mut self.to, len)
125            .context(EncodeDataSnafu {
126                position: self.bytes_written,
127            })?;
128        self.bytes_written += 8;
129        Ok(())
130    }
131
132    /// Encode and write an item delimiter.
133    pub fn encode_item_delimiter(&mut self) -> Result<()> {
134        self.encoder
135            .encode_item_delimiter(&mut self.to)
136            .context(EncodeDataSnafu {
137                position: self.bytes_written,
138            })?;
139        self.bytes_written += 8;
140        Ok(())
141    }
142
143    /// Encode and write a sequence delimiter.
144    pub fn encode_sequence_delimiter(&mut self) -> Result<()> {
145        self.encoder
146            .encode_sequence_delimiter(&mut self.to)
147            .context(EncodeDataSnafu {
148                position: self.bytes_written,
149            })?;
150        self.bytes_written += 8;
151        Ok(())
152    }
153
154    /// Write the given bytes directly to the inner writer.
155    ///
156    /// Note that this method
157    /// (unlike [`write_bytes`](StatefulEncoder::write_bytes))
158    /// does not perform any additional padding.
159    pub fn write_raw_bytes(&mut self, bytes: &[u8]) -> Result<()> {
160        self.to.write_all(bytes).context(WriteValueDataSnafu {
161            position: self.bytes_written,
162        })?;
163        self.bytes_written += bytes.len() as u64;
164        Ok(())
165    }
166
167    /// Write a primitive DICOM value as a bunch of bytes
168    /// directly to the inner writer.
169    ///
170    /// This method will perform the necessary padding
171    /// (always with zeros)
172    /// to ensure that the encoded value has an even number of bytes.
173    pub fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
174        debug_assert!(bytes.len() < u32::MAX as usize);
175        self.to.write_all(bytes).context(WriteValueDataSnafu {
176            position: self.bytes_written,
177        })?;
178        self.bytes_written += bytes.len() as u64;
179        if bytes.len() % 2 != 0 {
180            self.to.write_all(&[0]).context(WriteValueDataSnafu {
181                position: self.bytes_written,
182            })?;
183            self.bytes_written += 1;
184        }
185        Ok(())
186    }
187
188    /// Retrieve the number of bytes written so far by this printer.
189    pub fn bytes_written(&self) -> u64 {
190        self.bytes_written
191    }
192
193    /// Encode and write the values of a pixel data offset table.
194    pub fn encode_offset_table(&mut self, table: &[u32]) -> Result<()> {
195        self.encoder
196            .encode_offset_table(&mut self.to, table)
197            .context(EncodeDataSnafu {
198                position: self.bytes_written,
199            })?;
200
201        self.bytes_written += table.len() as u64 * 4;
202        Ok(())
203    }
204
205    /// Encode and write a data element with a primitive value.
206    ///
207    /// This method will perform the necessary padding to ensure that the
208    /// encoded value is an even number of bytes.
209    /// Where applicable,
210    /// this will use the inner text codec for textual values.
211    /// The length property of the header is ignored,
212    /// the true byte length of the value in its encoded form is used instead.
213    pub fn encode_primitive_element(
214        &mut self,
215        de: &DataElementHeader,
216        value: &PrimitiveValue,
217    ) -> Result<()> {
218        // intercept string encoding calls to use the text codec
219        match value {
220            PrimitiveValue::Str(text) => {
221                self.encode_text_element(text, *de)?;
222                Ok(())
223            }
224            PrimitiveValue::Strs(texts) => {
225                self.encode_texts_element(&texts[..], *de)?;
226                Ok(())
227            }
228            _ => {
229                // if VR is DS or IS and the value is binary,
230                // write value as a string instead
231                if let VR::DS | VR::IS = de.vr {
232                    return self.encode_element_as_text(value, de);
233                }
234
235                let byte_len = value.calculate_byte_len();
236                self.encode_element_header(DataElementHeader {
237                    tag: de.tag,
238                    vr: de.vr,
239                    len: Length(byte_len as u32),
240                })?;
241
242                let bytes = self.encoder.encode_primitive(&mut self.to, value).context(
243                    EncodeDataSnafu {
244                        position: self.bytes_written,
245                    },
246                )?;
247
248                self.bytes_written += bytes as u64;
249                if bytes % 2 != 0 {
250                    let padding = match de.vr {
251                        VR::DA | VR::DT | VR::TM => b' ',
252                        _ => 0,
253                    };
254                    self.to.write_all(&[padding]).context(WriteValueDataSnafu {
255                        position: self.bytes_written,
256                    })?;
257                    self.bytes_written += 1;
258                }
259
260                Ok(())
261            }
262        }
263    }
264
265    fn try_new_codec(&mut self, name: &str) {
266        let values: Vec<&str> = name.trim_end_matches(['\0', ' ']).split('\\').collect();
267        if let Some(codec) = SpecificCharacterSet::from_codes(&values) {
268            self.text = codec;
269        } else {
270            tracing::warn!("Unsupported character set `{}`, ignoring", name);
271        }
272    }
273
274    fn encode_text_element(&mut self, text: &str, de: DataElementHeader) -> Result<()> {
275        // encode it in memory first so that we know the real length
276        let mut encoded_value = self.convert_text_untrailed(text, de.vr)?;
277        // pad to even length
278        if encoded_value.len() % 2 == 1 {
279            let pad = if de.vr == VR::UI { b'\0' } else { b' ' };
280            encoded_value.push(pad);
281        }
282
283        // now we can write the header with the correct length
284        self.encode_element_header(DataElementHeader {
285            tag: de.tag,
286            vr: de.vr,
287            len: Length(encoded_value.len() as u32),
288        })?;
289        self.to
290            .write_all(&encoded_value)
291            .context(WriteValueDataSnafu {
292                position: self.bytes_written,
293            })?;
294        self.bytes_written += encoded_value.len() as u64;
295
296        // if element is Specific Character Set,
297        // update the text codec
298        if de.tag == Tag(0x0008, 0x0005) {
299            self.try_new_codec(text);
300        }
301
302        Ok(())
303    }
304
305    fn encode_texts_element<S>(&mut self, texts: &[S], de: DataElementHeader) -> Result<()>
306    where
307        S: AsRef<str>,
308    {
309        self.buffer.clear();
310        for (i, t) in texts.iter().enumerate() {
311            self.buffer
312                .extend_from_slice(&self.convert_text_untrailed(t.as_ref(), de.vr)?);
313            if i < texts.len() - 1 {
314                self.buffer.push(b'\\');
315            }
316        }
317        // pad to even length
318        if self.buffer.len() % 2 == 1 {
319            let pad = if de.vr == VR::UI { b'\0' } else { b' ' };
320            self.buffer.push(pad);
321        }
322
323        // now we can write the header with the correct length
324        self.encode_element_header(DataElementHeader {
325            tag: de.tag,
326            vr: de.vr,
327            len: Length(self.buffer.len() as u32),
328        })?;
329
330        self.to
331            .write_all(&self.buffer)
332            .context(WriteValueDataSnafu {
333                position: self.bytes_written,
334            })?;
335        self.bytes_written += self.buffer.len() as u64;
336
337        // if element is Specific Character Set,
338        // update the text codec
339        if de.tag == Tag(0x0008, 0x0005) {
340            // every value counts: `\ISO 2022 IR 87` is ISO 2022 code extension (#24)
341            let values: Vec<&str> = texts.iter().map(|t| t.as_ref()).collect();
342            self.try_new_codec(&values.join("\\"));
343        }
344
345        Ok(())
346    }
347
348    fn convert_text_untrailed(&self, text: &str, vr: VR) -> Result<Vec<u8>> {
349        match vr {
350            VR::AE | VR::AS | VR::CS | VR::DA | VR::DS | VR::DT | VR::IS | VR::TM | VR::UI => {
351                // these VRs always use the default character repertoire
352                DefaultCharacterSetCodec
353                    .encode(text)
354                    .context(EncodeTextSnafu {
355                        position: self.bytes_written,
356                    })
357            }
358            _ => self.text.encode(text).context(EncodeTextSnafu {
359                position: self.bytes_written,
360            }),
361        }
362    }
363
364    /// edge case method for encoding data elements with IS and VR values
365    /// (always as text)
366    fn encode_element_as_text(
367        &mut self,
368        value: &PrimitiveValue,
369        de: &DataElementHeader,
370    ) -> Result<()> {
371        match value {
372            PrimitiveValue::Empty => {
373                self.encode_element_header(DataElementHeader {
374                    tag: de.tag,
375                    vr: de.vr,
376                    len: Length(0),
377                })?;
378                Ok(())
379            }
380            PrimitiveValue::U8(_)
381            | PrimitiveValue::I16(_)
382            | PrimitiveValue::U16(_)
383            | PrimitiveValue::I32(_)
384            | PrimitiveValue::U32(_)
385            | PrimitiveValue::I64(_)
386            | PrimitiveValue::U64(_)
387            | PrimitiveValue::F32(_)
388            | PrimitiveValue::F64(_) => {
389                let textual_value = value.to_str();
390                self.encode_element_header(DataElementHeader {
391                    tag: de.tag,
392                    vr: de.vr,
393                    len: Length(even_len(textual_value.len() as u32)),
394                })?;
395
396                write!(self.to, "{textual_value}").context(WriteValueDataSnafu {
397                    position: self.bytes_written,
398                })?;
399                let len = if textual_value.len() % 2 == 1 {
400                    self.to.write_all(b" ").context(WriteValueDataSnafu {
401                        position: self.bytes_written,
402                    })?;
403                    textual_value.len() as u64 + 1
404                } else {
405                    textual_value.len() as u64
406                };
407                self.bytes_written += len;
408                Ok(())
409            }
410            PrimitiveValue::Date(_)
411            | PrimitiveValue::DateTime(_)
412            | PrimitiveValue::Time(_)
413            | PrimitiveValue::Tags(_)
414            | PrimitiveValue::Strs(_)
415            | PrimitiveValue::Str(_) => unreachable!(),
416        }
417    }
418
419    /// Flush the inner writer
420    pub fn flush(&mut self) -> std::io::Result<()> {
421        self.to.flush()
422    }
423}
424
425#[inline]
426fn even_len(l: u32) -> u32 {
427    (l + 1) & !1
428}
429
430#[cfg(test)]
431mod tests {
432    use dcmnorm_core::{
433        dicom_value, value::DicomTime, DataElement, DataElementHeader, DicomValue, Length,
434        PrimitiveValue, Tag, VR,
435    };
436    use dcmnorm_encoding::{
437        encode::{explicit_le::ExplicitVRLittleEndianEncoder, EncoderFor},
438        text::{SpecificCharacterSet, TextCodec},
439    };
440
441    use super::StatefulEncoder;
442
443    /// Odd lengthed values convert to tokens with even padding (PN)
444    #[test]
445    fn encode_odd_length_element_pn() {
446        let element = DataElement::new(
447            Tag(0x0010, 0x0010),
448            VR::PN,
449            DicomValue::new(dicom_value!(Strs, ["Dall^John"])),
450        );
451
452        let mut out: Vec<_> = Vec::new();
453
454        {
455            let mut encoder = StatefulEncoder::new(
456                &mut out,
457                EncoderFor::new(ExplicitVRLittleEndianEncoder::default()),
458                SpecificCharacterSet::default(),
459            );
460
461            encoder
462                .encode_primitive_element(element.header(), element.value().primitive().unwrap())
463                .unwrap();
464        }
465
466        assert_eq!(
467            &out,
468            &[
469                0x10, 0x00, 0x10, 0x00, // tag
470                b'P', b'N', // VR
471                0x0A, 0x00, // length
472                // ---------- value ----------
473                b'D', b'a', b'l', b'l', b'^', b'J', b'o', b'h', b'n', b' ',
474            ],
475        )
476    }
477
478    /// Odd lengthed values are encoded with even padding (bytes)
479    #[test]
480    fn encode_odd_length_element_bytes() {
481        let element = DataElement::new(
482            Tag(0x7FE0, 0x0010),
483            VR::OB,
484            DicomValue::new(vec![1; 9].into()),
485        );
486
487        let mut out: Vec<_> = Vec::new();
488
489        {
490            let mut encoder = StatefulEncoder::new(
491                &mut out,
492                EncoderFor::new(ExplicitVRLittleEndianEncoder::default()),
493                SpecificCharacterSet::default(),
494            );
495
496            encoder
497                .encode_primitive_element(element.header(), element.value().primitive().unwrap())
498                .unwrap();
499        }
500
501        assert_eq!(
502            &out,
503            &[
504                0xE0, 0x7F, 0x10, 0x00, // tag
505                b'O', b'B', // VR
506                0x00, 0x00, // reserved
507                0x0A, 0x00, 0x00, 0x00, // length
508                // ---------- value ----------
509                1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
510            ],
511        )
512    }
513
514    /// Odd lengthed values are encoded with even padding (UIDs)
515    #[test]
516    fn encode_odd_length_element_uid() {
517        let element = DataElement::new(
518            Tag(0x0000, 0x0002),
519            VR::UI,
520            DicomValue::new("1.2.840.10008.1.1".into()),
521        );
522
523        let mut out: Vec<_> = Vec::new();
524
525        {
526            let mut encoder = StatefulEncoder::new(
527                &mut out,
528                EncoderFor::new(ExplicitVRLittleEndianEncoder::default()),
529                SpecificCharacterSet::default(),
530            );
531
532            encoder
533                .encode_primitive_element(element.header(), element.value().primitive().unwrap())
534                .unwrap();
535        }
536
537        assert_eq!(
538            &out,
539            &[
540                // tag
541                0x00, 0x00, 0x02, 0x00, // VR
542                b'U', b'I', // length
543                0x12, 0x00, // length
544                // ---------- value ----------
545                b'1', b'.', b'2', b'.', b'8', b'4', b'0', b'.', b'1', b'0', b'0', b'0', b'8', b'.',
546                b'1', b'.', b'1', b'\0',
547            ],
548        )
549    }
550
551    /// Odd lengthed item values are encoded with even padding
552    #[test]
553    fn encode_odd_length_item_bytes() {
554        let mut out: Vec<_> = Vec::new();
555
556        {
557            let mut encoder = StatefulEncoder::new(
558                &mut out,
559                EncoderFor::new(ExplicitVRLittleEndianEncoder::default()),
560                SpecificCharacterSet::default(),
561            );
562
563            encoder.encode_item_header(9).unwrap();
564            encoder.write_bytes(&[5; 9]).unwrap();
565        }
566
567        assert_eq!(
568            &out,
569            &[
570                0xFE, 0xFF, 0x00, 0xE0, // tag (0xFFFE, 0xE000)
571                0x0A, 0x00, 0x00, 0x00, // length
572                // ---------- value ----------
573                5, 5, 5, 5, 5, 5, 5, 5, 5, 0,
574            ],
575        )
576    }
577
578    /// Odd lengthed textual values are encoded to even padding with a space
579    #[test]
580    fn encode_odd_length_text() {
581        let mut out: Vec<_> = Vec::new();
582
583        {
584            let mut encoder = StatefulEncoder::new(
585                &mut out,
586                EncoderFor::new(ExplicitVRLittleEndianEncoder::default()),
587                SpecificCharacterSet::default(),
588            );
589
590            let tm = DicomTime::from_hms_micro(23, 57, 59, 999_999).unwrap();
591
592            encoder
593                .encode_primitive_element(
594                    &DataElementHeader::new(Tag(0x0008, 0x0030), VR::TM, Length(14)),
595                    &PrimitiveValue::from(tm),
596                )
597                .unwrap();
598        }
599
600        assert_eq!(
601            &out,
602            &[
603                0x08, 0x00, 0x30, 0x00, // tag (0x0008, 0x0030)
604                b'T', b'M', // VR
605                0x0E, 0x00, // length
606                // ---------- value ----------
607                b'2', b'3', b'5', b'7', b'5', b'9', // time
608                b'.', b'9', b'9', b'9', b'9', b'9', b'9', // second fragment
609                b' ', // padding
610            ],
611        )
612    }
613
614    #[test]
615    fn test_even_len() {
616        use super::even_len;
617
618        assert_eq!(even_len(0), 0);
619        assert_eq!(even_len(1), 2);
620        assert_eq!(even_len(2), 2);
621        assert_eq!(even_len(3), 4);
622        assert_eq!(even_len(4), 4);
623        assert_eq!(even_len(5), 6);
624        assert_eq!(even_len(6), 6);
625        assert_eq!(even_len(0xFFFF_FFFD), 0xFFFF_FFFE);
626    }
627
628    /// Test that the stateful encoder updates
629    /// the active character set after writing a Specific Character Set element
630    /// with a supported text encoding.
631    #[test]
632    fn update_character_set() {
633        const GT: &[u8; 54] = &[
634            // Tag: (0008,0005) Specific Character Set
635            0x08, 0x00, 0x05, 0x00, // VR: CS
636            b'C', b'S', // Length: 10
637            0x0a, 0x00, // Value: "ISO_IR 192"
638            b'I', b'S', b'O', b'_', b'I', b'R', b' ', b'1', b'9', b'2',
639            // Tag: (0010,0010) Patient Name
640            0x10, 0x00, 0x10, 0x00, // VR: PN
641            b'P', b'N', // Length: 28
642            0x1c, 0x00, // Value: "Иванков^Андрей "
643            0xd0, 0x98, 0xd0, 0xb2, 0xd0, 0xb0, 0xd0, 0xbd, 0xd0, 0xba, 0xd0, 0xbe, 0xd0, 0xb2,
644            0x5e, 0xd0, 0x90, 0xd0, 0xbd, 0xd0, 0xb4, 0xd1, 0x80, 0xd0, 0xb5, 0xd0, 0xb9, b' ',
645        ];
646
647        let mut sink = Vec::with_capacity(GT.len());
648
649        let mut encoder = StatefulEncoder::new(
650            &mut sink,
651            EncoderFor::new(ExplicitVRLittleEndianEncoder::default()),
652            SpecificCharacterSet::default(),
653        );
654
655        // encode specific character set
656        let scs = DataElementHeader {
657            tag: Tag(0x0008, 0x0005),
658            vr: VR::CS,
659            len: Length(10),
660        };
661        let scs_value = PrimitiveValue::from("ISO_IR 192");
662
663        encoder.encode_primitive_element(&scs, &scs_value).unwrap();
664
665        // check that the encoder has changed
666        assert_eq!(encoder.text.name(), "ISO_IR 192");
667
668        // now encode something non-ASCII
669        let pn = DataElementHeader {
670            tag: Tag(0x0010, 0x0010),
671            vr: VR::PN,
672            len: Length(28),
673        };
674        let pn_value = PrimitiveValue::from("Иванков^Андрей ");
675        encoder.encode_primitive_element(&pn, &pn_value).unwrap();
676
677        // test all output against ground truth
678        assert_eq!(&sink, GT);
679    }
680}