-
Notifications
You must be signed in to change notification settings - Fork 74
/
mem.rs
3860 lines (3504 loc) · 129 KB
/
mem.rs
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module contains the implementation for an in-memory DICOM object.
//!
//! Use [`InMemDicomObject`] for your DICOM data set construction needs.
//! Values of this type support infallible insertion, removal, and retrieval
//! of elements by DICOM tag,
//! or name (keyword) with a data element dictionary look-up.
//!
//! If you wish to build a complete DICOM file,
//! you can start from an `InMemDicomObject`
//! and complement it with a [file meta group table](crate::meta)
//! (see [`with_meta`](InMemDicomObject::with_meta)
//! and [`with_exact_meta`](InMemDicomObject::with_exact_meta)).
//!
//! # Example
//!
//! A new DICOM data set can be built by providing a sequence of data elements.
//! Insertion and removal methods are also available.
//!
//! ```
//! # use dicom_core::{DataElement, VR, dicom_value};
//! # use dicom_dictionary_std::tags;
//! # use dicom_dictionary_std::uids;
//! # use dicom_object::InMemDicomObject;
//! let mut obj = InMemDicomObject::from_element_iter([
//! DataElement::new(tags::SOP_CLASS_UID, VR::UI, uids::COMPUTED_RADIOGRAPHY_IMAGE_STORAGE),
//! DataElement::new(tags::SOP_INSTANCE_UID, VR::UI, "2.25.60156688944589400766024286894543900794"),
//! // ...
//! ]);
//!
//! // continue adding elements
//! obj.put(DataElement::new(tags::MODALITY, VR::CS, "CR"));
//! ```
//!
//! In-memory DICOM objects may have a byte length recorded,
//! if it was part of a data set sequence with explicit length.
//! If necessary, this number can be obtained via the [`HasLength`] trait.
//! However, any modifications made to the object will reset this length
//! to [_undefined_](dicom_core::Length::UNDEFINED).
use dicom_core::ops::{
ApplyOp, AttributeAction, AttributeOp, AttributeSelector, AttributeSelectorStep,
};
use itertools::Itertools;
use smallvec::SmallVec;
use snafu::{ensure, OptionExt, ResultExt};
use std::borrow::Cow;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
use std::{collections::BTreeMap, io::Write};
use crate::file::ReadPreamble;
use crate::ops::{
ApplyError, ApplyResult, IncompatibleTypesSnafu, ModifySnafu, UnsupportedActionSnafu,
};
use crate::{meta::FileMetaTable, FileMetaTableBuilder};
use crate::{
AccessByNameError, AccessError, AtAccessError, BuildMetaTableSnafu, CreateParserSnafu,
CreatePrinterSnafu, DicomObject, ElementNotFoundSnafu, FileDicomObject, InvalidGroupSnafu,
MissingElementValueSnafu, MissingLeafElementSnafu, NoSpaceSnafu, NoSuchAttributeNameSnafu,
NoSuchDataElementAliasSnafu, NoSuchDataElementTagSnafu, NotASequenceSnafu, OpenFileSnafu,
ParseMetaDataSetSnafu, PrematureEndSnafu, PrepareMetaTableSnafu, PrintDataSetSnafu,
PrivateCreatorNotFoundSnafu, PrivateElementError, ReadError, ReadFileSnafu,
ReadPreambleBytesSnafu, ReadTokenSnafu, ReadUnsupportedTransferSyntaxSnafu,
UnexpectedTokenSnafu, WithMetaError, WriteError,
};
use dicom_core::dictionary::{DataDictionary, DataDictionaryEntry};
use dicom_core::header::{GroupNumber, HasLength, Header};
use dicom_core::value::{DataSetSequence, PixelFragmentSequence, Value, ValueType, C};
use dicom_core::{DataElement, Length, PrimitiveValue, Tag, VR};
use dicom_dictionary_std::{tags, StandardDataDictionary};
use dicom_encoding::transfer_syntax::TransferSyntaxIndex;
use dicom_encoding::{encode::EncodeTo, text::SpecificCharacterSet, TransferSyntax};
use dicom_parser::dataset::{DataSetReader, DataToken, IntoTokensOptions};
use dicom_parser::{
dataset::{read::Error as ParserError, DataSetWriter, IntoTokens},
StatefulDecode,
};
use dicom_transfer_syntax_registry::TransferSyntaxRegistry;
/// A full in-memory DICOM data element.
pub type InMemElement<D = StandardDataDictionary> = DataElement<InMemDicomObject<D>, InMemFragment>;
/// The type of a pixel data fragment.
pub type InMemFragment = dicom_core::value::InMemFragment;
type Result<T, E = AccessError> = std::result::Result<T, E>;
type ParserResult<T> = std::result::Result<T, ParserError>;
/// A DICOM object that is fully contained in memory.
///
/// See the [module-level documentation](self)
/// for more details.
#[derive(Debug, Clone)]
pub struct InMemDicomObject<D = StandardDataDictionary> {
/// the element map
entries: BTreeMap<Tag, InMemElement<D>>,
/// the data dictionary
dict: D,
/// The length of the DICOM object in bytes.
/// It is usually undefined, unless it is part of an item
/// in a sequence with a specified length in its item header.
len: Length,
/// In case the SpecificCharSet changes we need to mark the object as dirty,
/// because changing the character set may change the length in bytes of
/// stored text. It has to be public for now because we need
pub(crate) charset_changed: bool,
}
impl<D> PartialEq for InMemDicomObject<D> {
// This implementation ignores the data dictionary.
fn eq(&self, other: &Self) -> bool {
self.entries == other.entries
}
}
impl<D> HasLength for InMemDicomObject<D> {
fn length(&self) -> Length {
self.len
}
}
impl<'s, D: 's> DicomObject for &'s InMemDicomObject<D>
where
D: DataDictionary,
D: Clone,
{
type Element = &'s InMemElement<D>;
fn element(&self, tag: Tag) -> Result<Self::Element> {
self.entries
.get(&tag)
.context(NoSuchDataElementTagSnafu { tag })
}
fn element_by_name(&self, name: &str) -> Result<Self::Element, AccessByNameError> {
let tag = self.lookup_name(name)?;
self.element(tag).map_err(|e| e.into_access_by_name(name))
}
}
impl FileDicomObject<InMemDicomObject<StandardDataDictionary>> {
/// Create a DICOM object by reading from a file.
///
/// This function assumes the standard file encoding structure:
/// first it automatically detects whether the 128-byte preamble is present,
/// skipping it if found.
/// Then it reads the file meta group,
/// followed by the rest of the data set.
pub fn open_file<P: AsRef<Path>>(path: P) -> Result<Self, ReadError> {
Self::open_file_with_dict(path, StandardDataDictionary)
}
/// Create a DICOM object by reading from a byte source.
///
/// This function assumes the standard file encoding structure:
/// first it automatically detects whether the 128-byte preamble is present,
/// skipping it if found.
/// Then it reads the file meta group,
/// followed by the rest of the data set.
pub fn from_reader<S>(src: S) -> Result<Self, ReadError>
where
S: Read,
{
Self::from_reader_with_dict(src, StandardDataDictionary)
}
}
impl InMemDicomObject<StandardDataDictionary> {
/// Create a new empty DICOM object.
pub fn new_empty() -> Self {
InMemDicomObject {
entries: BTreeMap::new(),
dict: StandardDataDictionary,
len: Length::UNDEFINED,
charset_changed: false,
}
}
/// Construct a DICOM object from a fallible source of structured elements.
#[inline]
pub fn from_element_source<I>(iter: I) -> Result<Self>
where
I: IntoIterator<Item = Result<InMemElement<StandardDataDictionary>>>,
{
Self::from_element_source_with_dict(iter, StandardDataDictionary)
}
/// Construct a DICOM object from a non-fallible source of structured elements.
#[inline]
pub fn from_element_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = InMemElement<StandardDataDictionary>>,
{
Self::from_iter_with_dict(iter, StandardDataDictionary)
}
/// Construct a DICOM object representing a command set,
/// from a non-fallible iterator of structured elements.
///
/// This method will automatically insert
/// a _Command Group Length_ (0000,0000) element
/// based on the command elements found in the sequence.
#[inline]
pub fn command_from_element_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = InMemElement<StandardDataDictionary>>,
{
Self::command_from_iter_with_dict(iter, StandardDataDictionary)
}
/// Read an object from a source using the given decoder.
///
/// Note: [`read_dataset_with_ts`] and [`read_dataset_with_ts_cs`]
/// may be easier to use.
///
/// [`read_dataset_with_ts`]: InMemDicomObject::read_dataset_with_ts
/// [`read_dataset_with_ts_cs`]: InMemDicomObject::read_dataset_with_ts_cs
#[inline]
pub fn read_dataset<S>(decoder: S) -> Result<Self, ReadError>
where
S: StatefulDecode,
{
Self::read_dataset_with_dict(decoder, StandardDataDictionary)
}
/// Read an object from a source,
/// using the given transfer syntax and default character set.
///
/// If the attribute _Specific Character Set_ is found in the encoded data,
/// this will override the given character set.
#[inline]
pub fn read_dataset_with_ts_cs<S>(
from: S,
ts: &TransferSyntax,
cs: SpecificCharacterSet,
) -> Result<Self, ReadError>
where
S: Read,
{
Self::read_dataset_with_dict_ts_cs(from, StandardDataDictionary, ts, cs)
}
/// Read an object from a source,
/// using the given transfer syntax.
///
/// The default character set is assumed
/// until _Specific Character Set_ is found in the encoded data,
/// after which the text decoder will be overriden accordingly.
#[inline]
pub fn read_dataset_with_ts<S>(from: S, ts: &TransferSyntax) -> Result<Self, ReadError>
where
S: Read,
{
Self::read_dataset_with_dict_ts_cs(
from,
StandardDataDictionary,
ts,
SpecificCharacterSet::default(),
)
}
}
impl<D> FileDicomObject<InMemDicomObject<D>>
where
D: DataDictionary,
D: Clone,
{
/// Create a new empty object, using the given dictionary and
/// file meta table.
pub fn new_empty_with_dict_and_meta(dict: D, meta: FileMetaTable) -> Self {
FileDicomObject {
meta,
obj: InMemDicomObject {
entries: BTreeMap::new(),
dict,
len: Length::UNDEFINED,
charset_changed: false,
},
}
}
/// Create a DICOM object by reading from a file.
///
/// This function assumes the standard file encoding structure:
/// first it automatically detects whether the 128-byte preamble is present,
/// skipping it when found.
/// Then it reads the file meta group,
/// followed by the rest of the data set.
pub fn open_file_with_dict<P: AsRef<Path>>(path: P, dict: D) -> Result<Self, ReadError> {
Self::open_file_with(path, dict, TransferSyntaxRegistry)
}
/// Create a DICOM object by reading from a file.
///
/// This function assumes the standard file encoding structure:
/// first it automatically detects whether the 128-byte preamble is present,
/// skipping it when found.
/// Then it reads the file meta group,
/// followed by the rest of the data set.
///
/// This function allows you to choose a different transfer syntax index,
/// but its use is only advised when the built-in transfer syntax registry
/// is insufficient. Otherwise, please use [`open_file_with_dict`] instead.
///
/// [`open_file_with_dict`]: #method.open_file_with_dict
pub fn open_file_with<P: AsRef<Path>, R>(
path: P,
dict: D,
ts_index: R,
) -> Result<Self, ReadError>
where
P: AsRef<Path>,
R: TransferSyntaxIndex,
{
Self::open_file_with_all_options(path, dict, ts_index, None, ReadPreamble::Auto)
}
// detect the presence of a preamble
// and provide a better `ReadPreamble` option accordingly
fn detect_preamble<S>(reader: &mut BufReader<S>) -> std::io::Result<ReadPreamble>
where
S: Read,
{
let buf = reader.fill_buf()?;
let buflen = buf.len();
if buflen < 4 {
return Err(std::io::ErrorKind::UnexpectedEof.into());
}
if buflen >= 132 && &buf[128..132] == b"DICM" {
return Ok(ReadPreamble::Always);
}
if &buf[0..4] == b"DICM" {
return Ok(ReadPreamble::Never);
}
// could not detect
Ok(ReadPreamble::Auto)
}
pub(crate) fn open_file_with_all_options<P: AsRef<Path>, R>(
path: P,
dict: D,
ts_index: R,
read_until: Option<Tag>,
mut read_preamble: ReadPreamble,
) -> Result<Self, ReadError>
where
P: AsRef<Path>,
R: TransferSyntaxIndex,
{
let path = path.as_ref();
let mut file =
BufReader::new(File::open(path).with_context(|_| OpenFileSnafu { filename: path })?);
if read_preamble == ReadPreamble::Auto {
read_preamble = Self::detect_preamble(&mut file)
.with_context(|_| ReadFileSnafu { filename: path })?;
}
if read_preamble == ReadPreamble::Auto || read_preamble == ReadPreamble::Always {
let mut buf = [0u8; 128];
// skip the preamble
file.read_exact(&mut buf)
.with_context(|_| ReadFileSnafu { filename: path })?;
}
// read metadata header
let meta = FileMetaTable::from_reader(&mut file).context(ParseMetaDataSetSnafu)?;
// read rest of data according to metadata, feed it to object
if let Some(ts) = ts_index.get(&meta.transfer_syntax) {
let mut dataset = DataSetReader::new_with_ts(file, ts).context(CreateParserSnafu)?;
Ok(FileDicomObject {
meta,
obj: InMemDicomObject::build_object(
&mut dataset,
dict,
false,
Length::UNDEFINED,
read_until,
)?,
})
} else {
ReadUnsupportedTransferSyntaxSnafu {
uid: meta.transfer_syntax,
}
.fail()
}
}
/// Create a DICOM object by reading from a byte source.
///
/// This function assumes the standard file encoding structure:
/// first it automatically detects whether the 128-byte preamble is present,
/// skipping it when found.
/// Then it reads the file meta group,
/// followed by the rest of the data set.
pub fn from_reader_with_dict<S>(src: S, dict: D) -> Result<Self, ReadError>
where
S: Read,
{
Self::from_reader_with(src, dict, TransferSyntaxRegistry)
}
/// Create a DICOM object by reading from a byte source.
///
/// This function assumes the standard file encoding structure:
/// first it automatically detects whether the preamble is present,
/// skipping it when found.
/// Then it reads the file meta group,
/// followed by the rest of the data set.
///
/// This function allows you to choose a different transfer syntax index,
/// but its use is only advised when the built-in transfer syntax registry
/// is insufficient. Otherwise, please use [`from_reader_with_dict`] instead.
///
/// [`from_reader_with_dict`]: #method.from_reader_with_dict
pub fn from_reader_with<'s, S: 's, R>(src: S, dict: D, ts_index: R) -> Result<Self, ReadError>
where
S: Read,
R: TransferSyntaxIndex,
{
Self::from_reader_with_all_options(src, dict, ts_index, None, ReadPreamble::Auto)
}
pub(crate) fn from_reader_with_all_options<'s, S: 's, R>(
src: S,
dict: D,
ts_index: R,
read_until: Option<Tag>,
mut read_preamble: ReadPreamble,
) -> Result<Self, ReadError>
where
S: Read,
R: TransferSyntaxIndex,
{
let mut file = BufReader::new(src);
if read_preamble == ReadPreamble::Auto {
read_preamble = Self::detect_preamble(&mut file).context(ReadPreambleBytesSnafu)?;
}
if read_preamble == ReadPreamble::Always {
// skip preamble
let mut buf = [0u8; 128];
// skip the preamble
file.read_exact(&mut buf).context(ReadPreambleBytesSnafu)?;
}
// read metadata header
let meta = FileMetaTable::from_reader(&mut file).context(ParseMetaDataSetSnafu)?;
// read rest of data according to metadata, feed it to object
if let Some(ts) = ts_index.get(&meta.transfer_syntax) {
let mut dataset = DataSetReader::new_with_ts(file, ts).context(CreateParserSnafu)?;
let obj = InMemDicomObject::build_object(
&mut dataset,
dict,
false,
Length::UNDEFINED,
read_until,
)?;
Ok(FileDicomObject { meta, obj })
} else {
ReadUnsupportedTransferSyntaxSnafu {
uid: meta.transfer_syntax,
}
.fail()
}
}
}
impl FileDicomObject<InMemDicomObject<StandardDataDictionary>> {
/// Create a new empty object, using the given file meta table.
pub fn new_empty_with_meta(meta: FileMetaTable) -> Self {
FileDicomObject {
meta,
obj: InMemDicomObject {
entries: BTreeMap::new(),
dict: StandardDataDictionary,
len: Length::UNDEFINED,
charset_changed: false,
},
}
}
}
impl<D> InMemDicomObject<D>
where
D: DataDictionary,
D: Clone,
{
/// Create a new empty object, using the given dictionary for name lookup.
pub fn new_empty_with_dict(dict: D) -> Self {
InMemDicomObject {
entries: BTreeMap::new(),
dict,
len: Length::UNDEFINED,
charset_changed: false,
}
}
/// Construct a DICOM object from an iterator of structured elements.
pub fn from_element_source_with_dict<I>(iter: I, dict: D) -> Result<Self>
where
I: IntoIterator<Item = Result<InMemElement<D>>>,
{
let entries: Result<_> = iter.into_iter().map_ok(|e| (e.tag(), e)).collect();
Ok(InMemDicomObject {
entries: entries?,
dict,
len: Length::UNDEFINED,
charset_changed: false,
})
}
/// Construct a DICOM object from a non-fallible iterator of structured elements.
pub fn from_iter_with_dict<I>(iter: I, dict: D) -> Self
where
I: IntoIterator<Item = InMemElement<D>>,
{
let entries = iter.into_iter().map(|e| (e.tag(), e)).collect();
InMemDicomObject {
entries,
dict,
len: Length::UNDEFINED,
charset_changed: false,
}
}
/// Construct a DICOM object representing a command set,
/// from a non-fallible iterator of structured elements.
///
/// This method will automatically insert
/// a _Command Group Length_ (0000,0000) element
/// based on the command elements found in the sequence.
pub fn command_from_iter_with_dict<I>(iter: I, dict: D) -> Self
where
I: IntoIterator<Item = InMemElement<D>>,
{
let mut calculated_length: u32 = 0;
let mut entries: BTreeMap<_, _> = iter
.into_iter()
.map(|e| {
// count the length of command set elements
if e.tag().0 == 0x0000 && e.tag().1 != 0x0000 {
let l = e.value().length();
calculated_length += if l.is_defined() { even_len(l.0) } else { 0 } + 8;
}
(e.tag(), e)
})
.collect();
entries.insert(
Tag(0, 0),
InMemElement::new(Tag(0, 0), VR::UL, PrimitiveValue::from(calculated_length)),
);
InMemDicomObject {
entries,
dict,
len: Length::UNDEFINED,
charset_changed: false,
}
}
/// Read an object from a source,
/// using the given decoder
/// and the given dictionary for name lookup.
pub fn read_dataset_with_dict<S>(decoder: S, dict: D) -> Result<Self, ReadError>
where
S: StatefulDecode,
D: DataDictionary,
{
let mut dataset = DataSetReader::new(decoder, Default::default());
InMemDicomObject::build_object(&mut dataset, dict, false, Length::UNDEFINED, None)
}
/// Read an object from a source,
/// using the given data dictionary and transfer syntax.
#[inline]
pub fn read_dataset_with_dict_ts<S>(
from: S,
dict: D,
ts: &TransferSyntax,
) -> Result<Self, ReadError>
where
S: Read,
D: DataDictionary,
{
Self::read_dataset_with_dict_ts_cs(from, dict, ts, SpecificCharacterSet::default())
}
/// Read an object from a source,
/// using the given data dictionary,
/// transfer syntax,
/// and the given character set to assume by default.
///
/// If the attribute _Specific Character Set_ is found in the encoded data,
/// this will override the given character set.
pub fn read_dataset_with_dict_ts_cs<S>(
from: S,
dict: D,
ts: &TransferSyntax,
cs: SpecificCharacterSet,
) -> Result<Self, ReadError>
where
S: Read,
D: DataDictionary,
{
let from = BufReader::new(from);
let mut dataset = DataSetReader::new_with_ts_cs(from, ts, cs).context(CreateParserSnafu)?;
InMemDicomObject::build_object(&mut dataset, dict, false, Length::UNDEFINED, None)
}
// Standard methods follow. They are not placed as a trait implementation
// because they may require outputs to reference the lifetime of self,
// which is not possible without GATs.
/// Retrieve a particular DICOM element by its tag.
///
/// An error is returned if the element does not exist.
/// For an alternative to this behavior,
/// see [`element_opt`](InMemDicomObject::element_opt).
pub fn element(&self, tag: Tag) -> Result<&InMemElement<D>> {
self.entries
.get(&tag)
.context(NoSuchDataElementTagSnafu { tag })
}
/// Retrieve a particular DICOM element by its name.
///
/// This method translates the given attribute name into its tag
/// before retrieving the element.
/// If the attribute is known in advance,
/// using [`element`](InMemDicomObject::element)
/// with a tag constant is preferred.
///
/// An error is returned if the element does not exist.
/// For an alternative to this behavior,
/// see [`element_by_name_opt`](InMemDicomObject::element_by_name_opt).
pub fn element_by_name(&self, name: &str) -> Result<&InMemElement<D>, AccessByNameError> {
let tag = self.lookup_name(name)?;
self.entries
.get(&tag)
.with_context(|| NoSuchDataElementAliasSnafu {
tag,
alias: name.to_string(),
})
}
/// Retrieve a particular DICOM element that might not exist by its tag.
///
/// If the element does not exist,
/// `None` is returned.
pub fn element_opt(&self, tag: Tag) -> Result<Option<&InMemElement<D>>, AccessError> {
match self.element(tag) {
Ok(e) => Ok(Some(e)),
Err(super::AccessError::NoSuchDataElementTag { .. }) => Ok(None),
}
}
/// Get a particular DICOM attribute from this object by tag.
///
/// If the element does not exist,
/// `None` is returned.
pub fn get(&self, tag: Tag) -> Option<&InMemElement<D>> {
self.entries.get(&tag)
}
// Get a mutable reference to a particular DICOM attribute from this object by tag.
//
// Should be private as it would allow a user to change the tag of an
// element and diverge from the dictionary
fn get_mut(&mut self, tag: Tag) -> Option<&mut InMemElement<D>> {
self.entries.get_mut(&tag)
}
/// Retrieve a particular DICOM element that might not exist by its name.
///
/// If the element does not exist,
/// `None` is returned.
///
/// This method translates the given attribute name into its tag
/// before retrieving the element.
/// If the attribute is known in advance,
/// using [`element_opt`](InMemDicomObject::element_opt)
/// with a tag constant is preferred.
pub fn element_by_name_opt(
&self,
name: &str,
) -> Result<Option<&InMemElement<D>>, AccessByNameError> {
match self.element_by_name(name) {
Ok(e) => Ok(Some(e)),
Err(AccessByNameError::NoSuchDataElementAlias { .. }) => Ok(None),
Err(e) => Err(e),
}
}
fn find_private_creator(&self, group: GroupNumber, creator: &str) -> Option<&Tag> {
let range = Tag(group, 0)..Tag(group, 0xFF);
for (tag, elem) in self.entries.range(range) {
// Private Creators are always LO
// https://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/sect_7.8.html
if elem.header().vr() == VR::LO && elem.to_str().unwrap_or_default() == creator {
return Some(tag);
}
}
None
}
/// Get a private element from the dataset using the group number, creator and element number.
///
/// An error is raised when the group number is not odd,
/// the private creator is not found in the group,
/// or the private element is not found.
///
/// For more info, see the [DICOM standard section on private elements][1].
///
/// [1]: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/sect_7.8.html
///
/// ## Example
///
/// ```
/// # use dicom_core::{VR, PrimitiveValue, Tag, DataElement};
/// # use dicom_object::{InMemDicomObject, PrivateElementError};
/// # use std::error::Error;
/// let mut ds = InMemDicomObject::from_element_iter([
/// DataElement::new(
/// Tag(0x0009, 0x0010),
/// VR::LO,
/// PrimitiveValue::from("CREATOR 1"),
/// ),
/// DataElement::new(Tag(0x0009, 0x01001), VR::DS, "1.0"),
/// ]);
/// assert_eq!(
/// ds.private_element(0x0009, "CREATOR 1", 0x01)?
/// .value()
/// .to_str()?,
/// "1.0"
/// );
/// # Ok::<(), Box<dyn Error>>(())
/// ```
pub fn private_element(
&self,
group: GroupNumber,
creator: &str,
element: u8,
) -> Result<&InMemElement<D>, PrivateElementError> {
let tag = self.find_private_creator(group, creator).ok_or_else(|| {
PrivateCreatorNotFoundSnafu {
group,
creator: creator.to_string(),
}
.build()
})?;
let element_num = (tag.element() << 8) | (element as u16);
self.get(Tag(group, element_num)).ok_or_else(|| {
ElementNotFoundSnafu {
group,
creator: creator.to_string(),
elem: element,
}
.build()
})
}
/// Insert a data element to the object, replacing (and returning) any
/// previous element of the same attribute.
/// This might invalidate all sequence and item lengths if the charset of the
/// element changes.
pub fn put(&mut self, elt: InMemElement<D>) -> Option<InMemElement<D>> {
self.put_element(elt)
}
/// Insert a data element to the object, replacing (and returning) any
/// previous element of the same attribute.
/// This might invalidate all sequence and item lengths if the charset of the
/// element changes.
pub fn put_element(&mut self, elt: InMemElement<D>) -> Option<InMemElement<D>> {
self.len = Length::UNDEFINED;
self.invalidate_if_charset_changed(elt.tag());
self.entries.insert(elt.tag(), elt)
}
/// Insert a private element into the dataset, replacing (and returning) any
/// previous element of the same attribute.
///
/// This function will find the next available private element block in the given
/// group. If the creator already exists, the element will be added to the block
/// already reserved for that creator. If it does not exist, then a new block
/// will be reserved for the creator in the specified group.
/// An error is returned if there is no space left in the group.
///
/// For more info, see the [DICOM standard section on private elements][1].
///
/// [1]: https://dicom.nema.org/medical/dicom/2024a/output/chtml/part05/sect_7.8.html
///
/// ## Example
/// ```
/// # use dicom_core::{VR, PrimitiveValue, Tag, DataElement, header::Header};
/// # use dicom_object::InMemDicomObject;
/// # use std::error::Error;
/// let mut ds = InMemDicomObject::new_empty();
/// ds.put_private_element(
/// 0x0009,
/// "CREATOR 1",
/// 0x02,
/// VR::DS,
/// PrimitiveValue::from("1.0"),
/// )?;
/// assert_eq!(
/// ds.private_element(0x0009, "CREATOR 1", 0x02)?
/// .value()
/// .to_str()?,
/// "1.0"
/// );
/// assert_eq!(
/// ds.private_element(0x0009, "CREATOR 1", 0x02)?
/// .header()
/// .tag(),
/// Tag(0x0009, 0x0102)
/// );
/// # Ok::<(), Box<dyn Error>>(())
/// ```
pub fn put_private_element(
&mut self,
group: GroupNumber,
creator: &str,
element: u8,
vr: VR,
value: PrimitiveValue,
) -> Result<Option<InMemElement<D>>, PrivateElementError> {
ensure!(group % 2 == 1, InvalidGroupSnafu { group });
let private_creator = self.find_private_creator(group, creator);
if let Some(tag) = private_creator {
// Private creator already exists
let tag = Tag(group, tag.element() << 8 | (element as u16));
Ok(self.put_element(DataElement::new(tag, vr, value)))
} else {
// Find last reserved block of tags.
let range = Tag(group, 0)..Tag(group, 0xFF);
let last_entry = self.entries.range(range).next_back();
let next_available = match last_entry {
Some((tag, _)) => tag.element() + 1,
None => 0x01,
};
if next_available < 0xFF {
// Put private creator
let tag = Tag(group, next_available);
self.put_str(tag, VR::LO, creator);
// Put private element
let tag = Tag(group, next_available << 8 | (element as u16));
Ok(self.put_element(DataElement::new(tag, vr, value)))
} else {
NoSpaceSnafu { group }.fail()
}
}
}
/// Insert a new element with a string value to the object,
/// replacing (and returning) any previous element of the same attribute.
pub fn put_str(
&mut self,
tag: Tag,
vr: VR,
string: impl Into<String>,
) -> Option<InMemElement<D>> {
self.put_element(DataElement::new(tag, vr, string.into()))
}
/// Remove a DICOM element by its tag,
/// reporting whether it was present.
pub fn remove_element(&mut self, tag: Tag) -> bool {
if self.entries.remove(&tag).is_some() {
self.len = Length::UNDEFINED;
true
} else {
false
}
}
/// Remove a DICOM element by its keyword,
/// reporting whether it was present.
pub fn remove_element_by_name(&mut self, name: &str) -> Result<bool, AccessByNameError> {
let tag = self.lookup_name(name)?;
Ok(self.entries.remove(&tag).is_some()).map(|removed| {
if removed {
self.len = Length::UNDEFINED;
}
removed
})
}
/// Remove and return a particular DICOM element by its tag.
pub fn take_element(&mut self, tag: Tag) -> Result<InMemElement<D>> {
self.entries
.remove(&tag)
.map(|e| {
self.len = Length::UNDEFINED;
e
})
.context(NoSuchDataElementTagSnafu { tag })
}
/// Remove and return a particular DICOM element by its tag,
/// if it is present,
/// returns `None` otherwise.
pub fn take(&mut self, tag: Tag) -> Option<InMemElement<D>> {
self.entries.remove(&tag).map(|e| {
self.len = Length::UNDEFINED;
e
})
}
/// Remove and return a particular DICOM element by its name.
pub fn take_element_by_name(
&mut self,
name: &str,
) -> Result<InMemElement<D>, AccessByNameError> {
let tag = self.lookup_name(name)?;
self.entries
.remove(&tag)
.map(|e| {
self.len = Length::UNDEFINED;
e
})
.with_context(|| NoSuchDataElementAliasSnafu {
tag,
alias: name.to_string(),
})
}
/// Modify the object by
/// retaining only the DICOM data elements specified by the predicate.
///
/// The elements are visited in ascending tag order,
/// and those for which `f(&element)` returns `false` are removed.
pub fn retain(&mut self, mut f: impl FnMut(&InMemElement<D>) -> bool) {
self.entries.retain(|_, elem| f(elem));
self.len = Length::UNDEFINED;
}
/// Obtain a temporary mutable reference to a DICOM value by tag,
/// so that mutations can be applied within.
///
/// If found, this method resets all related lengths recorded
/// and returns `true`.
/// Returns `false` otherwise.
///
/// # Example
///
/// ```
/// # use dicom_core::{DataElement, VR, dicom_value};
/// # use dicom_dictionary_std::tags;
/// # use dicom_object::InMemDicomObject;
/// let mut obj = InMemDicomObject::from_element_iter([
/// DataElement::new(tags::LOSSY_IMAGE_COMPRESSION_RATIO, VR::DS, dicom_value!(Strs, ["25"])),
/// ]);
///
/// // update lossy image compression ratio
/// obj.update_value(tags::LOSSY_IMAGE_COMPRESSION_RATIO, |e| {
/// e.primitive_mut().unwrap().extend_str(["2.56"]);
/// });
///
/// assert_eq!(
/// obj.get(tags::LOSSY_IMAGE_COMPRESSION_RATIO).unwrap().value().to_str().unwrap(),
/// "25\\2.56"
/// );
/// ```
pub fn update_value(
&mut self,
tag: Tag,
f: impl FnMut(&mut Value<InMemDicomObject<D>, InMemFragment>),
) -> bool {
self.invalidate_if_charset_changed(tag);
if let Some(e) = self.entries.get_mut(&tag) {
e.update_value(f);
self.len = Length::UNDEFINED;
true
} else {
false
}
}
/// Obtain a temporary mutable reference to a DICOM value by AttributeSelector,
/// so that mutations can be applied within.
///
/// If found, this method resets all related lengths recorded
/// and returns `true`.
/// Returns `false` otherwise.
///