1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! This crate contains a high-level abstraction for reading and manipulating
//! DICOM objects.
//! At this level, objects are comparable to a dictionary of elements,
//! in which some of them can have DICOM objects themselves.
//! The end user should prefer using this abstraction when dealing with DICOM
//! objects.
//!
//! # Examples
//!
//! Loading a DICOM file and reading some attributes by their standard alias:
//!
//! ```no_run
//! use dicom_object::open_file;
//! # fn foo() -> Result<(), Box<dyn std::error::Error>> {
//! let obj = open_file("0001.dcm")?;
//! let patient_name = obj.element_by_name("PatientName")?.to_str()?;
//! let modality = obj.element_by_name("Modality")?.to_str()?;
//! # Ok(())
//! # }
//! ```
//!
//! Elements can also be fetched by tag.
//! Methods are available for converting the element's DICOM value
//! into something more usable in Rust.
//!
//! ```
//! # use dicom_object::{DefaultDicomObject, Tag};
//! # fn something(obj: DefaultDicomObject) -> Result<(), Box<dyn std::error::Error>> {
//! let patient_date = obj.element(Tag(0x0010, 0x0030))?.to_date()?;
//! let pixel_data_bytes = obj.element(Tag(0x7FE0, 0x0010))?.to_bytes()?;
//! # Ok(())
//! # }
//! ```
//!
//! Finally, DICOM objects can be serialized back into DICOM encoded bytes.
//! A method is provided for writing a file DICOM object into a new DICOM file.
//!
//! ```no_run
//! # use dicom_object::{DefaultDicomObject, Tag};
//! # fn something(obj: DefaultDicomObject) -> Result<(), Box<dyn std::error::Error>> {
//! obj.write_to_file("0001_new.dcm")?;
//! # Ok(())
//! # }
//! ```
//!
//! This method requires you to write a [file meta table] first.
//! When creating a new DICOM object from scratch,
//! use a [`FileMetaTableBuilder`] to construct the file meta group,
//! then use `with_meta` or `with_exact_meta`:
//!
//! [file meta table]: crate::meta::FileMetaTable
//! [`FileMetaTableBuilder`]: crate::meta::FileMetaTableBuilder
//!
//! ```no_run
//! # use dicom_object::{InMemDicomObject, FileMetaTableBuilder};
//! # fn something(obj: InMemDicomObject) -> Result<(), Box<dyn std::error::Error>> {
//! let file_obj = obj.with_meta(
//!     FileMetaTableBuilder::new()
//!         // Implicit VR Little Endian
//!         .transfer_syntax("1.2.840.10008.1.2")
//!         // Computed Radiography image storage
//!         .media_storage_sop_class_uid("1.2.840.10008.5.1.4.1.1.1")
//! )?;
//! file_obj.write_to_file("0001_new.dcm")?;
//! # Ok(())
//! # }
//! ```
//!
//! In order to write a plain DICOM data set,
//! use one of the various `write_dataset` methods.
//!
//! ```
//! # use dicom_object::InMemDicomObject;
//! # use dicom_core::{DataElement, Tag, VR, dicom_value};
//! # fn run() -> Result<(), Box<dyn std::error::Error>> {
//! // build your object
//! let mut obj = InMemDicomObject::create_empty();
//! let patient_name = DataElement::new(
//!     Tag(0x0010, 0x0010),
//!     VR::PN,
//!     dicom_value!(Str, "Doe^John"),
//! );
//! obj.put(patient_name);
//!
//! // write the object's data set
//! let mut serialized = Vec::new();
//! let ts = dicom_transfer_syntax_registry::entries::EXPLICIT_VR_LITTLE_ENDIAN.erased();
//! obj.write_dataset_with_ts(&mut serialized, &ts)?;
//! assert!(!serialized.is_empty());
//! # Ok(())
//! # }
//! # run().unwrap();
//! ```
pub mod file;
pub mod loader;
pub mod mem;
pub mod meta;
pub mod pixeldata;
pub mod tokens;

mod util;

