dicom-object 0.9.1

A high-level API for reading and manipulating DICOM objects
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
#![allow(clippy::derive_partial_eq_without_eq)]
//! 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.
//!
//!
//! ## Overview
//!
//! - Most interactions with DICOM objects
//!   will involve in-memory representations of the data set,
//!   through the type [`InMemDicomObject`].
//!   New DICOM instances can also be built from scratch using this type.
//!   A wide assortment of methods are available
//!   for reading and manipulating the data set.
//!   See the [`mem`] module for more details.
//! - Loading a DICOM file can be done with ease via the function [`open_file`].
//!   For additional file reading options, use [`OpenFileOptions`].
//!   These are all available in the [`mod@file`] module.
//! - Other implementations of a DICOM object may exist
//!   to better serve other use cases.
//!   If generic support for any DICOM object implementation is a requirement,
//!   you can try using the [`DicomObject`] trait.
//! - Currently, the default file DICOM object implementation
//!   loads the complete contents of the file in memory,
//!   including pixel data.
//!   To read DICOM data sets in smaller portions,
//!   you can use the [DICOM collector API](collector).
//!
//! # Encodings
//!
//! By default, `dicom-object` supports reading and writing DICOM files
//! in any transfer syntax without data set compression.
//! This includes _Explicit VR Little Endian_
//! (with or without encapsulated pixel data),
//! _Implicit VR Little Endian_,
//! and _Explicit VR Big Endian_ (retired).
//! To enable support for reading and writing deflated data sets
//! (such as _Deflated Explicit VR Little Endian_),
//! enable **Cargo feature `deflated`**.
//!
//! When working with imaging data,
//! consider using the [`dicom-pixeldata`] crate,
//! which offers methods to convert pixel data from objects
//! into images or multi-dimensional arrays.
//!
//! # Examples
//!
//! ## Reading a DICOM file
//!
//! To read an object from a DICOM file and inspect some attributes:
//!
//! ```no_run
//! use dicom_dictionary_std::tags;
//! use dicom_object::open_file;
//! # fn foo() -> Result<(), Box<dyn std::error::Error>> {
//! let obj = open_file("0001.dcm")?;
//!
//! let patient_name = obj.element(tags::PATIENT_NAME)?.to_str()?;
//! let modality = obj.element_by_name("Modality")?.to_str()?;
//! # Ok(())
//! # }
//! ```
//!
//! Elements can be fetched by tag,
//! either by creating a [`Tag`]
//! or by using one of the [readily available constants][const]
//! from the [`dicom-dictionary-std`][dictionary-std] crate.
//!
//! [const]: dicom_dictionary_std::tags
//! [dictionary-std]: https://docs.rs/dicom-dictionary-std
//!
//! By default, the entire data set is fully loaded into memory.
//! The pixel data and following elements can be ignored
//! by using [`OpenFileOptions`]:
//!
//! ```no_run
//! use dicom_object::OpenFileOptions;
//!
//! let obj = OpenFileOptions::new()
//!     .read_until(dicom_dictionary_std::tags::PIXEL_DATA)
//!     .open_file("0002.dcm")?;
//! # Result::<(), dicom_object::ReadError>::Ok(())
//! ```
//!
//! When reading from other data sources without file meta information,
//! you may need to use [`InMemDicomObject::read_dataset`]
//! and specify the transfer syntax explicitly.
//!
//! ## Fetching data in a DICOM file
//!
//! Once a data set element is looked up,
//! one will typically wish to inspect the value within.
//! Methods are available for converting the element's DICOM value
//! into something more usable in Rust.
//!
//! ```
//! # use dicom_dictionary_std::tags;
//! # use dicom_object::{DefaultDicomObject, Tag};
//! # fn something(obj: DefaultDicomObject) -> Result<(), Box<dyn std::error::Error>> {
//! let patient_date = obj.element(tags::PATIENT_BIRTH_DATE)?.to_date()?;
//! let pixel_data_bytes = obj.element(tags::PIXEL_DATA)?.to_bytes()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Writing DICOM
//!
//! **Note:** the code above will only work if you are fetching native pixel data.
//! If you are potentially working with encapsulated pixel data,
//! see the [`dicom-pixeldata`] crate.
//!
//! [`dicom-pixeldata`]: https://docs.rs/dicom-pixeldata
//!
//! ## Writing DICOM data
//!
//! 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
//! [`with_meta`]: crate::InMemDicomObject::with_meta
//! [`with_exact_meta`]: crate::InMemDicomObject::with_exact_meta
//!
//! ```no_run
//! # use dicom_object::{InMemDicomObject, FileMetaTableBuilder};
//! # fn something(obj: InMemDicomObject) -> Result<(), Box<dyn std::error::Error>> {
//! use dicom_dictionary_std::uids;
//!
//! let file_obj = obj.with_meta(
//!     FileMetaTableBuilder::new()
//!         // Implicit VR Little Endian
//!         .transfer_syntax(uids::IMPLICIT_VR_LITTLE_ENDIAN)
//!         // 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 data set writing methods
//! such as [`write_dataset_with_ts`]:
//!
//! [`write_dataset_with_ts`]: InMemDicomObject::write_dataset_with_ts
//!
//! ```
//! # use dicom_object::InMemDicomObject;
//! # use dicom_core::{DataElement, Tag, VR};
//! # fn run() -> Result<(), Box<dyn std::error::Error>> {
//! // build your object
//! let mut obj = InMemDicomObject::from_element_iter([
//!     DataElement::new(
//!         Tag(0x0010, 0x0010),
//!         VR::PN,
//!         "Doe^John",
//!     ),
//! ]);
//!
//! // 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_eq!(
//!     serialized.len(),
//!     16, // 4 (tag) + 2 (VR) + 2 (length) + 8 (data)
//! );
//! # Ok(())
//! # }
//! # run().unwrap();
//! ```
pub mod collector;
pub mod file;
pub mod mem;
pub mod meta;
pub mod ops;
pub mod tokens;

