Skip to main content

dcmnorm_object/
pixel.rs

1//! [`PixelDataObject`] and [`ApplyOp`] implementations for [`DefaultDicomObject`] - the two
2//! traits `dcmnorm-encoding`'s/`dcmnorm-core`'s pixel data codec adapters need to read
3//! image-shape attributes from an object and, for the encapsulated-pixel-data writer, apply
4//! required post-transcode attribute patches (e.g. Photometric Interpretation adjustments)
5//! back onto it.
6
7use std::borrow::Cow;
8
9use dcmnorm_core::header::Tag;
10use dcmnorm_core::ops::{ApplyOp, AttributeAction, AttributeOp, AttributeSelectorStep};
11use dcmnorm_encoding::adapters::{PixelDataObject, RawPixelData};
12
13use crate::file::{DefaultDicomObject, FileDicomObject};
14use crate::mem::{ApplyOpError, InMemDicomObject, MissingElementError};
15
16const ROWS: Tag = Tag(0x0028, 0x0010);
17const COLUMNS: Tag = Tag(0x0028, 0x0011);
18const SAMPLES_PER_PIXEL: Tag = Tag(0x0028, 0x0002);
19const BITS_ALLOCATED: Tag = Tag(0x0028, 0x0100);
20const BITS_STORED: Tag = Tag(0x0028, 0x0101);
21const PHOTOMETRIC_INTERPRETATION: Tag = Tag(0x0028, 0x0004);
22const NUMBER_OF_FRAMES: Tag = Tag(0x0028, 0x0008);
23const PIXEL_DATA: Tag = Tag(0x7FE0, 0x0010);
24
25impl PixelDataObject for FileDicomObject<InMemDicomObject> {
26    fn transfer_syntax_uid(&self) -> &str {
27        self.meta.transfer_syntax()
28    }
29
30    fn rows(&self) -> Option<u16> {
31        self.object.get(ROWS)?.to_int().ok()
32    }
33
34    fn cols(&self) -> Option<u16> {
35        self.object.get(COLUMNS)?.to_int().ok()
36    }
37
38    fn samples_per_pixel(&self) -> Option<u16> {
39        self.object.get(SAMPLES_PER_PIXEL)?.to_int().ok()
40    }
41
42    fn bits_allocated(&self) -> Option<u16> {
43        self.object.get(BITS_ALLOCATED)?.to_int().ok()
44    }
45
46    fn bits_stored(&self) -> Option<u16> {
47        self.object.get(BITS_STORED)?.to_int().ok()
48    }
49
50    fn photometric_interpretation(&self) -> Option<&str> {
51        // Extract the inner `&str` by matching rather than calling `.trim_end()` straight on
52        // the `Cow` - the latter would borrow from the temporary `Cow` value itself rather
53        // than from `self`, and not compile. PhotometricInterpretation is a CS-type VR (pure
54        // ASCII per PS3.5), so `Cow::Owned` (a lossy non-UTF8 conversion) is not valid DICOM
55        // for this tag and treated as absent rather than allocating just to satisfy the
56        // signature.
57        match self.object.get(PHOTOMETRIC_INTERPRETATION)?.to_str().ok()? {
58            Cow::Borrowed(s) => Some(s.trim_end()),
59            Cow::Owned(_) => None,
60        }
61    }
62
63    fn number_of_frames(&self) -> Option<u32> {
64        self.object
65            .get(NUMBER_OF_FRAMES)
66            .and_then(|e| e.to_str().ok())
67            .and_then(|s| s.trim().parse().ok())
68    }
69
70    fn number_of_fragments(&self) -> Option<u32> {
71        match self.object.get(PIXEL_DATA)?.value() {
72            dcmnorm_core::value::Value::PixelSequence(seq) => Some(seq.fragments().len() as u32),
73            _ => None,
74        }
75    }
76
77    fn fragment(&self, fragment: usize) -> Option<Cow<'_, [u8]>> {
78        match self.object.get(PIXEL_DATA)?.value() {
79            dcmnorm_core::value::Value::PixelSequence(seq) => seq
80                .fragments()
81                .get(fragment)
82                .map(|f| Cow::Borrowed(f.as_slice())),
83            dcmnorm_core::value::Value::Primitive(pv) if fragment == 0 => Some(pv.to_bytes()),
84            _ => None,
85        }
86    }
87
88    fn offset_table(&self) -> Option<Cow<'_, [u32]>> {
89        match self.object.get(PIXEL_DATA)?.value() {
90            dcmnorm_core::value::Value::PixelSequence(seq) => {
91                Some(Cow::Borrowed(seq.offset_table()))
92            }
93            _ => None,
94        }
95    }
96
97    fn raw_pixel_data(&self) -> Option<RawPixelData> {
98        match self.object.get(PIXEL_DATA)?.value() {
99            dcmnorm_core::value::Value::PixelSequence(seq) => Some(RawPixelData {
100                fragments: seq.fragments().iter().cloned().collect(),
101                offset_table: seq.offset_table().iter().copied().collect(),
102            }),
103            dcmnorm_core::value::Value::Primitive(pv) => Some(RawPixelData {
104                fragments: std::iter::once(pv.to_bytes().into_owned()).collect(),
105                offset_table: Default::default(),
106            }),
107            _ => None,
108        }
109    }
110}
111
112impl ApplyOp for DefaultDicomObject {
113    type Err = ApplyOpError;
114
115    fn apply(&mut self, op: AttributeOp) -> Result<(), Self::Err> {
116        // Surface a real error only for the one failure mode dcmnorm's own callers actually
117        // hit in practice - replacing an attribute that must already exist - matching the
118        // `ApplyOp` trait's contract ("no changes to the receiver are made" on error). Every
119        // other action already treats absence as a valid outcome per `AttributeAction`'s own
120        // documented semantics (e.g. Remove on a missing tag is a no-op, not an error).
121        if let AttributeAction::Replace(_) | AttributeAction::ReplaceStr(_) = &op.action {
122            if let AttributeSelectorStep::Tag(tag) = *op.selector.first_step() {
123                if self.object.get(tag).is_none() {
124                    return Err(ApplyOpError::MissingElement(MissingElementError { tag }));
125                }
126            }
127            // else: an unsupported selector shape - `self.object.apply` below reports it.
128        }
129        self.object.apply(op)
130    }
131}