pub use crate::file::{from_reader, open_file};
pub use crate::mem::InMemDicomObject;
pub use crate::meta::{FileMetaTable, FileMetaTableBuilder};
pub use dicom_core::Tag;
pub use dicom_dictionary_std::StandardDataDictionary;

/// The default implementation of a root DICOM object.
pub type DefaultDicomObject = FileDicomObject<mem::InMemDicomObject<StandardDataDictionary>>;

use dicom_core::header::Header;
use dicom_encoding::{text::SpecificCharacterSet, transfer_syntax::TransferSyntaxIndex};
use dicom_parser::dataset::{DataSetWriter, IntoTokens};
use dicom_transfer_syntax_registry::TransferSyntaxRegistry;
use snafu::{Backtrace, OptionExt, ResultExt, Snafu};
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

/// The current implementation class UID generically referring to DICOM-rs.
///
/// Automatically generated as per the standard, part 5, section B.2.
///
/// This UID is subject to changes in future versions.
pub const IMPLEMENTATION_CLASS_UID: &str = "2.25.137038125948464847900039011591283709926";

/// The current implementation version name generically referring to DICOM-rs.
///
/// This names is subject to changes in future versions.
pub const IMPLEMENTATION_VERSION_NAME: &str = "DICOM-rs 0.3";

/// Trait type for a DICOM object.
/// This is a high-level abstraction where an object is accessed and
/// manipulated as dictionary of entries indexed by tags, which in
/// turn may contain a DICOM object.
///
/// This trait interface is experimental and prone to sudden changes.
pub trait DicomObject {
    type Element: Header;

    /// Retrieve a particular DICOM element by its tag.
    fn element(&self, tag: Tag) -> Result<Self::Element>;

    /// Retrieve a particular DICOM element by its name.
    fn element_by_name(&self, name: &str) -> Result<Self::Element>;

    /// Retrieve the processed meta information table, if available.
    ///
    /// This table will generally not be reachable from children objects
    /// in another object with a valid meta table. As such, it is recommended
    /// for this method to be called at the root of a DICOM object.
    fn meta(&self) -> Option<&FileMetaTable> {
        None
    }
}

#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum Error {
    #[snafu(display("Could not open file '{}'", filename.display()))]
    OpenFile {
        filename: std::path::PathBuf,
        backtrace: Backtrace,
        source: std::io::Error,
    },
    #[snafu(display("Could not read from file '{}'", filename.display()))]
    ReadFile {
        filename: std::path::PathBuf,
        backtrace: Backtrace,
        source: std::io::Error,
    },
    #[snafu(display("Could not parse meta group data set"))]
    ParseMetaDataSet {
        #[snafu(backtrace)]
        source: crate::meta::Error,
    },
    #[snafu(display("Could not create data set parser"))]
    CreateParser {
        #[snafu(backtrace)]
        source: dicom_parser::dataset::read::Error,
    },
    #[snafu(display("Could not read data set token"))]
    ReadToken {
        #[snafu(backtrace)]
        source: dicom_parser::dataset::read::Error,
    },
    #[snafu(display("Could not write to file '{}'", filename.display()))]
    WriteFile {
        filename: std::path::PathBuf,
        backtrace: Backtrace,
        source: std::io::Error,
    },
    #[snafu(display("Could not write object preamble"))]
    WritePreamble {
        backtrace: Backtrace,
        source: std::io::Error,
    },
    #[snafu(display("Could not write magic code"))]
    WriteMagicCode {
        backtrace: Backtrace,
        source: std::io::Error,
    },
    #[snafu(display("Could not create data set printer"))]
    CreatePrinter {
        #[snafu(backtrace)]
        source: dicom_parser::dataset::write::Error,
    },
    #[snafu(display("Could not print meta group data set"))]
    PrintMetaDataSet {
        #[snafu(backtrace)]
        source: crate::meta::Error,
    },
    #[snafu(display("Could not print data set"))]
    PrintDataSet {
        #[snafu(backtrace)]
        source: dicom_parser::dataset::write::Error,
    },
    #[snafu(display("Unsupported transfer syntax `{}`", uid))]
    UnsupportedTransferSyntax { uid: String, backtrace: Backtrace },
    #[snafu(display("No such data element with tag {}", tag))]
    NoSuchDataElementTag { tag: Tag, backtrace: Backtrace },
    #[snafu(display("No such data element {} (with tag {})", alias, tag))]
    NoSuchDataElementAlias {
        tag: Tag,
        alias: String,
        backtrace: Backtrace,
    },
    #[snafu(display("Unknown data attribute named `{}`", name))]
    NoSuchAttributeName { name: String, backtrace: Backtrace },
    #[snafu(display("Missing element value"))]
    MissingElementValue { backtrace: Backtrace },
    #[snafu(display("Unexpected token {:?}", token))]
    UnexpectedToken {
        token: dicom_parser::dataset::DataToken,
        backtrace: Backtrace,
    },
    #[snafu(display("Premature data set end"))]
    PrematureEnd { backtrace: Backtrace },
    /// Could not build file meta table
    BuildMetaTable {
        #[snafu(backtrace)]
        source: crate::meta::Error,
    },
    /// Could not prepare file meta table
    PrepareMetaTable {
        source: dicom_core::value::CastValueError,
        backtrace: Backtrace,
    },
}

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// A root DICOM object contains additional meta information about the object
/// in a separate table.
#[deprecated(since = "0.4.0", note = "use `FileDicomObject` instead")]
pub type RootDicomObject<O> = FileDicomObject<O>;