pub use crate::collector::{DicomCollector, DicomCollectorOptions};
pub use crate::file::{from_reader, open_file, OpenFileOptions};
pub use crate::mem::InMemDicomObject;
pub use crate::meta::{FileMetaTable, FileMetaTableBuilder};
use dicom_core::ops::{AttributeSelector, AttributeSelectorStep};
use dicom_core::value::{DicomValueType, ValueType};
pub use dicom_core::Tag;
use dicom_core::{DataDictionary, DicomValue, PrimitiveValue};
use dicom_dictionary_std::uids;
pub use dicom_dictionary_std::StandardDataDictionary;

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

use dicom_core::header::{GroupNumber, HasLength};
use dicom_encoding::adapters::{PixelDataObject, RawPixelData};
use dicom_encoding::transfer_syntax::TransferSyntaxIndex;
use dicom_encoding::Codec;
use dicom_parser::dataset::{DataSetWriter, IntoTokens};
use dicom_transfer_syntax_registry::TransferSyntaxRegistry;
use itertools::Either;
use meta::FileMetaAttribute;
use smallvec::SmallVec;
use snafu::{prelude::*, Backtrace};
use std::borrow::Cow;
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 may change in future versions,
/// even between patch versions.
pub const IMPLEMENTATION_CLASS_UID: &str = "2.25.269557681719719925684832053554655571250";

/// The current implementation version name generically referring to DICOM-rs.
///
/// This name may change in future versions,
/// even between patch versions.
pub const IMPLEMENTATION_VERSION_NAME: &str = "DICOM-rs 0.9.1";

/// An error which occurs when fetching a value
#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum AttributeError {
    /// A custom error when encoding fails.
    /// Read the `message` and the underlying `source`
    /// for more details.
    #[snafu(whatever, display("{}", message))]
    Custom {
        /// The error message.
        message: String,
        /// The underlying error cause, if any.
        #[snafu(source(from(Box<dyn std::error::Error + Send + Sync + 'static>, Some)))]
        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
    },

    /// the value cannot be converted to the requested type
    ConvertValue {
        source: dicom_core::value::ConvertValueError,
    },

    /// the value is not a data set sequence
    NotDataSet,

    /// the requested item index does not exist
    DataSetItemOutOfBounds,

    /// the value is not a pixel data element
    NotPixelData,

    /// the requested pixel data fragment index does not exist
    FragmentOutOfBounds,
}

/// Interface type for access to a DICOM object' attribute in a DICOM object.
///
/// Accessing an attribute via the [`DicomObject`] trait
/// will generally result in a value of this type,
/// which can then be converted into a more usable form.
///
/// Both [`DicomValue`] and references to it implement this trait.
pub trait DicomAttribute: DicomValueType {
    /// The data type of an item in a data set sequence
    type Item<'a>: HasLength
    where
        Self: 'a;

    /// The data type of a single contiguous pixel data fragment
    type PixelData<'a>
    where
        Self: 'a;

    /// Obtain an in-memory representation of the primitive value,
    /// cloning the value if necessary.
    ///
    /// An error is returned if the value is a data set sequence or
    /// an encapsulated pixel data fragment sequence.
    fn to_primitive_value(&self) -> Result<PrimitiveValue, AttributeError>;

    /// Obtain one of the items in the attribute,
    /// if the attribute value represents a data set sequence.
    ///
    /// Returns an error if the attribute is not a sequence.
    fn item(&self, index: u32) -> Result<Self::Item<'_>, AttributeError>;

    /// Obtain the number of data set items or pixel data fragments,
    /// if the attribute value represents a data set sequence or pixel data.
    /// Returns `None` otherwise.
    fn num_items(&self) -> Option<u32>;

    /// Obtain one of the fragments in the attribute,
    /// if the attribute value represents a pixel data fragment sequence.
    ///
    /// Returns an error if the attribute is not a pixel data sequence.
    fn fragment(&self, index: u32) -> Result<Self::PixelData<'_>, AttributeError>;

    /// Obtain the number of pixel data fragments,
    /// if the attribute value represents encapsulated pixel data.
    ///
    /// It should equivalent to `num_items`,
    /// save for returning `None` if the attribute is a data set sequence.
    fn num_fragments(&self) -> Option<u32> {
        if DicomValueType::value_type(self) == ValueType::PixelSequence {
            self.num_items()
        } else {
            None
        }
    }

    /// Obtain the attribute's value as a string,
    /// converting it if necessary.
    fn to_str(&self) -> Result<Cow<'_, str>, AttributeError> {
        Ok(Cow::Owned(self.to_primitive_value()?.to_str().to_string()))
    }

    /// Obtain the attribute's value as a 16-bit unsigned integer,
    /// converting it if necessary.
    fn to_u16(&self) -> Result<u16, AttributeError> {
        self.to_primitive_value()?
            .to_int()
            .context(ConvertValueSnafu)
    }

    /// Obtain the attribute's value as a 32-bit signed integer,
    /// converting it if necessary.
    fn to_i32(&self) -> Result<i32, AttributeError> {
        self.to_primitive_value()?
            .to_int()
            .context(ConvertValueSnafu)
    }

    /// Obtain the attribute's value as a 32-bit unsigned integer,
    /// converting it if necessary.
    fn to_u32(&self) -> Result<u32, AttributeError> {
        self.to_primitive_value()?
            .to_int()
            .context(ConvertValueSnafu)
    }

    /// Obtain the attribute's value as a 32-bit floating-point number,
    /// converting it if necessary.
    fn to_f32(&self) -> Result<f32, AttributeError> {
        self.to_primitive_value()?
            .to_float32()
            .context(ConvertValueSnafu)
    }

    /// Obtain the attribute's value as a 64-bit floating-point number,
    /// converting it if necessary.
    fn to_f64(&self) -> Result<f64, AttributeError> {
        self.to_primitive_value()?
            .to_float64()
            .context(ConvertValueSnafu)
    }

    /// Obtain the attribute's value as bytes,
    /// converting it if necessary.
    fn to_bytes(&self) -> Result<Cow<'_, [u8]>, AttributeError> {
        Ok(Cow::Owned(self.to_primitive_value()?.to_bytes().to_vec()))
    }
}

