Skip to main content

dcmnorm_parser/dataset/
write.rs

1//! Module for the data set writer
2//!
3//! This module contains a mid-level abstraction for printing DICOM data sets
4//! sequentially.
5//! The [`DataSetWriter`] receives data tokens to be encoded and written
6//! to a writer.
7//! In this process, the writer will also adapt values
8//! to the necessary DICOM encoding rules.
9use crate::dataset::{DataToken, SeqTokenType};
10use crate::stateful::encode::StatefulEncoder;
11use dcmnorm_core::header::Header;
12use dcmnorm_core::{DataElementHeader, Length, Tag, VR};
13use dcmnorm_encoding::encode::EncodeTo;
14use dcmnorm_encoding::text::SpecificCharacterSet;
15use dcmnorm_encoding::transfer_syntax::DynEncoder;
16use dcmnorm_encoding::TransferSyntax;
17use snafu::{Backtrace, OptionExt, ResultExt, Snafu};
18use std::io::Write;
19
20#[derive(Debug, Snafu)]
21#[non_exhaustive]
22pub enum Error {
23    /// Unsupported transfer syntax for encoding
24    #[snafu(display("Unsupported transfer syntax {} ({})", ts_uid, ts_alias))]
25    UnsupportedTransferSyntax {
26        ts_uid: &'static str,
27        ts_alias: &'static str,
28        backtrace: Backtrace,
29    },
30    /// Character set known, but not supported
31    #[snafu(display("Unsupported character set {:?}", charset))]
32    UnsupportedCharacterSet {
33        charset: SpecificCharacterSet,
34        backtrace: Backtrace,
35    },
36    /// An element value token appeared without an introducing element header
37    #[snafu(display("Unexpected token {:?} without element header", token))]
38    UnexpectedToken {
39        token: DataToken,
40        backtrace: Backtrace,
41    },
42    #[snafu(display("Could not write element header tagged {}", tag))]
43    WriteHeader {
44        tag: Tag,
45        #[snafu(backtrace)]
46        source: crate::stateful::encode::Error,
47    },
48    #[snafu(display("Could not write item header"))]
49    WriteItemHeader {
50        #[snafu(backtrace)]
51        source: crate::stateful::encode::Error,
52    },
53
54    #[snafu(display("Could not write sequence delimiter"))]
55    WriteSequenceDelimiter {
56        #[snafu(backtrace)]
57        source: crate::stateful::encode::Error,
58    },
59
60    #[snafu(display("Could not write item delimiter"))]
61    WriteItemDelimiter {
62        #[snafu(backtrace)]
63        source: crate::stateful::encode::Error,
64    },
65
66    #[snafu(display("Could not write element value"))]
67    WriteValue {
68        #[snafu(backtrace)]
69        source: crate::stateful::encode::Error,
70    },
71    #[snafu(display("Could not flush buffer"))]
72    FlushBuffer {
73        source: std::io::Error,
74        backtrace: Backtrace,
75    },
76}
77
78pub type Result<T> = std::result::Result<T, Error>;
79
80/// A writer-specific token representing a sequence or item start.
81#[derive(Debug)]
82struct SeqToken {
83    /// Whether it is the start of a sequence or the start of an item.
84    typ: SeqTokenType,
85    /// The length of the value, as indicated by the starting element,
86    /// can be unknown.
87    len: Length,
88}
89
90/// A strategy for writing data set sequences and items
91/// when the writer encounters a sequence or item with explicit (defined) length.
92#[derive(Debug, Default, Copy, Clone, Eq, Hash, PartialEq)]
93#[non_exhaustive]
94pub enum ExplicitLengthSqItemStrategy {
95    /// All explicit length items and sequences
96    /// are converted to [`Length::UNDEFINED`].
97    ///
98    /// This means that even if you create or read a data set with explicit length
99    /// items / sequences, the resulting output of the writer will have undefined
100    /// lengths for all items and sequences,
101    /// expect for encapsulated pixel data fragments.
102    ///
103    /// This is, as of yet, the safest way to handle
104    /// explicit length items and sequences, and thus the default behavior.
105    #[default]
106    SetUndefined,
107    /// Explicit length items and sequences are written without any change,
108    /// left as they were encountered in the data set.
109    ///
110    /// Item and sequence lengths in the data set will not be recalculated!
111    /// As a consequence, if the content of a sequence or item with explicit length
112    /// is manipulated after it was created or read from a source
113    /// (thus possibly changing its real size),
114    /// this strategy will not update the length of that sequence or item,
115    /// producing invalid output.
116    NoChange,
117    // TODO(#692) Explicit length items and sequences could as well be recalculated, as is the behavior
118    // of some DICOM libraries. Because recalculation is expensive and leaving sequences and items
119    // with length undefined is DICOM compliant, this strategy is not implemented yet.
120    // Recalculate,
121}
122
123/// The set of options for the data set writer.
124#[derive(Debug, Default, Copy, Clone, Eq, Hash, PartialEq)]
125#[non_exhaustive]
126pub struct DataSetWriterOptions {
127    /// What to do with sequences and items with explicit lengths.
128    pub explicit_length_sq_item_strategy: ExplicitLengthSqItemStrategy,
129}
130
131impl DataSetWriterOptions {
132    /// Replace the write strategy for explicit length sequences and items of the options.
133    pub fn explicit_length_sq_item_strategy(
134        mut self,
135        exp_length: ExplicitLengthSqItemStrategy,
136    ) -> Self {
137        self.explicit_length_sq_item_strategy = exp_length;
138        self
139    }
140}
141
142/// A stateful device for printing a DICOM data set in sequential order.
143/// This is analogous to the `DatasetReader` type for converting data
144/// set tokens to bytes.
145#[derive(Debug)]
146pub struct DataSetWriter<W, E, T = SpecificCharacterSet> {
147    printer: StatefulEncoder<W, E, T>,
148    seq_tokens: Vec<SeqToken>,
149    last_de: Option<DataElementHeader>,
150    options: DataSetWriterOptions,
151}
152
153impl<'w, W: 'w> DataSetWriter<W, DynEncoder<'w, W>>
154where
155    W: Write,
156{
157    /// Create a new data set writer
158    /// with the given transfer syntax specifier.
159    ///
160    /// Uses the default [DataSetWriterOptions] for the writer.
161    pub fn with_ts(to: W, ts: &TransferSyntax) -> Result<Self> {
162        Self::with_ts_options(to, ts, DataSetWriterOptions::default())
163    }
164
165    /// Create a new data set writer
166    /// with the given transfer syntax specifier
167    /// and the specific character.
168    ///
169    /// Uses the default [DataSetWriterOptions] for the writer.
170    pub fn with_ts_cs(to: W, ts: &TransferSyntax, charset: SpecificCharacterSet) -> Result<Self> {
171        Self::with_ts_cs_options(to, ts, charset, DataSetWriterOptions::default())
172    }
173
174    /// Create a new data set writer
175    /// with the given transfer syntax specifier
176    /// and options.
177    pub fn with_ts_options(
178        to: W,
179        ts: &TransferSyntax,
180        options: DataSetWriterOptions,
181    ) -> Result<Self> {
182        let encoder = ts.encoder_for().context(UnsupportedTransferSyntaxSnafu {
183            ts_uid: ts.uid(),
184            ts_alias: ts.name(),
185        })?;
186        Ok(DataSetWriter::new_with_codec_options(
187            to,
188            encoder,
189            SpecificCharacterSet::default(),
190            options,
191        ))
192    }
193
194    /// Create a new data set writer
195    /// with the given transfer syntax specifier,
196    /// specific character set and options.
197    pub fn with_ts_cs_options(
198        to: W,
199        ts: &TransferSyntax,
200        charset: SpecificCharacterSet,
201        options: DataSetWriterOptions,
202    ) -> Result<Self> {
203        let encoder = ts.encoder_for().context(UnsupportedTransferSyntaxSnafu {
204            ts_uid: ts.uid(),
205            ts_alias: ts.name(),
206        })?;
207        Ok(DataSetWriter::new_with_codec_options(
208            to, encoder, charset, options,
209        ))
210    }
211}
212
213impl<W, E> DataSetWriter<W, E> {
214    /// Create a new dataset writer with the given encoder,
215    /// which prints to the given writer.
216    #[inline]
217    pub fn new(to: W, encoder: E) -> Self {
218        DataSetWriter::new_with_options(to, encoder, DataSetWriterOptions::default())
219    }
220
221    /// Create a new dataset writer with the given encoder,
222    /// which prints to the given writer.
223    #[inline]
224    pub fn new_with_options(to: W, encoder: E, options: DataSetWriterOptions) -> Self {
225        DataSetWriter {
226            printer: StatefulEncoder::new(to, encoder, SpecificCharacterSet::default()),
227            seq_tokens: Vec::new(),
228            last_de: None,
229            options,
230        }
231    }
232}
233
234impl<W, E, T> DataSetWriter<W, E, T> {
235    /// Create a new dataset writer with the given encoder and text codec,
236    /// which prints to the given writer.
237    #[inline]
238    pub fn new_with_codec(to: W, encoder: E, text: T) -> Self {
239        DataSetWriter::new_with_codec_options(to, encoder, text, DataSetWriterOptions::default())
240    }
241
242    /// Create a new dataset writer with the given encoder and text codec,
243    /// which prints to the given writer.
244    #[inline]
245    pub fn new_with_codec_options(
246        to: W,
247        encoder: E,
248        text: T,
249        options: DataSetWriterOptions,
250    ) -> Self {
251        DataSetWriter {
252            printer: StatefulEncoder::new(to, encoder, text),
253            seq_tokens: Vec::new(),
254            last_de: None,
255            options,
256        }
257    }
258}
259
260impl<W, E> DataSetWriter<W, E>
261where
262    W: Write,
263    E: EncodeTo<W>,
264{
265    /// Feed the given sequence of tokens which are part of the same data set.
266    #[inline]
267    pub fn write_sequence<I>(&mut self, tokens: I) -> Result<()>
268    where
269        I: IntoIterator<Item = DataToken>,
270    {
271        for token in tokens {
272            self.write(token)?;
273        }
274
275        Ok(())
276    }
277
278    /// Feed the given data set token for writing the data set.
279    pub fn write(&mut self, token: DataToken) -> Result<()> {
280        match token {
281            DataToken::SequenceStart { tag, len, .. } => {
282                match self.options.explicit_length_sq_item_strategy {
283                    ExplicitLengthSqItemStrategy::SetUndefined => {
284                        self.seq_tokens.push(SeqToken {
285                            typ: SeqTokenType::Sequence,
286                            len: Length::UNDEFINED,
287                        });
288                        self.write_impl(&DataToken::SequenceStart {
289                            tag,
290                            len: Length::UNDEFINED,
291                        })?;
292                    }
293                    ExplicitLengthSqItemStrategy::NoChange => {
294                        self.seq_tokens.push(SeqToken {
295                            typ: SeqTokenType::Sequence,
296                            len,
297                        });
298                        self.write_impl(&token)?;
299                    }
300                }
301                Ok(())
302            }
303            DataToken::ItemStart { len } => {
304                match self.options.explicit_length_sq_item_strategy {
305                    ExplicitLengthSqItemStrategy::SetUndefined => {
306                        // only set undefined length in dataset sequence items
307                        // (not pixel data fragments, those always have an explicit length)
308                        let len = if self
309                            .last_de
310                            .map(|h| h.is_encapsulated_pixeldata())
311                            .unwrap_or(false)
312                        {
313                            len
314                        } else {
315                            Length::UNDEFINED
316                        };
317                        self.seq_tokens.push(SeqToken {
318                            typ: SeqTokenType::Item,
319                            len,
320                        });
321                        self.write_impl(&DataToken::ItemStart { len })?;
322                    }
323                    ExplicitLengthSqItemStrategy::NoChange => {
324                        self.seq_tokens.push(SeqToken {
325                            typ: SeqTokenType::Item,
326                            len,
327                        });
328                        self.write_impl(&token)?;
329                    }
330                }
331                Ok(())
332            }
333            DataToken::ItemEnd => {
334                // only write if it's an unknown length item
335                if let Some(seq_start) = self.seq_tokens.pop() {
336                    if seq_start.typ == SeqTokenType::Item && seq_start.len.is_undefined() {
337                        self.write_impl(&token)?;
338                    }
339                }
340                Ok(())
341            }
342            DataToken::SequenceEnd => {
343                // only write if it's an unknown length sequence
344                if let Some(seq_start) = self.seq_tokens.pop() {
345                    if seq_start.typ == SeqTokenType::Sequence && seq_start.len.is_undefined() {
346                        self.write_impl(&token)?;
347                    }
348                }
349                Ok(())
350            }
351            DataToken::ElementHeader(de) => {
352                // save the header for later
353                self.last_de = Some(de);
354
355                // postpone writing the header until the value token is given
356                Ok(())
357            }
358            token @ DataToken::PixelSequenceStart => {
359                // save the header so we know that
360                // we're in encapsulated pixel data
361                self.last_de = Some(DataElementHeader {
362                    tag: Tag(0x7fe0, 0x0010),
363                    vr: VR::OB,
364                    len: Length::UNDEFINED,
365                });
366
367                self.seq_tokens.push(SeqToken {
368                    typ: SeqTokenType::Sequence,
369                    len: Length::UNDEFINED,
370                });
371                self.write_impl(&token)
372            }
373            token @ DataToken::ItemValue(_)
374            | token @ DataToken::PrimitiveValue(_)
375            | token @ DataToken::OffsetTable(_) => self.write_impl(&token),
376        }
377    }
378
379    /// Write a whole primitive element from a borrowed value - equivalent to feeding
380    /// `DataToken::ElementHeader(header)` then `DataToken::PrimitiveValue(value)`, without
381    /// requiring an owned (cloned) value. Writing a native multi-frame object through the token
382    /// API otherwise deep-copies its entire PixelData just to serialize it.
383    pub fn write_primitive_element(
384        &mut self,
385        header: DataElementHeader,
386        value: &dcmnorm_core::value::PrimitiveValue,
387    ) -> Result<()> {
388        self.printer
389            .encode_primitive_element(&header, value)
390            .context(WriteValueSnafu)?;
391        self.last_de = None;
392        Ok(())
393    }
394
395    /// Write an item's raw value (e.g. an encapsulated pixel data fragment) from a borrowed
396    /// slice - equivalent to feeding `DataToken::ItemValue(data.to_vec())` without the copy.
397    pub fn write_item_value(&mut self, data: &[u8]) -> Result<()> {
398        self.printer.write_bytes(data).context(WriteValueSnafu)
399    }
400
401    /// Write an element header directly without buffering its value - for callers streaming a
402    /// large defined-length value (such as native PixelData) via [`Self::write_raw_bytes`].
403    pub fn write_element_header(&mut self, header: DataElementHeader) -> Result<()> {
404        self.printer
405            .encode_element_header(header)
406            .context(WriteHeaderSnafu { tag: header.tag })?;
407        self.last_de = None;
408        Ok(())
409    }
410
411    /// Write raw, already-encoded bytes directly to the underlying writer without padding.
412    pub fn write_raw_bytes(&mut self, data: &[u8]) -> Result<()> {
413        self.printer.write_raw_bytes(data).context(WriteValueSnafu)
414    }
415
416    /// Number of bytes written to the data set stream so far.
417    pub fn bytes_written(&self) -> u64 {
418        self.printer.bytes_written()
419    }
420
421    fn write_impl(&mut self, token: &DataToken) -> Result<()> {
422        match token {
423            DataToken::ElementHeader(header) => {
424                self.printer
425                    .encode_element_header(*header)
426                    .context(WriteHeaderSnafu { tag: header.tag })?;
427            }
428            DataToken::SequenceStart { tag, len } => {
429                self.printer
430                    .encode_element_header(DataElementHeader::new(*tag, VR::SQ, *len))
431                    .context(WriteHeaderSnafu { tag: *tag })?;
432            }
433            DataToken::PixelSequenceStart => {
434                let tag = Tag(0x7fe0, 0x0010);
435                self.printer
436                    .encode_element_header(DataElementHeader::new(tag, VR::OB, Length::UNDEFINED))
437                    .context(WriteHeaderSnafu { tag })?;
438            }
439            DataToken::SequenceEnd => {
440                self.printer
441                    .encode_sequence_delimiter()
442                    .context(WriteSequenceDelimiterSnafu)?;
443            }
444            DataToken::ItemStart { len } => {
445                self.printer
446                    .encode_item_header(len.0)
447                    .context(WriteItemHeaderSnafu)?;
448            }
449            DataToken::ItemEnd => {
450                self.printer
451                    .encode_item_delimiter()
452                    .context(WriteItemDelimiterSnafu)?;
453            }
454            DataToken::PrimitiveValue(ref value) => {
455                let last_de = self.last_de.take().with_context(|| UnexpectedTokenSnafu {
456                    token: token.clone(),
457                })?;
458
459                self.printer
460                    .encode_primitive_element(&last_de, value)
461                    .context(WriteValueSnafu)?;
462                self.last_de = None;
463            }
464            DataToken::OffsetTable(table) => {
465                self.printer
466                    .encode_offset_table(table)
467                    .context(WriteValueSnafu)?;
468            }
469            DataToken::ItemValue(data) => {
470                self.printer.write_bytes(data).context(WriteValueSnafu)?;
471            }
472        }
473        Ok(())
474    }
475
476    /// Flush the inner writer
477    pub fn flush(&mut self) -> Result<()> {
478        self.printer.flush().context(FlushBufferSnafu)
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::super::DataToken;
485    use super::{DataSetWriter, DataSetWriterOptions, ExplicitLengthSqItemStrategy};
486    use dcmnorm_core::{
487        header::{DataElementHeader, Length},
488        value::PrimitiveValue,
489        Tag, VR,
490    };
491    use dcmnorm_encoding::encode::{explicit_le::ExplicitVRLittleEndianEncoder, EncoderFor};
492
493    fn validate_dataset_writer<I>(
494        tokens: I,
495        ground_truth: &[u8],
496        writer_options: DataSetWriterOptions,
497    ) where
498        I: IntoIterator<Item = DataToken>,
499    {
500        let mut raw_out: Vec<u8> = vec![];
501        let encoder = EncoderFor::new(ExplicitVRLittleEndianEncoder::default());
502        let mut dset_writer =
503            DataSetWriter::new_with_options(&mut raw_out, encoder, writer_options);
504
505        dset_writer.write_sequence(tokens).unwrap();
506
507        assert_eq!(raw_out, ground_truth);
508    }
509
510    #[test]
511    fn write_sequence_explicit() {
512        let tokens = vec![
513            DataToken::SequenceStart {
514                tag: Tag(0x0018, 0x6011),
515                len: Length(46),
516            },
517            DataToken::ItemStart { len: Length(20) },
518            DataToken::ElementHeader(DataElementHeader {
519                tag: Tag(0x0018, 0x6012),
520                vr: VR::US,
521                len: Length(2),
522            }),
523            DataToken::PrimitiveValue(PrimitiveValue::U16([1].as_ref().into())),
524            DataToken::ElementHeader(DataElementHeader {
525                tag: Tag(0x0018, 0x6014),
526                vr: VR::US,
527                len: Length(2),
528            }),
529            DataToken::PrimitiveValue(PrimitiveValue::U16([2].as_ref().into())),
530            DataToken::ItemEnd,
531            DataToken::ItemStart { len: Length(10) },
532            DataToken::ElementHeader(DataElementHeader {
533                tag: Tag(0x0018, 0x6012),
534                vr: VR::US,
535                len: Length(2),
536            }),
537            DataToken::PrimitiveValue(PrimitiveValue::U16([4].as_ref().into())),
538            DataToken::ItemEnd,
539            DataToken::SequenceEnd,
540            DataToken::ElementHeader(DataElementHeader {
541                tag: Tag(0x0020, 0x4000),
542                vr: VR::LT,
543                len: Length(4),
544            }),
545            DataToken::PrimitiveValue(PrimitiveValue::Str("TEST".into())),
546        ];
547
548        #[rustfmt::skip]
549        static GROUND_TRUTH_LENGTH_UNDEFINED: &[u8] = &[
550            0x18, 0x00, 0x11, 0x60, // sequence tag: (0018,6011) SequenceOfUltrasoundRegions
551            b'S', b'Q', // VR 
552            0x00, 0x00, // reserved
553            0xff, 0xff, 0xff, 0xff, // seq length: UNDEFINED
554            // -- 12 --
555            0xfe, 0xff, 0x00, 0xe0, // item start tag
556            0xff, 0xff, 0xff, 0xff, // item length: UNDEFINED
557            // -- 20 --
558            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x01, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 1
559            // -- 30 --
560            0x18, 0x00, 0x14, 0x60, b'U', b'S', 0x02, 0x00, 0x02, 0x00, // (0018, 6012) RegionDataType, len = 2, value = 2
561            // -- 40 --
562            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
563            0xfe, 0xff, 0x00, 0xe0, // item start tag
564            0xff, 0xff, 0xff, 0xff, // item length: UNDEFINED
565            // -- 48 --
566            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x04, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 4
567            // -- 58 --
568            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
569            0xfe, 0xff, 0xdd, 0xe0, 0x00, 0x00, 0x00, 0x00, // sequence end
570            0x20, 0x00, 0x00, 0x40, b'L', b'T', 0x04, 0x00, // (0020,4000) ImageComments, len = 4  
571            b'T', b'E', b'S', b'T', // value = "TEST"
572        ];
573
574        #[rustfmt::skip]
575        static GROUND_TRUTH_NO_CHANGE: &[u8] = &[
576            0x18, 0x00, 0x11, 0x60, // sequence tag: (0018,6011) SequenceOfUltrasoundRegions
577            b'S', b'Q', // VR 
578            0x00, 0x00, // reserved
579            0x2e, 0x00, 0x00, 0x00, // length: 28 + 18 = 46 (#= 2)
580            // -- 12 --
581            0xfe, 0xff, 0x00, 0xe0, // item start tag
582            0x14, 0x00, 0x00, 0x00, // item length: 20 (#= 2)
583            // -- 20 --
584            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x01, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 1
585            // -- 30 --
586            0x18, 0x00, 0x14, 0x60, b'U', b'S', 0x02, 0x00, 0x02, 0x00, // (0018, 6012) RegionDataType, len = 2, value = 2
587            // -- 40 --
588            0xfe, 0xff, 0x00, 0xe0, // item start tag
589            0x0a, 0x00, 0x00, 0x00, // item length: 10 (#= 1)
590            // -- 48 --
591            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x04, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 4
592            // -- 58 --
593            0x20, 0x00, 0x00, 0x40, b'L', b'T', 0x04, 0x00, // (0020,4000) ImageComments, len = 4  
594            b'T', b'E', b'S', b'T', // value = "TEST"
595        ];
596
597        let no_change = DataSetWriterOptions {
598            explicit_length_sq_item_strategy: ExplicitLengthSqItemStrategy::NoChange,
599        };
600        validate_dataset_writer(tokens.clone(), GROUND_TRUTH_NO_CHANGE, no_change);
601        validate_dataset_writer(
602            tokens,
603            GROUND_TRUTH_LENGTH_UNDEFINED,
604            DataSetWriterOptions::default(),
605        );
606    }
607
608    #[test]
609    fn write_element_overrides_len() {
610        let tokens = vec![
611            DataToken::ElementHeader(DataElementHeader {
612                // Specific Character Set (0008,0005)
613                tag: Tag(0x0008, 0x0005),
614                vr: VR::CS,
615                len: Length(10),
616            }),
617            DataToken::PrimitiveValue(PrimitiveValue::from("ISO_IR 100")),
618            DataToken::ElementHeader(DataElementHeader {
619                // Referring Physician's Name (0008,0090)
620                tag: Tag(0x0008, 0x0090),
621                vr: VR::PN,
622                // deliberately incorrect length
623                len: Length("Simões^João".len() as u32),
624            }),
625            DataToken::PrimitiveValue(PrimitiveValue::from("Simões^João")),
626        ];
627
628        #[rustfmt::skip]
629        static GROUND_TRUTH: &[u8] = &[
630            // Specific Character Set (0008,0005)
631            0x08, 0x00, 0x05, 0x00, //
632            b'C', b'S', // VR
633            0x0a, 0x00, // length: 10
634            b'I', b'S', b'O', b'_', b'I', b'R', b' ', b'1', b'0', b'0', // value = "ISO_IR 100"
635            // Referring Physician's Name (0008,0090)
636            0x08, 0x00, 0x90, 0x00, //
637            b'P', b'N', // VR
638            0x0c, 0x00, // length: 12
639            // value = "Simões^João "
640            b'S', b'i', b'm', 0xF5, b'e', b's', b'^', b'J', b'o', 0xE3, b'o', b' '
641        ];
642        validate_dataset_writer(tokens, GROUND_TRUTH, DataSetWriterOptions::default());
643    }
644
645    #[test]
646    fn write_sequence_implicit() {
647        let tokens = vec![
648            DataToken::SequenceStart {
649                tag: Tag(0x0018, 0x6011),
650                len: Length::UNDEFINED,
651            },
652            DataToken::ItemStart {
653                len: Length::UNDEFINED,
654            },
655            DataToken::ElementHeader(DataElementHeader {
656                tag: Tag(0x0018, 0x6012),
657                vr: VR::US,
658                len: Length(2),
659            }),
660            DataToken::PrimitiveValue(PrimitiveValue::U16([1].as_ref().into())),
661            DataToken::ElementHeader(DataElementHeader {
662                tag: Tag(0x0018, 0x6014),
663                vr: VR::US,
664                len: Length(2),
665            }),
666            DataToken::PrimitiveValue(PrimitiveValue::U16([2].as_ref().into())),
667            DataToken::ItemEnd,
668            DataToken::ItemStart {
669                len: Length::UNDEFINED,
670            },
671            DataToken::ElementHeader(DataElementHeader {
672                tag: Tag(0x0018, 0x6012),
673                vr: VR::US,
674                len: Length(2),
675            }),
676            DataToken::PrimitiveValue(PrimitiveValue::U16([4].as_ref().into())),
677            DataToken::ItemEnd,
678            DataToken::SequenceEnd,
679            DataToken::ElementHeader(DataElementHeader {
680                tag: Tag(0x0020, 0x4000),
681                vr: VR::LT,
682                len: Length(4),
683            }),
684            DataToken::PrimitiveValue(PrimitiveValue::Str("TEST".into())),
685        ];
686
687        #[rustfmt::skip]
688        static GROUND_TRUTH: &[u8] = &[
689            0x18, 0x00, 0x11, 0x60, // sequence tag: (0018,6011) SequenceOfUltrasoundRegions
690            b'S', b'Q', // VR 
691            0x00, 0x00, // reserved
692            0xff, 0xff, 0xff, 0xff, // length: undefined
693            // -- 12 --
694            0xfe, 0xff, 0x00, 0xe0, // item start tag
695            0xff, 0xff, 0xff, 0xff, // item length: undefined
696            // -- 20 --
697            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x01, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 1
698            // -- 30 --
699            0x18, 0x00, 0x14, 0x60, b'U', b'S', 0x02, 0x00, 0x02, 0x00, // (0018, 6012) RegionDataType, len = 2, value = 2
700            // -- 40 --
701            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
702            // -- 48 --
703            0xfe, 0xff, 0x00, 0xe0, // item start tag
704            0xff, 0xff, 0xff, 0xff, // item length: undefined
705            // -- 56 --
706            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x04, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 4
707            // -- 66 --
708            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
709            // -- 74 --
710            0xfe, 0xff, 0xdd, 0xe0, 0x00, 0x00, 0x00, 0x00, // sequence end
711            // -- 82 --
712            0x20, 0x00, 0x00, 0x40, b'L', b'T', 0x04, 0x00, // (0020,4000) ImageComments, len = 4  
713            b'T', b'E', b'S', b'T', // value = "TEST"
714        ];
715
716        let no_change = DataSetWriterOptions {
717            explicit_length_sq_item_strategy: ExplicitLengthSqItemStrategy::NoChange,
718        };
719        validate_dataset_writer(tokens.clone(), GROUND_TRUTH, no_change);
720        validate_dataset_writer(tokens, GROUND_TRUTH, DataSetWriterOptions::default());
721    }
722
723    #[test]
724    fn write_sequence_explicit_with_implicit_item_len() {
725        let tokens = vec![
726            DataToken::SequenceStart {
727                tag: Tag(0x0018, 0x6011),
728                len: Length(60),
729            },
730            DataToken::ItemStart {
731                len: Length::UNDEFINED,
732            },
733            DataToken::ElementHeader(DataElementHeader {
734                tag: Tag(0x0018, 0x6012),
735                vr: VR::US,
736                len: Length(2),
737            }),
738            DataToken::PrimitiveValue(PrimitiveValue::U16([1].as_ref().into())),
739            DataToken::ElementHeader(DataElementHeader {
740                tag: Tag(0x0018, 0x6014),
741                vr: VR::US,
742                len: Length(2),
743            }),
744            DataToken::PrimitiveValue(PrimitiveValue::U16([2].as_ref().into())),
745            DataToken::ItemEnd,
746            DataToken::ItemStart {
747                len: Length::UNDEFINED,
748            },
749            DataToken::ElementHeader(DataElementHeader {
750                tag: Tag(0x0018, 0x6012),
751                vr: VR::US,
752                len: Length(2),
753            }),
754            DataToken::PrimitiveValue(PrimitiveValue::U16([4].as_ref().into())),
755            DataToken::ItemEnd,
756            DataToken::SequenceEnd,
757            DataToken::ElementHeader(DataElementHeader {
758                tag: Tag(0x0020, 0x4000),
759                vr: VR::LT,
760                len: Length(4),
761            }),
762            DataToken::PrimitiveValue(PrimitiveValue::Str("TEST".into())),
763        ];
764
765        #[rustfmt::skip]
766        static GROUND_TRUTH_LENGTH_UNDEFINED: &[u8] = &[
767            0x18, 0x00, 0x11, 0x60, // sequence tag: (0018,6011) SequenceOfUltrasoundRegions
768            b'S', b'Q', // VR 
769            0x00, 0x00, // reserved
770            0xff, 0xff, 0xff, 0xff, // length: UNDEFINED
771            0xfe, 0xff, 0x00, 0xe0, // item start tag
772            0xff, 0xff, 0xff, 0xff, // item length: undefined
773            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x01, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 1
774            0x18, 0x00, 0x14, 0x60, b'U', b'S', 0x02, 0x00, 0x02, 0x00, // (0018, 6012) RegionDataType, len = 2, value = 2
775            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
776            0xfe, 0xff, 0x00, 0xe0, // item start tag
777            0xff, 0xff, 0xff, 0xff, // item length: undefined
778            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x04, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 4
779            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
780            0xfe, 0xff, 0xdd, 0xe0, 0x00, 0x00, 0x00, 0x00, // sequence end
781            0x20, 0x00, 0x00, 0x40, b'L', b'T', 0x04, 0x00, // (0020,4000) ImageComments, len = 4  
782            b'T', b'E', b'S', b'T', // value = "TEST"
783        ];
784
785        #[rustfmt::skip]
786        static GROUND_TRUTH_NO_CHANGE: &[u8] = &[
787            0x18, 0x00, 0x11, 0x60, // sequence tag: (0018,6011) SequenceOfUltrasoundRegions
788            b'S', b'Q', // VR 
789            0x00, 0x00, // reserved
790            0x3c, 0x00, 0x00, 0x00, // length: 60
791            // -- 12 --
792            0xfe, 0xff, 0x00, 0xe0, // item start tag
793            0xff, 0xff, 0xff, 0xff, // item length: undefined
794            // -- 20 --
795            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x01, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 1
796            // -- 30 --
797            0x18, 0x00, 0x14, 0x60, b'U', b'S', 0x02, 0x00, 0x02, 0x00, // (0018, 6012) RegionDataType, len = 2, value = 2
798            // -- 40 --
799            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
800            // -- 48 --
801            0xfe, 0xff, 0x00, 0xe0, // item start tag
802            0xff, 0xff, 0xff, 0xff, // item length: undefined
803            // -- 56 --
804            0x18, 0x00, 0x12, 0x60, b'U', b'S', 0x02, 0x00, 0x04, 0x00, // (0018, 6012) RegionSpatialformat, len = 2, value = 4
805            // -- 66 --
806            0xfe, 0xff, 0x0d, 0xe0, 0x00, 0x00, 0x00, 0x00, // item end
807            // -- 74 --
808            0x20, 0x00, 0x00, 0x40, b'L', b'T', 0x04, 0x00, // (0020,4000) ImageComments, len = 4  
809            b'T', b'E', b'S', b'T', // value = "TEST"
810        ];
811        let no_change = DataSetWriterOptions {
812            explicit_length_sq_item_strategy: ExplicitLengthSqItemStrategy::NoChange,
813        };
814
815        validate_dataset_writer(tokens.clone(), GROUND_TRUTH_NO_CHANGE, no_change);
816        validate_dataset_writer(
817            tokens,
818            GROUND_TRUTH_LENGTH_UNDEFINED,
819            DataSetWriterOptions::default(),
820        );
821    }
822
823    #[test]
824    fn write_encapsulated_pixeldata() {
825        let tokens = vec![
826            DataToken::PixelSequenceStart,
827            DataToken::ItemStart { len: Length(0) },
828            DataToken::ItemEnd,
829            DataToken::ItemStart { len: Length(32) },
830            DataToken::ItemValue(vec![0x99; 32]),
831            DataToken::ItemEnd,
832            DataToken::SequenceEnd,
833            DataToken::ElementHeader(DataElementHeader::new(
834                Tag(0xfffc, 0xfffc),
835                VR::OB,
836                Length(8),
837            )),
838            DataToken::PrimitiveValue(PrimitiveValue::U8([0x00; 8].as_ref().into())),
839        ];
840
841        // the encoded data should be equivalent because
842        // pixel data fragment items always have an explicit length (PS3.5 A.4)
843
844        #[rustfmt::skip]
845        static GROUND_TRUTH: &[u8] = &[
846            0xe0, 0x7f, 0x10, 0x00, // (7FE0, 0010) PixelData
847            b'O', b'B', // VR 
848            0x00, 0x00, // reserved
849            0xff, 0xff, 0xff, 0xff, // length: undefined
850            // -- 12 -- Basic offset table
851            0xfe, 0xff, 0x00, 0xe0, // item start tag
852            0x00, 0x00, 0x00, 0x00, // item length: 0
853            // -- 20 -- First fragment of pixel data
854            0xfe, 0xff, 0x00, 0xe0, // item start tag
855            0x20, 0x00, 0x00, 0x00, // item length: 32
856            // -- 28 -- Compressed Fragment
857            0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
858            0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
859            0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
860            0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
861            // -- 60 -- End of pixel data
862            0xfe, 0xff, 0xdd, 0xe0, // sequence end tag
863            0x00, 0x00, 0x00, 0x00,
864            // -- 68 -- padding
865            0xfc, 0xff, 0xfc, 0xff, // (fffc,fffc) DataSetTrailingPadding
866            b'O', b'B', // VR
867            0x00, 0x00, // reserved
868            0x08, 0x00, 0x00, 0x00, // length: 8
869            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
870        ];
871        let no_change = DataSetWriterOptions {
872            explicit_length_sq_item_strategy: ExplicitLengthSqItemStrategy::NoChange,
873        };
874        validate_dataset_writer(tokens.clone(), GROUND_TRUTH, no_change);
875        validate_dataset_writer(tokens, GROUND_TRUTH, DataSetWriterOptions::default());
876    }
877}