Skip to main content

dcmnorm_object/
file.rs

1//! Whole-file DICOM objects: a [`FileMetaTable`] plus an object (normally [`InMemDicomObject`]),
2//! and the [`OpenFileOptions`] builder for reading them from disk/a byte source.
3
4use std::fs::File;
5use std::io::{BufReader, Cursor, Read, Write};
6use std::path::Path;
7
8use dcmnorm_encoding::transfer_syntax::TransferSyntaxIndex;
9use dcmnorm_parser::dataset::read::DataSetReaderOptions;
10use dcmnorm_transcode::TransferSyntaxRegistry;
11
12use crate::error::{ReadError, WriteError};
13use crate::mem::InMemDicomObject;
14use crate::meta::{FileMetaTable, DICM_MAGIC, PREAMBLE_LEN};
15
16/// A DICOM object with its accompanying File Meta Information.
17#[derive(Debug, Clone, PartialEq)]
18pub struct FileDicomObject<T> {
19    pub(crate) meta: FileMetaTable,
20    pub(crate) object: T,
21}
22
23/// The default, in-memory DICOM file object type - a [`FileMetaTable`] plus an
24/// [`InMemDicomObject`].
25pub type DefaultDicomObject = FileDicomObject<InMemDicomObject>;
26
27impl<T> FileDicomObject<T> {
28    pub fn meta(&self) -> &FileMetaTable {
29        &self.meta
30    }
31
32    pub fn meta_mut(&mut self) -> &mut FileMetaTable {
33        &mut self.meta
34    }
35
36    pub fn into_inner(self) -> T {
37        self.object
38    }
39}
40
41impl std::ops::Deref for DefaultDicomObject {
42    type Target = InMemDicomObject;
43    fn deref(&self) -> &Self::Target {
44        &self.object
45    }
46}
47
48impl std::ops::DerefMut for DefaultDicomObject {
49    fn deref_mut(&mut self) -> &mut Self::Target {
50        &mut self.object
51    }
52}
53
54impl DefaultDicomObject {
55    /// Construct a new, empty object already carrying the given meta table.
56    pub fn new_empty_with_meta(meta: FileMetaTable) -> Self {
57        FileDicomObject {
58            meta,
59            object: InMemDicomObject::new_empty(),
60        }
61    }
62
63    /// Insert or replace a text element by tag and VR, creating it if absent.
64    pub fn put_str(
65        &mut self,
66        tag: dcmnorm_core::Tag,
67        vr: dcmnorm_core::VR,
68        value: impl Into<String>,
69    ) {
70        self.object.put_str(tag, vr, value);
71    }
72
73    /// Read a Part 10 file (128-byte preamble + "DICM" magic + meta group + data set) from
74    /// `path`.
75    pub fn open_file(path: impl AsRef<Path>) -> Result<Self, ReadError> {
76        let file = File::open(path.as_ref()).map_err(|source| ReadError::Io {
77            source,
78            context: "opening file",
79        })?;
80        Self::from_reader(BufReader::new(file))
81    }
82
83    /// Read a Part 10 object (128-byte preamble + "DICM" magic + meta group + data set) from
84    /// any [`Read`] source.
85    pub fn from_reader(mut source: impl Read) -> Result<Self, ReadError> {
86        let mut meta = FileMetaTable::read_from(&mut source)?.ok_or(ReadError::NotDicom)?;
87        let ts = meta
88            .transfer_syntax_ts()
89            .ok_or_else(|| ReadError::UnsupportedTransferSyntax {
90                uid: meta.transfer_syntax.clone(),
91            })?;
92        let object = InMemDicomObject::read_dataset_with_ts(source, ts)?;
93        backfill_media_storage_uids(&mut meta, &object);
94        Ok(FileDicomObject { meta, object })
95    }
96
97    /// Write this object as a full Part 10 file (preamble + "DICM" magic + meta group + data
98    /// set) to `path`.
99    pub fn write_to_file(&self, path: impl AsRef<Path>) -> Result<(), WriteError> {
100        let file = File::create(path.as_ref()).map_err(|source| WriteError::Io {
101            source,
102            context: "creating file",
103        })?;
104        self.write_all(&mut std::io::BufWriter::new(file))
105    }
106
107    /// Write this object as a full Part 10 stream (preamble + "DICM" magic + meta group + data
108    /// set) to any [`Write`] sink.
109    pub fn write_all(&self, mut to: impl Write) -> Result<(), WriteError> {
110        self.meta.write_to(&mut to)?;
111        let ts = TransferSyntaxRegistry
112            .get(crate::meta::io_util::trim_uid(&self.meta.transfer_syntax))
113            .ok_or_else(|| WriteError::UnsupportedTransferSyntax {
114                uid: self.meta.transfer_syntax.clone(),
115            })?;
116        self.object.write_dataset_with_ts(&mut to, ts)
117    }
118
119    /// Write this object as a full Part 10 stream, delegating `(7FE0,0010) PixelData` to
120    /// `write_pixel_data` at its exact tag-order position. The second argument passed to the
121    /// closure is the byte offset within `to` where the data set starts (right after the Part 10
122    /// preamble + File Meta Information).
123    pub fn write_all_with_pixel_data<W, E, F>(
124        &self,
125        mut to: W,
126        write_pixel_data: F,
127    ) -> Result<(), E>
128    where
129        W: Write,
130        E: From<WriteError>,
131        F: for<'w> FnOnce(
132            &mut dcmnorm_parser::dataset::DataSetWriter<
133                Box<dyn Write + 'w>,
134                dcmnorm_encoding::transfer_syntax::DynEncoder<'w, Box<dyn Write + 'w>>,
135            >,
136            u64,
137        ) -> Result<(), E>,
138    {
139        let mut meta_sink = CountingWriter {
140            inner: &mut to,
141            count: 0,
142        };
143        self.meta.write_to(&mut meta_sink)?;
144        let dataset_start = meta_sink.count;
145        let ts = TransferSyntaxRegistry
146            .get(crate::meta::io_util::trim_uid(&self.meta.transfer_syntax))
147            .ok_or_else(|| WriteError::UnsupportedTransferSyntax {
148                uid: self.meta.transfer_syntax.clone(),
149            })?;
150        self.object
151            .write_dataset_with_ts_and_pixel_data(&mut to, ts, |writer| {
152                write_pixel_data(writer, dataset_start)
153            })
154    }
155}
156
157/// Whether to require/skip the 128-byte preamble when opening a file.
158#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
159pub enum ReadPreamble {
160    #[default]
161    Auto,
162    Always,
163}
164
165/// Builder for reading a DICOM file with non-default options (an explicit preamble
166/// requirement, or an early-stop tag for partial/fast reads).
167#[derive(Debug, Clone, Default)]
168pub struct OpenFileOptions {
169    read_preamble: ReadPreamble,
170    read_until: Option<dcmnorm_core::Tag>,
171    flexible_decoding: bool,
172}
173
174impl OpenFileOptions {
175    pub fn new() -> Self {
176        Self::default()
177    }
178
179    pub fn read_preamble(mut self, mode: ReadPreamble) -> Self {
180        self.read_preamble = mode;
181        self
182    }
183
184    /// Stop reading as soon as an element with a tag greater than `tag` is encountered
185    /// (inclusive of `tag` itself) - a fast path for partial/filtered reads that don't need
186    /// the rest of the data set. Matches `dcmnorm`'s `--filter` CLI early-stop optimization.
187    pub fn read_until(mut self, tag: dcmnorm_core::Tag) -> Self {
188        self.read_until = Some(tag);
189        self
190    }
191
192    /// Detect from the data set itself whether a Little Endian file is encoded with explicit or
193    /// implicit VRs, instead of trusting its declared transfer syntax - for non-conformant files
194    /// that declare Explicit VR Little Endian but write Implicit VR (see
195    /// `DataSetReaderOptions::flexible_decoding`). Applies to [`Self::open_file`] and
196    /// [`Self::from_reader`]. Off by default.
197    pub fn flexible_decoding(mut self, flexible_decoding: bool) -> Self {
198        self.flexible_decoding = flexible_decoding;
199        self
200    }
201
202    pub fn open_file(self, path: impl AsRef<Path>) -> Result<DefaultDicomObject, ReadError> {
203        let file = File::open(path.as_ref()).map_err(|source| ReadError::Io {
204            source,
205            context: "opening file",
206        })?;
207        self.from_reader(BufReader::new(file))
208    }
209
210    pub fn from_reader(self, mut source: impl Read) -> Result<DefaultDicomObject, ReadError> {
211        let mut meta = self.read_meta(&mut source)?;
212        let ts = meta
213            .transfer_syntax_ts()
214            .ok_or_else(|| ReadError::UnsupportedTransferSyntax {
215                uid: meta.transfer_syntax.clone(),
216            })?;
217
218        let options = DataSetReaderOptions::default().flexible_decoding(self.flexible_decoding);
219        let object = if let Some(stop_tag) = self.read_until {
220            crate::mem::read_dataset_until(source, ts, stop_tag, options)?
221        } else {
222            InMemDicomObject::read_dataset_with_ts_options(source, ts, options)?
223        };
224        backfill_media_storage_uids(&mut meta, &object);
225        Ok(FileDicomObject { meta, object })
226    }
227
228    /// Read everything in `path` up to (not including) a native PixelData value, and report
229    /// where that value sits in the file instead of loading it - the building block for reading
230    /// one frame of a large multi-frame object (seek to it) without paying for all the others.
231    ///
232    /// Returns `Ok(None)` whenever this shortcut doesn't apply and the caller should do a full
233    /// read instead: an encapsulated or dataset-compressed (deflated) transfer syntax (no
234    /// stable byte offsets into native pixels), or no top-level, defined-length PixelData.
235    /// `read_until` is ignored. Elements after PixelData (trailing padding, digital signatures)
236    /// are not read.
237    pub fn open_file_until_pixel_data(
238        self,
239        path: impl AsRef<Path>,
240    ) -> Result<Option<(DefaultDicomObject, PixelDataValueLocation)>, ReadError> {
241        let file = File::open(path.as_ref()).map_err(|source| ReadError::Io {
242            source,
243            context: "opening file",
244        })?;
245        let mut source = CountingReader {
246            inner: BufReader::new(file),
247            count: 0,
248        };
249        let mut meta = self.read_meta(&mut source)?;
250        let ts = meta
251            .transfer_syntax_ts()
252            .ok_or_else(|| ReadError::UnsupportedTransferSyntax {
253                uid: meta.transfer_syntax.clone(),
254            })?;
255        if ts.is_encapsulated_pixel_data()
256            || !matches!(ts.codec(), dcmnorm_encoding::transfer_syntax::Codec::None)
257        {
258            return Ok(None);
259        }
260
261        let (object, header) = crate::mem::read_dataset_until_pixel_data_header(&mut source, ts)?;
262        let Some(header) = header else {
263            return Ok(None);
264        };
265        let Some(length) = header.len.get() else {
266            return Ok(None);
267        };
268        backfill_media_storage_uids(&mut meta, &object);
269        Ok(Some((
270            FileDicomObject { meta, object },
271            PixelDataValueLocation {
272                vr: header.vr,
273                length,
274                offset: source.count,
275            },
276        )))
277    }
278
279    /// Read `path` in full except for the large values `defer` picks out - plus, when
280    /// `defer_pixel_sequences` is set, encapsulated pixel data - which are skipped by seeking
281    /// past them and returned as file locations in [`DeferredValues`] instead (e.g. to emit as
282    /// DICOM JSON BulkDataURIs without ever reading them). Deferred elements stay in the object
283    /// with an empty placeholder value; see [`DeferredValues`].
284    ///
285    /// Returns `Ok(None)` when byte offsets in the file can't be relied on, so the caller should
286    /// read in full instead: a dataset-compressed (deflated) transfer syntax, a data set that
287    /// isn't a seekable Part 10 file, or a deferred range that runs past the end of the file
288    /// (truncation - a full read reports that properly). `read_until` is ignored.
289    pub fn open_file_deferring(
290        self,
291        path: impl AsRef<Path>,
292        defer: &dyn Fn(&dcmnorm_core::header::DataElementHeader) -> bool,
293        defer_pixel_sequences: bool,
294    ) -> Result<Option<(DefaultDicomObject, crate::mem::DeferredValues)>, ReadError> {
295        let file = File::open(path.as_ref()).map_err(|source| ReadError::Io {
296            source,
297            context: "opening file",
298        })?;
299        let file_len = file
300            .metadata()
301            .map_err(|source| ReadError::Io {
302                source,
303                context: "reading file metadata",
304            })?
305            .len();
306        self.from_reader_deferring(
307            BufReader::new(file),
308            Some(file_len),
309            defer,
310            defer_pixel_sequences,
311            false,
312        )
313    }
314
315    /// [`Self::open_file_deferring`] over any seekable Part 10 source, positioned at its
316    /// preamble: a byte slice in a `Cursor`, or a forward-only stream behind an adapter that
317    /// implements forward `Seek` by reading and discarding (the reader only ever seeks forward,
318    /// relative to its current position). `source_len`, when known, is checked against the
319    /// deferred ranges as the file length is; with `None` that check is the caller's.
320    ///
321    /// With `stop_at_pixel_data`, nothing past the top-level PixelData header is read: PixelData
322    /// is recorded as deferred where its value starts (length
323    /// [`crate::DeferredValueLocation::UNDEFINED_LENGTH`] when encapsulated) and later elements
324    /// are left out, as `dcm4che`'s `readDatasetUntilPixelData` does.
325    pub fn from_reader_deferring<R: Read + std::io::Seek>(
326        self,
327        mut source: R,
328        source_len: Option<u64>,
329        defer: &dyn Fn(&dcmnorm_core::header::DataElementHeader) -> bool,
330        defer_pixel_sequences: bool,
331        stop_at_pixel_data: bool,
332    ) -> Result<Option<(DefaultDicomObject, crate::mem::DeferredValues)>, ReadError> {
333        let mut meta = self.read_meta(&mut source)?;
334        let ts = meta
335            .transfer_syntax_ts()
336            .ok_or_else(|| ReadError::UnsupportedTransferSyntax {
337                uid: meta.transfer_syntax.clone(),
338            })?;
339        if matches!(
340            ts.codec(),
341            dcmnorm_encoding::transfer_syntax::Codec::Dataset(_)
342        ) {
343            return Ok(None);
344        }
345        let base_offset = source.stream_position().map_err(|source| ReadError::Io {
346            source,
347            context: "locating data set",
348        })?;
349
350        let mut reader = dcmnorm_parser::dataset::DataSetReader::new_with_ts(source, ts)
351            .map_err(|source| ReadError::Dataset { source })?;
352        let (object, deferred) = crate::mem::build_dataset_deferring(
353            &mut reader,
354            false,
355            defer,
356            defer_pixel_sequences,
357            stop_at_pixel_data,
358            base_offset,
359        )?;
360        if source_len.is_some_and(|len| deferred.max_end() > len) {
361            return Ok(None);
362        }
363        backfill_media_storage_uids(&mut meta, &object);
364        Ok(Some((FileDicomObject { meta, object }, deferred)))
365    }
366
367    /// Read `path` in full except for top-level `(7FE0,0010) PixelData`, which is left on disk
368    /// and described by [`crate::DeferredPixelData`] (native offset/length, or encapsulated
369    /// Basic Offset Table plus per-fragment offsets/lengths). Every other element - including
370    /// nested `IconImageSequence` pixels and trailing elements after `PixelData` - is loaded
371    /// normally.
372    ///
373    /// Returns `Ok(None)` when the file cannot be read this way (dataset-compressed / deflated
374    /// transfer syntax, or a deferred range running past EOF) so the caller can fall back to a
375    /// full read.
376    pub fn open_file_deferring_pixel_data(
377        self,
378        path: impl AsRef<Path>,
379    ) -> Result<Option<(DefaultDicomObject, crate::mem::DeferredPixelData, File)>, ReadError> {
380        use std::io::Seek;
381
382        let mut file = File::open(path.as_ref()).map_err(|source| ReadError::Io {
383            source,
384            context: "opening file",
385        })?;
386        let file_len = file
387            .metadata()
388            .map_err(|source| ReadError::Io {
389                source,
390                context: "reading file metadata",
391            })?
392            .len();
393        let (mut meta, object, pixel_data) = {
394            let mut source = BufReader::new(&mut file);
395            let meta = self.read_meta(&mut source)?;
396            let ts =
397                meta.transfer_syntax_ts()
398                    .ok_or_else(|| ReadError::UnsupportedTransferSyntax {
399                        uid: meta.transfer_syntax.clone(),
400                    })?;
401            if matches!(
402                ts.codec(),
403                dcmnorm_encoding::transfer_syntax::Codec::Dataset(_)
404            ) {
405                return Ok(None);
406            }
407            let base_offset = source.stream_position().map_err(|source| ReadError::Io {
408                source,
409                context: "locating data set",
410            })?;
411
412            let mut reader = dcmnorm_parser::dataset::DataSetReader::new_with_ts(source, ts)
413                .map_err(|source| ReadError::Dataset { source })?;
414            let (object, pixel_data) =
415                crate::mem::build_dataset_deferring_pixel_data(&mut reader, base_offset)?;
416            if pixel_data.max_end() > file_len {
417                return Err(ReadError::Io {
418                    source: std::io::Error::new(
419                        std::io::ErrorKind::UnexpectedEof,
420                        "deferred PixelData extends past end of file",
421                    ),
422                    context: "validating PixelData bounds",
423                });
424            }
425            (meta, object, pixel_data)
426        };
427        backfill_media_storage_uids(&mut meta, &object);
428        Ok(Some((FileDicomObject { meta, object }, pixel_data, file)))
429    }
430
431    fn read_meta(&self, mut source: impl Read) -> Result<FileMetaTable, ReadError> {
432        Ok(match self.read_preamble {
433            // Peek-and-detect: falls back to treating `source` as meta-less if the preamble or
434            // "DICM" magic aren't there.
435            ReadPreamble::Auto => {
436                FileMetaTable::read_from(&mut source)?.ok_or(ReadError::NotDicom)?
437            }
438            // No detection/fallback: the preamble and magic are required, and their absence (or
439            // mismatch) is a hard error rather than a silent reinterpretation as meta-less -
440            // matching what a caller who explicitly opted out of auto-detection would expect.
441            ReadPreamble::Always => {
442                let mut preamble = [0u8; PREAMBLE_LEN];
443                source
444                    .read_exact(&mut preamble)
445                    .map_err(|source| ReadError::Io {
446                        source,
447                        context: "reading 128-byte preamble",
448                    })?;
449                let mut magic = [0u8; 4];
450                source
451                    .read_exact(&mut magic)
452                    .map_err(|source| ReadError::Io {
453                        source,
454                        context: "reading \"DICM\" magic",
455                    })?;
456                if &magic != DICM_MAGIC {
457                    return Err(ReadError::NotDicom);
458                }
459                FileMetaTable::read_meta_group(&mut source)?
460            }
461        })
462    }
463}
464
465/// Where a native PixelData value sits in a file, as found by
466/// [`OpenFileOptions::open_file_until_pixel_data`]: its declared VR and byte length, and the
467/// absolute byte offset of its first value byte.
468#[derive(Debug, Clone, Copy, PartialEq, Eq)]
469pub struct PixelDataValueLocation {
470    pub vr: dcmnorm_core::VR,
471    pub length: u32,
472    pub offset: u64,
473}
474
475/// Counts bytes handed to the parser. Both the meta reader and the data set reader consume
476/// exactly what they parse (no read-ahead past the element in hand), so the count after
477/// stopping at PixelData's header is the file offset of its value.
478struct CountingReader<R> {
479    inner: R,
480    count: u64,
481}
482
483impl<R: Read> Read for CountingReader<R> {
484    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
485        let read = self.inner.read(buf)?;
486        self.count += read as u64;
487        Ok(read)
488    }
489}
490
491struct CountingWriter<W> {
492    inner: W,
493    count: u64,
494}
495
496impl<W: Write> Write for CountingWriter<W> {
497    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
498        let written = self.inner.write(buf)?;
499        self.count += written as u64;
500        Ok(written)
501    }
502
503    fn flush(&mut self) -> std::io::Result<()> {
504        self.inner.flush()
505    }
506}
507
508const SOP_CLASS_UID: dcmnorm_core::Tag = dcmnorm_core::Tag(0x0008, 0x0016);
509const SOP_INSTANCE_UID: dcmnorm_core::Tag = dcmnorm_core::Tag(0x0008, 0x0018);
510
511/// Some non-conformant DICOM writers (seen from fo-dicom-generated files) omit
512/// MediaStorageSOPClassUID/MediaStorageSOPInstanceUID (0002,0002)/(0002,0003) from the file
513/// meta group entirely, even though they're Type 1 per PS3.10 - `dicom-object`'s reader
514/// tolerated this by backfilling them from the data set's own SOPClassUID/SOPInstanceUID
515/// (0008,0016)/(0008,0018), which are almost always present redundantly. Preserved here for
516/// parity - confirmed against a real fixture (`test/files/sr.dcm`, written by fo-dicom 4.0.7).
517fn backfill_media_storage_uids(meta: &mut FileMetaTable, object: &InMemDicomObject) {
518    if meta.media_storage_sop_class_uid.is_empty() {
519        if let Some(uid) = object.get(SOP_CLASS_UID).and_then(|e| e.to_str().ok()) {
520            meta.media_storage_sop_class_uid = uid.trim_end_matches(['\0', ' ']).to_owned();
521        }
522    }
523    if meta.media_storage_sop_instance_uid.is_empty() {
524        if let Some(uid) = object.get(SOP_INSTANCE_UID).and_then(|e| e.to_str().ok()) {
525            meta.media_storage_sop_instance_uid = uid.trim_end_matches(['\0', ' ']).to_owned();
526        }
527    }
528}
529
530/// Read a bare data set (no meta group) and attach the given meta table to it. Used for
531/// `dcmnorm`'s meta-less/preamble-less trial-parse fallback path.
532pub fn with_meta_from_bare_dataset(
533    object: InMemDicomObject,
534    meta: FileMetaTable,
535) -> DefaultDicomObject {
536    FileDicomObject { meta, object }
537}
538
539/// Read raw bytes as a bare data set, trying Implicit VR LE, then Explicit VR LE, then
540/// Explicit VR BE in that order and taking the first one that parses successfully - the same
541/// permissive fallback `dcmnorm` already relies on for meta-less raw dumps.
542pub fn read_dataset_trial_parse(bytes: &[u8]) -> Option<(InMemDicomObject, &'static str)> {
543    const CANDIDATES: &[&str] = &[
544        dcmnorm_dictionary::uids::IMPLICIT_VR_LITTLE_ENDIAN,
545        dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN,
546        "1.2.840.10008.1.2.2",
547    ];
548    for uid in CANDIDATES {
549        let Some(ts) = TransferSyntaxRegistry.get(uid) else {
550            continue;
551        };
552        if let Ok(object) = InMemDicomObject::read_dataset_with_ts(Cursor::new(bytes), ts) {
553            return Some((object, uid));
554        }
555    }
556    None
557}
558
559#[cfg(test)]
560mod tests {
561    use super::{OpenFileOptions, ReadPreamble};
562    use dcmnorm_dictionary::tags;
563    use std::path::PathBuf;
564
565    fn fixture(name: &str) -> PathBuf {
566        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
567            .parent()
568            .unwrap()
569            .parent()
570            .unwrap()
571            .join("test")
572            .join("files")
573            .join(name)
574    }
575
576    #[test]
577    fn read_preamble_always_accepts_a_real_part10_file() {
578        let object = OpenFileOptions::new()
579            .read_preamble(ReadPreamble::Always)
580            .open_file(fixture("mr_small.dcm"))
581            .expect("a real Part 10 file has a preamble and DICM magic");
582        assert_eq!(
583            object
584                .get(tags::MODALITY)
585                .and_then(|e| e.to_str().ok())
586                .as_deref(),
587            Some("MR")
588        );
589    }
590
591    #[test]
592    fn read_preamble_always_rejects_a_file_with_no_preamble() {
593        // nometa_explicit_le.dcm is a bare data set: no 128-byte preamble, no "DICM" magic.
594        // ReadPreamble::Always must not silently fall back to auto-detection - it should fail
595        // cleanly instead of misinterpreting the first bytes of the data set as a preamble.
596        let result = OpenFileOptions::new()
597            .read_preamble(ReadPreamble::Always)
598            .open_file(fixture("nometa_explicit_le.dcm"));
599        assert!(result.is_err(), "expected an error, got {result:?}");
600    }
601
602    #[test]
603    fn read_preamble_auto_does_not_fall_back_to_bare_dataset_parsing() {
604        // OpenFileOptions::from_reader/open_file never did meta-less fallback (that's a
605        // separate, explicit opt-in via read_dataset_trial_parse) - Auto only controls whether
606        // detection happens, not whether a failed detection is tolerated.
607        let result = OpenFileOptions::new().open_file(fixture("nometa_explicit_le.dcm"));
608        assert!(result.is_err(), "expected an error, got {result:?}");
609    }
610
611    #[test]
612    fn explicit_vr_big_endian_file_reads_with_correct_values() {
613        let object = OpenFileOptions::new()
614            .open_file(fixture("explicit_vr_be.dcm"))
615            .expect("should read");
616        assert_eq!(
617            object.meta().transfer_syntax.trim_end_matches('\0'),
618            "1.2.840.10008.1.2.2"
619        );
620        assert_eq!(
621            object
622                .get(tags::MODALITY)
623                .and_then(|e| e.to_str().ok())
624                .as_deref(),
625            Some("US")
626        );
627    }
628}