/// Trait type for a generalized interpretation of a DICOM object.
///
/// This is a high-level abstraction where an object is accessed and
/// manipulated as a dictionary of entries indexed by tags, which in
/// turn may contain a DICOM object.
///
/// ## Examples
///
/// You can use this trait to operate on DICOM data sets
/// when the exact DICOM object type is not known.
///
/// ```
/// # use dicom_core::prelude::*;
/// # use dicom_dictionary_std::tags;
/// # use dicom_object::mem::InMemDicomObject;
/// use dicom_object::DicomObject;
/// use dicom_object::DicomAttribute as _;
///
/// fn my_data() -> impl DicomObject {
///     InMemDicomObject::from_element_iter([
///         DataElement::new(
///             tags::SOP_INSTANCE_UID,
///             VR::UI,
///             "2.25.60131396312732822704775296119377475501",
///         ),
///     ])
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let obj = my_data();
/// assert_eq!(
///     obj.attr(tags::SOP_INSTANCE_UID)?.to_str()?,
///    "2.25.60131396312732822704775296119377475501"
/// );
/// # Ok(())
/// # }
/// ```
///
/// It works for in-memory data sets, file meta groups,
/// and other similar structures.
/// When operating on DICOM file objects,
/// the look-up will be directed to the right group
/// depending on the attribute requested.
///
/// ```no_run
/// # use dicom_dictionary_std::tags;
/// use dicom_object::{DicomObject as _, open_file};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let file = open_file("00001.dcm")?;
///
/// let Some(media_storage_sop_class_uid) = file.attr_opt(tags::MEDIA_STORAGE_SOP_CLASS_UID)? else {
///     panic!("DICOM file should have a Media Storage SOP Class UID");
/// };
/// # Ok(())
/// # }
/// ```
///
/// Types implementing this trait
/// will likely also implement [`ApplyOp`](dicom_core::ops::ApplyOp),
/// enabling more operations on DICOM objects.
pub trait DicomObject {
    /// The type representing a DICOM attribute in the object
    /// and/or the necessary means to retrieve the value from it.
    ///
    /// This is the outcome of a shallow look-up
    /// using the methods [`attr`](DicomObject::attr)
    /// or [`attr_opt`](DicomObject::attr_opt).
    type Attribute<'a>: DicomAttribute
    where
        Self: 'a;

    /// The type representing a DICOM leaf attribute in the object
    /// and/or the necessary means to retrieve the value from it.
    ///
    /// This is the outcome of a potentially deep look-up
    /// using the method [`at`](DicomObject::at).
    type LeafAttribute<'a>: DicomAttribute
    where
        Self: 'a;

    /// Retrieve a particular DICOM attribute
    /// by looking up the given tag at the object's root.
    ///
    /// `Ok(None)` is returned when the object was successfully looked up
    /// but the element is not present.
    /// This is not a recursive search.
    fn attr_opt(&self, tag: Tag) -> Result<Option<Self::Attribute<'_>>, AccessError>;

    /// Retrieve a particular DICOM element by its name (keyword).
    ///
    /// `Ok(None)` is returned when the object was successfully looked up
    /// but the element is not present.
    ///
    /// If the DICOM tag is already known,
    /// prefer calling [`attr_opt`](Self::attr_opt)
    /// with one of the [constants from the DICOM dictionary][tags].
    ///
    /// [tags]: dicom_dictionary_std::tags
    fn attr_by_name_opt(
        &self,
        name: &str,
    ) -> Result<Option<Self::Attribute<'_>>, AccessByNameError>;

    /// Retrieve a particular DICOM attribute
    /// by looking up the given tag at the object's root.
    ///
    /// Unlike [`attr_opt`](Self::attr_opt),
    /// this method returns an error if the element is not present.
    fn attr(&self, tag: Tag) -> Result<Self::Attribute<'_>, AccessError> {
        self.attr_opt(tag)?
            .context(NoSuchDataElementTagSnafu { tag })
    }

    /// Retrieve a particular DICOM attribute
    /// with a look-up by attribute selector.
    ///
    /// This method returns an error if the element is not present.
    fn at(
        &self,
        selector: impl Into<AttributeSelector>,
    ) -> Result<Self::LeafAttribute<'_>, AtAccessError>;

    /// Retrieve a particular DICOM element by its name (keyword).
    ///
    /// Unlike [`attr_by_name_opt`](Self::attr_by_name_opt),
    /// this method returns an error if the element is not present.
    ///
    /// If the DICOM tag is already known,
    /// prefer calling [`attr`](Self::attr)
    /// with one of the [constants from the DICOM dictionary][tags].
    ///
    /// [tags]: dicom_dictionary_std::tags
    fn attr_by_name(&self, name: &str) -> Result<Self::Attribute<'_>, AccessByNameError> {
        self.attr_by_name_opt(name)?
            .context(NoSuchAttributeNameSnafu { name })
    }
}

impl<O, P> DicomAttribute for DicomValue<O, P>
where
    O: HasLength,
    for<'a> &'a O: HasLength,
{
    type Item<'a>
        = &'a O
    where
        Self: 'a,
        O: 'a;
    type PixelData<'a>
        = &'a P
    where
        Self: 'a,
        P: 'a;

    #[inline]
    fn to_primitive_value(&self) -> Result<PrimitiveValue, AttributeError> {
        match self {
            DicomValue::Primitive(value) => Ok(value.clone()),
            _ => Err(AttributeError::ConvertValue {
                source: dicom_core::value::ConvertValueError {
                    requested: "primitive",
                    original: self.value_type(),
                    cause: None,
                },
            }),
        }
    }

    #[inline]
    fn item(&self, index: u32) -> Result<&O, AttributeError> {
        let items = self.items().context(NotDataSetSnafu)?;
        items
            .get(index as usize)
            .context(DataSetItemOutOfBoundsSnafu)
    }

    #[inline]
    fn num_items(&self) -> Option<u32> {
        match self {
            DicomValue::PixelSequence(seq) => Some(seq.fragments().len() as u32),
            DicomValue::Sequence(seq) => Some(seq.multiplicity()),
            _ => None,
        }
    }

    #[inline]
    fn fragment(&self, index: u32) -> Result<Self::PixelData<'_>, AttributeError> {
        match self {
            DicomValue::PixelSequence(seq) => Ok(seq
                .fragments()
                .get(index as usize)
                .context(FragmentOutOfBoundsSnafu)?),
            _ => Err(AttributeError::NotPixelData),
        }
    }

    #[inline]
    fn to_str(&self) -> Result<Cow<'_, str>, AttributeError> {
        DicomValue::to_str(self).context(ConvertValueSnafu)
    }

    #[inline]
    fn to_bytes(&self) -> Result<Cow<'_, [u8]>, AttributeError> {
        DicomValue::to_bytes(self).context(ConvertValueSnafu)
    }
}