/// A root DICOM object retrieved from a standard DICOM file,
/// containing additional information from the file meta group
/// in a separate table value.
#[derive(Debug, Clone, PartialEq)]
pub struct FileDicomObject<O> {
    meta: FileMetaTable,
    obj: O,
}

impl<O> FileDicomObject<O> {
    /// Retrieve the processed meta header table.
    pub fn meta(&self) -> &FileMetaTable {
        &self.meta
    }

    /// Retrieve the inner DICOM object structure, discarding the meta table.
    pub fn into_inner(self) -> O {
        self.obj
    }
}

impl<O> FileDicomObject<O>
where
    for<'a> &'a O: IntoTokens,
{
    /// Write the entire object as a DICOM file
    /// into the given file path.
    /// Preamble, magic code, and file meta group will be included
    /// before the inner object.
    pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let path = path.as_ref();
        let file = File::create(path).context(WriteFile { filename: path })?;
        let mut to = BufWriter::new(file);

        // write preamble
        to.write_all(&[0_u8; 128][..])
            .context(WriteFile { filename: path })?;

        // write magic sequence
        to.write_all(b"DICM")
            .context(WriteFile { filename: path })?;

        // write meta group
        self.meta.write(&mut to).context(PrintMetaDataSet)?;

        // prepare encoder
        let registry = TransferSyntaxRegistry::default();
        let ts = registry.get(&self.meta.transfer_syntax).with_context(|| {
            UnsupportedTransferSyntax {
                uid: self.meta.transfer_syntax.clone(),
            }
        })?;
        let cs = SpecificCharacterSet::Default;
        let mut dset_writer = DataSetWriter::with_ts_cs(to, ts, cs).context(CreatePrinter)?;

        // write object
        dset_writer
            .write_sequence((&self.obj).into_tokens())
            .context(PrintDataSet)?;

        Ok(())
    }

    /// Write the entire object as a DICOM file
    /// into the given writer.
    /// Preamble, magic code, and file meta group will be included
    /// before the inner object.
    pub fn write_all<W: Write>(&self, to: W) -> Result<()> {
        let mut to = BufWriter::new(to);

        // write preamble
        to.write_all(&[0_u8; 128][..]).context(WritePreamble)?;

        // write magic sequence
        to.write_all(b"DICM").context(WriteMagicCode)?;

        // write meta group
        self.meta.write(&mut to).context(PrintMetaDataSet)?;

        // prepare encoder
        let registry = TransferSyntaxRegistry::default();
        let ts = registry.get(&self.meta.transfer_syntax).with_context(|| {
            UnsupportedTransferSyntax {
                uid: self.meta.transfer_syntax.clone(),
            }
        })?;
        let cs = SpecificCharacterSet::Default;
        let mut dset_writer = DataSetWriter::with_ts_cs(to, ts, cs).context(CreatePrinter)?;

        // write object
        dset_writer
            .write_sequence((&self.obj).into_tokens())
            .context(PrintDataSet)?;

        Ok(())
    }

    /// Write the file meta group set into the given writer.
    ///
    /// This is equivalent to `self.meta().write(to)`.
    pub fn write_meta<W: Write>(&self, to: W) -> Result<()> {
        self.meta.write(to).context(PrintMetaDataSet)
    }

    /// Write the inner data set into the given writer,
    /// without preamble, magic code, nor file meta group.
    ///
    /// The transfer syntax is selected from the file meta table.
    pub fn write_dataset<W: Write>(&self, to: W) -> Result<()> {
        let to = BufWriter::new(to);

        // prepare encoder
        let registry = TransferSyntaxRegistry::default();
        let ts = registry.get(&self.meta.transfer_syntax).with_context(|| {
            UnsupportedTransferSyntax {
                uid: self.meta.transfer_syntax.clone(),
            }
        })?;
        let cs = SpecificCharacterSet::Default;
        let mut dset_writer = DataSetWriter::with_ts_cs(to, ts, cs).context(CreatePrinter)?;

        // write object
        dset_writer
            .write_sequence((&self.obj).into_tokens())
            .context(PrintDataSet)?;

        Ok(())
    }
}