impl<'b, O, P> DicomAttribute for &'b DicomValue<O, P>
where
    O: HasLength,
    &'b O: HasLength,
    O: Clone,
    P: Clone,
{
    type Item<'a>
        = &'b O
    where
        Self: 'a,
        O: 'a;
    type PixelData<'a>
        = &'b P
    where
        Self: 'a,
        P: 'a;

    #[inline]
    fn to_primitive_value(&self) -> Result<PrimitiveValue, AttributeError> {
        match self {
            DicomValue::Primitive(value) => Ok(value.clone()),
            _ => Err(AttributeError::ConvertValue {
                source: dicom_core::value::ConvertValueError {
                    requested: "primitive",
                    original: self.value_type(),
                    cause: None,
                },
            }),
        }
    }

    #[inline]
    fn item(&self, index: u32) -> Result<Self::Item<'_>, AttributeError> {
        let items = self.items().context(NotDataSetSnafu)?;
        items
            .get(index as usize)
            .context(DataSetItemOutOfBoundsSnafu)
    }

    #[inline]
    fn num_items(&self) -> Option<u32> {
        match self {
            DicomValue::PixelSequence(seq) => Some(seq.fragments().len() as u32),
            DicomValue::Sequence(seq) => Some(seq.multiplicity()),
            _ => None,
        }
    }

    #[inline]
    fn fragment(&self, index: u32) -> Result<Self::PixelData<'_>, AttributeError> {
        match self {
            DicomValue::PixelSequence(seq) => seq
                .fragments()
                .get(index as usize)
                .context(FragmentOutOfBoundsSnafu),
            _ => Err(AttributeError::NotPixelData),
        }
    }

    #[inline]
    fn num_fragments(&self) -> Option<u32> {
        match self {
            DicomValue::PixelSequence(seq) => Some(seq.fragments().len() as u32),
            _ => None,
        }
    }

    #[inline]
    fn to_str(&self) -> Result<Cow<'_, str>, AttributeError> {
        DicomValue::to_str(self).context(ConvertValueSnafu)
    }

    #[inline]
    fn to_bytes(&self) -> Result<Cow<'_, [u8]>, AttributeError> {
        DicomValue::to_bytes(self).context(ConvertValueSnafu)
    }
}

/// An error which may occur when loading a DICOM object
#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum ReadError {
    #[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,
    },
    /// Could not read preamble bytes
    ReadPreambleBytes {
        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 parse sop attribute"))]
    ParseSopAttribute {
        #[snafu(source(from(dicom_core::value::ConvertValueError, Box::from)))]
        source: Box<dicom_core::value::ConvertValueError>,
        backtrace: Backtrace,
    },
    #[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("Missing element value after header token"))]
    MissingElementValue { backtrace: Backtrace },
    #[snafu(display("Unrecognized transfer syntax `{}`", uid))]
    ReadUnrecognizedTransferSyntax { uid: String, backtrace: Backtrace },
    #[snafu(display("Unsupported reading for transfer syntax `{}` ({})", uid, name))]
    ReadUnsupportedTransferSyntax {
        uid: &'static str,
        name: &'static str,
        backtrace: Backtrace,
    },
    #[snafu(display(
        "Unsupported reading for transfer syntax `{uid}` ({name}, try enabling feature `{feature_name}`)"
    ))]
    ReadUnsupportedTransferSyntaxWithSuggestion {
        uid: &'static str,
        name: &'static str,
        feature_name: &'static str,
        backtrace: Backtrace,
    },
    #[snafu(display("Unexpected token {:?}", token))]
    UnexpectedToken {
        token: Box<dicom_parser::dataset::DataToken>,
        backtrace: Backtrace,
    },
    #[snafu(display("Premature data set end"))]
    PrematureEnd { backtrace: Backtrace },
}

/// An error which may occur when writing a DICOM object
#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum WriteError {
    #[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("Unrecognized transfer syntax `{uid}`"))]
    WriteUnrecognizedTransferSyntax { uid: String, backtrace: Backtrace },
    #[snafu(display("Unsupported transfer syntax `{uid}` ({name})"))]
    WriteUnsupportedTransferSyntax {
        uid: &'static str,
        name: &'static str,
        backtrace: Backtrace,
    },
    #[snafu(display(
        "Unsupported transfer syntax `{uid}` ({name}, try enabling feature `{feature_name}`)"
    ))]
    WriteUnsupportedTransferSyntaxWithSuggestion {
        uid: &'static str,
        name: &'static str,
        feature_name: &'static str,
        backtrace: Backtrace,
    },
}

/// An error which may occur during private element look-up or insertion
#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum PrivateElementError {
    /// Group number must be odd
    #[snafu(display("Group number must be odd, found {:#06x}", group))]
    InvalidGroup { group: GroupNumber },
    /// Private creator not found in group
    #[snafu(display("Private creator {} not found in group {:#06x}", creator, group))]
    PrivateCreatorNotFound { creator: String, group: GroupNumber },
    /// Element not found in group
    #[snafu(display(
        "Private Creator {} found in group {:#06x}, but elem {:#06x} not found",
        creator,
        group,
        elem
    ))]
    ElementNotFound {
        creator: String,
        group: GroupNumber,
        elem: u8,
    },
    /// No space available for more private elements in the group
    #[snafu(display("No space available in group {:#06x}", group))]
    NoSpace { group: GroupNumber },
}

/// An error which may occur when looking up a DICOM object's attributes.
#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum AccessError {
    #[snafu(display("No such data element with tag {}", tag))]
    NoSuchDataElementTag { tag: Tag, backtrace: Backtrace },
}

impl AccessError {
    pub fn into_access_by_name(self, alias: impl Into<String>) -> AccessByNameError {
        match self {
            AccessError::NoSuchDataElementTag { tag, backtrace } => {
                AccessByNameError::NoSuchDataElementAlias {
                    tag,
                    alias: alias.into(),
                    backtrace,
                }
            }
        }
    }
}

/// An error which may occur when looking up a DICOM object's attributes
/// at an arbitrary depth,
/// such as through [`value_at`](crate::InMemDicomObject::value_at).
#[derive(Debug, Snafu)]
#[non_exhaustive]
#[snafu(visibility(pub(crate)))]
pub enum AtAccessError {
    /// Missing intermediate sequence for {selector} at step {step_index}
    MissingSequence {
        selector: AttributeSelector,
        step_index: u32,
    },
    /// Step {step_index} for {selector} is not a data set sequence
    NotASequence {
        selector: AttributeSelector,
        step_index: u32,
    },
    /// Missing element at last step for {selector}
    MissingLeafElement { selector: AttributeSelector },
}

/// An error which may occur when looking up a DICOM object's attributes
/// by a keyword (or alias) instead of by tag.
///
/// These accesses incur a look-up at the data element dictionary,
/// which may fail if no such entry exists.
#[derive(Debug, Snafu)]
pub enum AccessByNameError {
    #[snafu(display("No such data element {} (with tag {})", alias, tag))]
    NoSuchDataElementAlias {
        tag: Tag,
        alias: String,
        backtrace: Backtrace,
    },

    /// Could not resolve attribute name from the data dictionary
    #[snafu(display("Unknown data attribute named `{}`", name))]
    NoSuchAttributeName { name: String, backtrace: Backtrace },
}

#[derive(Debug, Snafu)]
#[non_exhaustive]
pub enum WithMetaError {
    /// Could not build file meta table
    BuildMetaTable {
        #[snafu(backtrace)]
        source: crate::meta::Error,
    },
    /// Could not prepare file meta table
    PrepareMetaTable {
        #[snafu(source(from(dicom_core::value::ConvertValueError, Box::from)))]
        source: Box<dicom_core::value::ConvertValueError>,
        backtrace: Backtrace,
    },
}