impl<O> ::std::ops::Deref for FileDicomObject<O> {
    type Target = O;

    fn deref(&self) -> &Self::Target {
        &self.obj
    }
}

impl<O> ::std::ops::DerefMut for FileDicomObject<O> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.obj
    }
}

impl<O> DicomObject for FileDicomObject<O>
where
    O: DicomObject,
{
    type Element = <O as DicomObject>::Element;

    fn element(&self, tag: Tag) -> Result<Self::Element> {
        self.obj.element(tag)
    }

    fn element_by_name(&self, name: &str) -> Result<Self::Element> {
        self.obj.element_by_name(name)
    }

    fn meta(&self) -> Option<&FileMetaTable> {
        Some(&self.meta)
    }
}

impl<'a, O: 'a> DicomObject for &'a FileDicomObject<O>
where
    O: DicomObject,
{
    type Element = <O as DicomObject>::Element;

    fn element(&self, tag: Tag) -> Result<Self::Element> {
        self.obj.element(tag)
    }

    fn element_by_name(&self, name: &str) -> Result<Self::Element> {
        self.obj.element_by_name(name)
    }
}

impl<O> IntoIterator for FileDicomObject<O>
where
    O: IntoIterator,
{
    type Item = <O as IntoIterator>::Item;
    type IntoIter = <O as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.obj.into_iter()
    }
}

#[cfg(test)]
mod tests {
    use crate::meta::FileMetaTableBuilder;
    use crate::FileDicomObject;

    #[test]
    fn smoke_test() {
        const FILE_NAME: &str = ".smoke-test.dcm";

        let meta = FileMetaTableBuilder::new()
            .transfer_syntax(
                dicom_transfer_syntax_registry::entries::EXPLICIT_VR_LITTLE_ENDIAN.uid(),
            )
            .media_storage_sop_class_uid("1.2.840.10008.5.1.4.1.1.1")
            .media_storage_sop_instance_uid("1.2.3.456")
            .implementation_class_uid("1.2.345.6.7890.1.234")
            .build()
            .unwrap();
        let obj = FileDicomObject::new_empty_with_meta(meta);

        obj.write_to_file(FILE_NAME).unwrap();

        let obj2 = FileDicomObject::open_file(FILE_NAME).unwrap();

        assert_eq!(obj, obj2);

        let _ = std::fs::remove_file(FILE_NAME);
    }
}