/// A root DICOM object retrieved from a standard DICOM file,
/// containing additional information from the file meta group
/// in a separate table value.
///
/// **Note:** This type implements `Deref` towards the inner object,
/// meaning that most method calls will be directed
/// as if the call was performed directly on the main data set.
/// While this is convenient,
/// it also means that data elements from the file meta group
/// cannot be accessed without explicitly taking a reference
/// first through [`meta()`](FileDicomObject::meta).
/// To abstract this away,
/// see the [`DicomObject`] trait.
#[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 a mutable reference to the processed meta header table.
    ///
    /// Considerable care should be taken when modifying this table,
    /// as it may influence object reading and writing operations.
    /// When modifying the table through this method,
    /// the user is responsible for updating the meta information group length as well,
    /// which can be done by calling
    /// [`update_information_group_length`](FileMetaTable::update_information_group_length).
    ///
    /// See also [`update_meta`](Self::update_meta).
    pub fn meta_mut(&mut self) -> &mut FileMetaTable {
        &mut self.meta
    }

    /// Update the processed meta header table through a function.
    ///
    /// Considerable care should be taken when modifying this table,
    /// as it may influence object reading and writing operations.
    /// The meta information group length is updated automatically.
    pub fn update_meta(&mut self, f: impl FnOnce(&mut FileMetaTable)) {
        f(&mut self.meta);
        self.meta.update_information_group_length();
    }

    /// 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<(), WriteError> {
        let path = path.as_ref();
        let file = File::create(path).context(WriteFileSnafu { filename: path })?;
        let mut to = BufWriter::new(file);

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

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

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

        self.write_dataset_impl(to)
    }

    /// 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(&self, to: impl Write) -> Result<(), WriteError> {
        let mut to = BufWriter::new(to);

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

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

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

        self.write_dataset_impl(to)
    }

    /// 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<(), WriteError> {
        self.meta.write(to).context(PrintMetaDataSetSnafu)
    }

    /// 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<(), WriteError> {
        let to = BufWriter::new(to);

        self.write_dataset_impl(to)
    }

    /// Helper function for writing the DICOM data set in this file DICOM object
    /// with the right transfer syntax.
    /// Automatically retrieves a data set adapter if required and available,
    /// returns an error if the transfer syntax is not supported for data set writing.
    fn write_dataset_impl(&self, to: impl Write) -> Result<(), WriteError> {
        let ts_uid = self.meta.transfer_syntax();
        // prepare encoder
        let ts = if let Some(ts) = TransferSyntaxRegistry.get(ts_uid) {
            ts
        } else {
            return WriteUnrecognizedTransferSyntaxSnafu {
                uid: ts_uid.to_string(),
            }
            .fail();
        };
        match ts.codec() {
            Codec::Dataset(Some(adapter)) => {
                let adapter = adapter.adapt_writer(Box::new(to));
                let mut dset_writer =
                    DataSetWriter::with_ts(adapter, ts).context(CreatePrinterSnafu)?;

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

                dset_writer.flush().context(PrintDataSetSnafu)?;

                Ok(())
            }
            Codec::Dataset(None) => {
                // dataset adapter needed, but not provided
                if ts_uid == uids::DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN
                    || ts_uid == uids::JPIP_REFERENCED_DEFLATE
                    || ts_uid == uids::JPIPHTJ2K_REFERENCED_DEFLATE
                {
                    return WriteUnsupportedTransferSyntaxWithSuggestionSnafu {
                        uid: ts.uid(),
                        name: ts.name(),
                        feature_name: "dicom-transfer-syntax-registry/deflate",
                    }
                    .fail();
                }
                WriteUnsupportedTransferSyntaxSnafu {
                    uid: ts.uid(),
                    name: ts.name(),
                }
                .fail()
            }
            Codec::None | Codec::EncapsulatedPixelData(..) => {
                // no dataset adapter needed
                let mut dset_writer = DataSetWriter::with_ts(to, ts).context(CreatePrinterSnafu)?;

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

                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<L, R> DicomAttribute for Either<L, R>
where
    L: DicomAttribute,
    R: DicomAttribute,
{
    type Item<'a>
        = Either<L::Item<'a>, R::Item<'a>>
    where
        Self: 'a;
    type PixelData<'a>
        = Either<L::PixelData<'a>, R::PixelData<'a>>
    where
        Self: 'a;

    fn to_primitive_value(&self) -> Result<PrimitiveValue, AttributeError> {
        match self {
            Either::Left(l) => l.to_primitive_value(),
            Either::Right(r) => r.to_primitive_value(),
        }
    }

    fn item(&self, index: u32) -> Result<Self::Item<'_>, AttributeError> {
        match self {
            Either::Left(l) => l.item(index).map(Either::Left),
            Either::Right(r) => r.item(index).map(Either::Right),
        }
    }

    fn num_items(&self) -> Option<u32> {
        match self {
            Either::Left(l) => l.num_items(),
            Either::Right(r) => r.num_items(),
        }
    }

    fn fragment(&self, index: u32) -> Result<Self::PixelData<'_>, AttributeError> {
        match self {
            Either::Left(l) => l.fragment(index).map(Either::Left),
            Either::Right(r) => r.fragment(index).map(Either::Right),
        }
    }
}

impl<O> DicomObject for FileDicomObject<O>
where
    O: DicomObject,
{
    type Attribute<'a>
        = Either<FileMetaAttribute<'a>, O::Attribute<'a>>
    where
        Self: 'a,
        O: 'a;

    type LeafAttribute<'a>
        = Either<FileMetaAttribute<'a>, O::LeafAttribute<'a>>
    where
        Self: 'a,
        O: 'a;

    #[inline]
    fn attr_opt(&self, tag: Tag) -> Result<Option<Self::Attribute<'_>>, AccessError> {
        match tag {
            Tag(0x0002, _) => {
                let attr = self.meta.attr_opt(tag)?;
                Ok(attr.map(Either::Left))
            }
            _ => {
                let attr = self.obj.attr_opt(tag)?;
                Ok(attr.map(Either::Right))
            }
        }
    }

    #[inline]
    fn attr_by_name_opt(
        &self,
        name: &str,
    ) -> Result<Option<Self::Attribute<'_>>, AccessByNameError> {
        match name {
            "FileMetaInformationGroupLength"
            | "FileMetaInformationVersion"
            | "MediaStorageSOPClassUID"
            | "MediaStorageSOPInstanceUID"
            | "TransferSyntaxUID"
            | "ImplementationClassUID"
            | "ImplementationVersionName"
            | "SourceApplicationEntityTitle"
            | "SendingApplicationEntityTitle"
            | "ReceivingApplicationEntityTitle"
            | "PrivateInformationCreatorUID"
            | "PrivateInformation" => {
                let attr = self.meta.attr_by_name_opt(name)?;
                Ok(attr.map(Either::Left))
            }
            _ => {
                let attr = self.obj.attr_by_name_opt(name)?;
                Ok(attr.map(Either::Right))
            }
        }
    }

    #[inline]
    fn attr(&self, tag: Tag) -> Result<Self::Attribute<'_>, AccessError> {
        match tag {
            Tag(0x0002, _) => {
                let attr = self.meta.attr(tag)?;
                Ok(Either::Left(attr))
            }
            _ => {
                let attr = self.obj.attr(tag)?;
                Ok(Either::Right(attr))
            }
        }
    }

    fn at(
        &self,
        selector: impl Into<AttributeSelector>,
    ) -> Result<Self::LeafAttribute<'_>, AtAccessError> {
        let selector: AttributeSelector = selector.into();
        match selector.first_step() {
            AttributeSelectorStep::Tag(tag @ Tag(0x0002, _)) => {
                let attr = self
                    .meta
                    .attr(*tag)
                    .map_err(|_| AtAccessError::MissingLeafElement { selector })?;
                Ok(Either::Left(attr))
            }
            _ => {
                let attr = self.obj.at(selector)?;
                Ok(Either::Right(attr))
            }
        }
    }
}

impl<'s, O: 's> DicomObject for &'s FileDicomObject<O>
where
    O: DicomObject,
{
    type Attribute<'a>
        = Either<FileMetaAttribute<'a>, O::Attribute<'a>>
    where
        Self: 'a,
        O: 'a;

    type LeafAttribute<'a>
        = Either<FileMetaAttribute<'a>, O::LeafAttribute<'a>>
    where
        Self: 'a,
        O: 'a;

    #[inline]
    fn attr_opt(&self, tag: Tag) -> Result<Option<Self::Attribute<'_>>, AccessError> {
        (**self).attr_opt(tag)
    }

    #[inline]
    fn attr_by_name_opt(
        &self,
        name: &str,
    ) -> Result<Option<Self::Attribute<'_>>, AccessByNameError> {
        (**self).attr_by_name_opt(name)
    }

    #[inline]
    fn attr(&self, tag: Tag) -> Result<Self::Attribute<'_>, AccessError> {
        (**self).attr(tag)
    }

    #[inline]
    fn attr_by_name(&self, name: &str) -> Result<Self::Attribute<'_>, AccessByNameError> {
        (**self).attr_by_name(name)
    }

    #[inline]
    fn at(
        &self,
        selector: impl Into<AttributeSelector>,
    ) -> Result<Self::LeafAttribute<'_>, AtAccessError> {
        (**self).at(selector)
    }
}

/// This implementation creates an iterator
/// to the elements of the underlying data set,
/// consuming the whole object.
/// The attributes in the file meta group are _not_ included.
///
/// To obtain an iterator over the meta elements,
/// use [`meta().to_element_iter()`](FileMetaTable::to_element_iter).
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()
    }
}

/// This implementation creates an iterator
/// to the elements of the underlying data set.
/// The attributes in the file meta group are _not_ included.
///
/// To obtain an iterator over the meta elements,
/// use [`meta().to_element_iter()`](FileMetaTable::to_element_iter).
impl<'a, O> IntoIterator for &'a FileDicomObject<O>
where
    &'a O: IntoIterator,
{
    type Item = <&'a O as IntoIterator>::Item;
    type IntoIter = <&'a O as IntoIterator>::IntoIter;

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

/// Implement basic pixeldata encoder/decoder functionality
impl<D> PixelDataObject for FileDicomObject<InMemDicomObject<D>>
where
    D: DataDictionary + Clone,
{
    fn transfer_syntax_uid(&self) -> &str {
        self.meta.transfer_syntax()
    }

    /// Return the Rows attribute or None if it is not found
    fn rows(&self) -> Option<u16> {
        (**self)
            .get(dicom_dictionary_std::tags::ROWS)?
            .uint16()
            .ok()
    }

    /// Return the Columns attribute or None if it is not found
    fn cols(&self) -> Option<u16> {
        (**self)
            .get(dicom_dictionary_std::tags::COLUMNS)?
            .uint16()
            .ok()
    }

    /// Return the SamplesPerPixel attribute or None if it is not found
    fn samples_per_pixel(&self) -> Option<u16> {
        (**self)
            .get(dicom_dictionary_std::tags::SAMPLES_PER_PIXEL)?
            .uint16()
            .ok()
    }

    /// Return the BitsAllocated attribute or None if it is not set
    fn bits_allocated(&self) -> Option<u16> {
        (**self)
            .get(dicom_dictionary_std::tags::BITS_ALLOCATED)?
            .uint16()
            .ok()
    }

    /// Return the BitsStored attribute or None if it is not set
    fn bits_stored(&self) -> Option<u16> {
        (**self)
            .get(dicom_dictionary_std::tags::BITS_STORED)?
            .uint16()
            .ok()
    }

    fn photometric_interpretation(&self) -> Option<&str> {
        (**self)
            .get(dicom_dictionary_std::tags::PHOTOMETRIC_INTERPRETATION)?
            .string()
            .ok()
            .map(|s| s.trim_end())
    }

    /// Return the NumberOfFrames attribute or None if it is not set
    fn number_of_frames(&self) -> Option<u32> {
        (**self)
            .get(dicom_dictionary_std::tags::NUMBER_OF_FRAMES)?
            .to_int()
            .ok()
    }

    /// Returns the number of fragments or None for native pixel data
    fn number_of_fragments(&self) -> Option<u32> {
        let pixel_data = (**self).get(dicom_dictionary_std::tags::PIXEL_DATA)?;
        match pixel_data.value() {
            DicomValue::Primitive(_p) => Some(1),
            DicomValue::PixelSequence(v) => Some(v.fragments().len() as u32),
            DicomValue::Sequence(..) => None,
        }
    }

    /// Return a specific encoded pixel fragment by index as a `Vec<u8>`
    /// or `None` if no pixel data is found.
    ///
    /// Non-encapsulated pixel data can be retrieved by requesting fragment #0.
    ///
    /// Panics if `fragment` is out of bounds for the encapsulated pixel data fragments.
    fn fragment(&self, fragment: usize) -> Option<Cow<'_, [u8]>> {
        let pixel_data = (**self).get(dicom_dictionary_std::tags::PIXEL_DATA)?;
        match pixel_data.value() {
            DicomValue::PixelSequence(v) => Some(Cow::Borrowed(v.fragments()[fragment].as_ref())),
            DicomValue::Primitive(p) if fragment == 0 => Some(p.to_bytes()),
            _ => None,
        }
    }

    fn offset_table(&self) -> Option<Cow<'_, [u32]>> {
        let pixel_data = (**self).get(dicom_dictionary_std::tags::PIXEL_DATA)?;
        match pixel_data.value() {
            DicomValue::Primitive(_) => None,
            DicomValue::Sequence(_) => None,
            DicomValue::PixelSequence(seq) => Some(Cow::from(seq.offset_table())),
        }
    }

    /// Should return either a byte slice/vector if native pixel data
    /// or byte fragments if encapsulated.
    /// Returns None if no pixel data is found
    fn raw_pixel_data(&self) -> Option<RawPixelData> {
        let pixel_data = (**self).get(dicom_dictionary_std::tags::PIXEL_DATA)?;
        match pixel_data.value() {
            DicomValue::Primitive(p) => {
                // Create 1 fragment with all bytes
                let fragment = p.to_bytes().to_vec();
                let mut fragments = SmallVec::new();
                fragments.push(fragment);
                Some(RawPixelData {
                    fragments,
                    offset_table: SmallVec::new(),
                })
            }
            DicomValue::PixelSequence(v) => {
                let (offset_table, fragments) = v.clone().into_parts();
                Some(RawPixelData {
                    fragments,
                    offset_table,
                })
            }
            DicomValue::Sequence(..) => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use dicom_core::{DataElement, PrimitiveValue, VR};
    use dicom_dictionary_std::{tags, uids};

    use crate::meta::FileMetaTableBuilder;
    use crate::{AccessError, DicomAttribute as _, DicomObject, FileDicomObject, InMemDicomObject};

    fn assert_type_not_too_large<T>(max_size: usize) {
        let size = std::mem::size_of::<T>();
        if size > max_size {
            panic!(
                "Type {} of byte size {} exceeds acceptable size {}",
                std::any::type_name::<T>(),
                size,
                max_size
            );
        }
    }

    #[test]
    fn errors_not_too_large() {
        assert_type_not_too_large::<AccessError>(64);
    }

    #[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);
    }

    /// A FileDicomObject<InMemDicomObject>
    /// can be used like a DICOM object.
    #[test]
    fn file_dicom_object_can_use_inner() {
        let mut obj = InMemDicomObject::new_empty();

        obj.put(DataElement::new(
            dicom_dictionary_std::tags::PATIENT_NAME,
            VR::PN,
            PrimitiveValue::from("John Doe"),
        ));

        let mut obj = obj
            .with_meta(
                FileMetaTableBuilder::new()
                    .media_storage_sop_class_uid("1.2.840.10008.5.1.4.1.1.7")
                    .media_storage_sop_instance_uid("1.2.23456789")
                    .transfer_syntax("1.2.840.10008.1.2.1"),
            )
            .unwrap();

        // contains patient name
        assert_eq!(
            obj.element(tags::PATIENT_NAME)
                .unwrap()
                .value()
                .to_str()
                .unwrap(),
            "John Doe",
        );

        // same result using DicomObject
        assert_eq!(
            DicomObject::attr(&obj, tags::PATIENT_NAME)
                .unwrap()
                .to_str()
                .unwrap(),
            "John Doe",
        );

        // can be removed with take
        obj.take_element(tags::PATIENT_NAME).unwrap();

        assert!(matches!(
            obj.element(tags::PATIENT_NAME),
            Err(AccessError::NoSuchDataElementTag { .. }),
        ));
    }

    #[test]
    fn file_dicom_object_can_iterate_over_elements() {
        let mut obj = InMemDicomObject::new_empty();

        obj.put(DataElement::new(
            dicom_dictionary_std::tags::PATIENT_NAME,
            VR::PN,
            PrimitiveValue::from("John Doe"),
        ));
        obj.put(DataElement::new(
            dicom_dictionary_std::tags::SOP_INSTANCE_UID,
            VR::PN,
            PrimitiveValue::from("1.2.987654321"),
        ));

        let obj = obj
            .with_meta(
                FileMetaTableBuilder::new()
                    .media_storage_sop_class_uid("1.2.840.10008.5.1.4.1.1.7")
                    .media_storage_sop_instance_uid("1.2.987654321")
                    .transfer_syntax("1.2.840.10008.1.2.1"),
            )
            .unwrap();

        // iter
        let mut iter = (&obj).into_iter();
        assert_eq!(
            iter.next().unwrap().header().tag,
            dicom_dictionary_std::tags::SOP_INSTANCE_UID
        );
        assert_eq!(
            iter.next().unwrap().header().tag,
            dicom_dictionary_std::tags::PATIENT_NAME
        );
        assert_eq!(iter.next(), None);

        // into_iter
        let mut iter = obj.into_iter();
        assert_eq!(
            iter.next().unwrap().header().tag,
            dicom_dictionary_std::tags::SOP_INSTANCE_UID
        );
        assert_eq!(
            iter.next().unwrap().header().tag,
            dicom_dictionary_std::tags::PATIENT_NAME
        );
        assert_eq!(iter.next(), None);
    }

    /// Can access file meta properties via the DicomObject trait
    #[test]
    pub fn file_dicom_can_update_meta() {
        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("2.25.280986007517028771599125034987786349815")
            .implementation_class_uid("1.2.345.6.7890.1.234")
            .build()
            .unwrap();
        let mut obj = FileDicomObject::new_empty_with_meta(meta);

        obj.update_meta(|meta| {
            meta.receiving_application_entity_title = Some("SOMETHING".to_string());
        });

        assert_eq!(
            obj.meta().receiving_application_entity_title.as_deref(),
            Some("SOMETHING"),
        );
    }

    #[test]
    fn dicom_object_api_on_file_dicom_object() {
        use crate::{DicomAttribute as _, DicomObject as _};

        let meta = FileMetaTableBuilder::new()
            .transfer_syntax(uids::RLE_LOSSLESS)
            .media_storage_sop_class_uid(uids::ENHANCED_MR_IMAGE_STORAGE)
            .media_storage_sop_instance_uid("2.25.94766187067244888884745908966163363746")
            .build()
            .unwrap();
        let obj = FileDicomObject::new_empty_with_meta(meta);

        assert_eq!(
            obj.attr(tags::TRANSFER_SYNTAX_UID)
                .unwrap()
                .to_str()
                .unwrap(),
            uids::RLE_LOSSLESS
        );

        let sop_class_uid = obj.attr_opt(tags::MEDIA_STORAGE_SOP_CLASS_UID).unwrap();
        let sop_class_uid = sop_class_uid.as_ref().map(|v| v.to_str().unwrap());
        assert_eq!(
            sop_class_uid.as_deref(),
            Some(uids::ENHANCED_MR_IMAGE_STORAGE)
        );

        assert_eq!(
            obj.attr_by_name("MediaStorageSOPInstanceUID")
                .unwrap()
                .to_str()
                .unwrap(),
            "2.25.94766187067244888884745908966163363746"
        );

        assert_eq!(
            obj.at(tags::MEDIA_STORAGE_SOP_INSTANCE_UID)
                .unwrap()
                .to_str()
                .unwrap(),
            "2.25.94766187067244888884745908966163363746"
        );
    }

    #[test]
    fn operations_api_on_primitive_values() {
        use crate::DicomAttribute;
        use dicom_dictionary_std::tags;

        let obj = InMemDicomObject::from_element_iter([
            DataElement::new(tags::PATIENT_NAME, VR::PN, PrimitiveValue::from("Doe^John")),
            DataElement::new(tags::INSTANCE_NUMBER, VR::IS, PrimitiveValue::from("5")),
        ]);

        let patient_name = obj.get(tags::PATIENT_NAME).unwrap().value();

        // can get string using DICOM attribute API

        assert_eq!(&DicomAttribute::to_str(patient_name).unwrap(), "Doe^John");

        // can get integer from Instance Number

        let instance_number = obj.get(tags::INSTANCE_NUMBER).unwrap().value();
        assert_eq!(DicomAttribute::to_u32(instance_number).unwrap(), 5);

        // cannot get items

        assert_eq!(patient_name.num_items(), None);
        assert_eq!(patient_name.num_fragments(), None);
        assert!(matches!(
            patient_name.item(0),
            Err(crate::AttributeError::NotDataSet)
        ));

        assert_eq!(instance_number.num_items(), None);
        assert_eq!(instance_number.num_fragments(), None);
        assert!(matches!(
            patient_name.item(0),
            Err(crate::AttributeError::NotDataSet)
        ));
        assert!(matches!(
            instance_number.item(0),
            Err(crate::AttributeError::NotDataSet)
        ));
    }
}