dcmnorm-object 0.20.1

In-house DICOM in-memory object model and Part 10 file I/O, replacing dicom-object. See README.md.
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
//! The in-memory DICOM object tree ([`InMemDicomObject`]) and its element type.
//!
//! Elements are stored as a `Vec<InMemElement>` kept sorted by tag, not a `BTreeMap`/`HashMap` -
//! see the crate README for why. `.get`/`.element` use binary search; `.put` uses a binary
//! search to find the insertion point, so lookups stay O(log n) even though insertion is O(n)
//! (objects are built once via a single ordered parse pass, then queried many times - the right
//! tradeoff for this access pattern).

use std::io::{Read, Write};

use dcmnorm_core::header::{DataElement, HasLength, Header, Tag};
use dcmnorm_core::value::{DataSetSequence, PixelFragmentSequence, Value, C};
use dcmnorm_core::{ops::AttributeOp, PrimitiveValue, VR};
use dcmnorm_encoding::transfer_syntax::{Codec, TransferSyntax};
use dcmnorm_parser::dataset::read::DataSetReaderOptions;
use dcmnorm_parser::dataset::{DataSetReader, DataSetWriter, DataToken};

use crate::error::{ReadError, WriteError};

/// The pixel data fragment type used by [`InMemDicomObject`] - a plain owned byte buffer.
pub type InMemFragment = Vec<u8>;

/// A data element within an [`InMemDicomObject`] tree (a primitive value, a nested sequence of
/// further `InMemDicomObject`s, or an encapsulated pixel data fragment sequence).
pub type InMemElement = DataElement<InMemDicomObject, InMemFragment>;

/// An in-memory DICOM data set: a flat, tag-ordered list of elements, each of which may itself
/// contain a nested list (for `SQ` values).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InMemDicomObject {
    elements: Vec<InMemElement>,
}

impl HasLength for InMemDicomObject {
    fn length(&self) -> dcmnorm_core::header::Length {
        dcmnorm_core::header::Length::UNDEFINED
    }
}

impl InMemDicomObject {
    /// An empty object with no elements.
    pub fn new_empty() -> Self {
        InMemDicomObject {
            elements: Vec::new(),
        }
    }

    /// Build an object directly from a list of elements, sorting them into tag order.
    /// Matches `dicom_object::InMemDicomObject::from_element_iter`.
    pub fn from_element_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = InMemElement>,
    {
        let mut elements: Vec<InMemElement> = iter.into_iter().collect();
        elements.sort_by_key(|e| e.tag());
        InMemDicomObject { elements }
    }

    /// Build a DIMSE command data set from a list of elements. DIMSE command sets have the
    /// same shape as a regular data set (a flat list of primitive elements, always Implicit VR
    /// Little Endian on the wire per PS3.7) - this is an alias for [`Self::from_element_iter`]
    /// kept for call-site clarity in `dimse.rs`/`scp.rs`.
    pub fn command_from_element_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = InMemElement>,
    {
        Self::from_element_iter(iter)
    }

    fn binary_search(&self, tag: Tag) -> Result<usize, usize> {
        self.elements.binary_search_by_key(&tag, |e| e.tag())
    }

    /// Look up an element by tag. Returns `None` if absent.
    pub fn get(&self, tag: Tag) -> Option<&InMemElement> {
        self.binary_search(tag).ok().map(|i| &self.elements[i])
    }

    /// Look up a mutable element by tag. Returns `None` if absent.
    pub fn get_mut(&mut self, tag: Tag) -> Option<&mut InMemElement> {
        self.binary_search(tag).ok().map(|i| &mut self.elements[i])
    }

    /// Look up an element by tag, returning a `Result` (an `Err` with a descriptive message on
    /// absence) rather than `Option` - for call sites that want to `?`-propagate a hard failure
    /// on a required element.
    pub fn element(&self, tag: Tag) -> Result<&InMemElement, MissingElementError> {
        self.get(tag).ok_or(MissingElementError { tag })
    }

    /// Insert or replace a text element by tag and VR, creating it if absent. A thin
    /// convenience wrapper around [`Self::put`] for CLI-style attribute edits
    /// (`--set KEY=VALUE`) and DIMSE command/identifier construction that only ever deal in
    /// string values.
    pub fn put_str(&mut self, tag: Tag, vr: VR, value: impl Into<String>) {
        self.put(DataElement::new(
            tag,
            vr,
            PrimitiveValue::from(value.into()),
        ));
    }

    /// Insert or replace an element, keeping the element list in tag order.
    pub fn put(&mut self, element: InMemElement) {
        match self.binary_search(element.tag()) {
            Ok(i) => self.elements[i] = element,
            Err(i) => self.elements.insert(i, element),
        }
    }

    /// Remove an element by tag. Returns whether an element was actually present.
    pub fn remove_element(&mut self, tag: Tag) -> bool {
        match self.binary_search(tag) {
            Ok(i) => {
                self.elements.remove(i);
                true
            }
            Err(_) => false,
        }
    }

    /// Iterate over all elements, in tag order.
    pub fn iter(&self) -> impl Iterator<Item = &InMemElement> {
        self.elements.iter()
    }

    /// The number of top-level elements in this object.
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Apply an attribute mutation, as returned by a pixel data encoder after transcoding (e.g.
    /// a Photometric Interpretation or Planar Configuration adjustment required by the new
    /// transfer syntax).
    ///
    /// # Errors
    ///
    /// Returns [`ApplyOpError::UnsupportedSelector`] if `op`'s selector is not a single
    /// top-level tag. dcmnorm only ever applies single-step, top-level selectors today
    /// (confirmed by its own usage in `io.rs` - pixel data codec post-transcode attribute
    /// patches never target nested sequences), so a full attribute-selector-path walk isn't
    /// implemented here - but a caller that *does* build one of those selectors should get a
    /// clear error, not have the operation silently do nothing.
    pub fn apply(&mut self, op: AttributeOp) -> Result<(), ApplyOpError> {
        use dcmnorm_core::ops::{AttributeAction, AttributeSelectorStep};

        let AttributeSelectorStep::Tag(tag) = *op.selector.first_step() else {
            return Err(ApplyOpError::UnsupportedSelector);
        };
        let current_vr = || self.get(tag).map(|e| e.vr()).unwrap_or(VR::UN);

        match op.action {
            AttributeAction::Remove => {
                self.remove_element(tag);
            }
            AttributeAction::Empty => {
                self.put(DataElement::new(tag, current_vr(), PrimitiveValue::Empty));
            }
            AttributeAction::SetVr(vr) => {
                if let Some(element) = self.get(tag) {
                    let value = element.value().clone();
                    self.put(DataElement::new(tag, vr, value));
                }
            }
            AttributeAction::Set(value) => {
                self.put(DataElement::new(tag, vr_for_action_value(&value), value));
            }
            AttributeAction::SetIfMissing(value) if self.get(tag).is_none() => {
                self.put(DataElement::new(tag, vr_for_action_value(&value), value));
            }
            AttributeAction::SetStr(s) => {
                self.put(DataElement::new(
                    tag,
                    current_vr(),
                    PrimitiveValue::from(s.into_owned()),
                ));
            }
            AttributeAction::SetStrIfMissing(s) if self.get(tag).is_none() => {
                self.put(DataElement::new(
                    tag,
                    VR::CS,
                    PrimitiveValue::from(s.into_owned()),
                ));
            }
            AttributeAction::Replace(value) if self.get(tag).is_some() => {
                self.put(DataElement::new(tag, vr_for_action_value(&value), value));
            }
            AttributeAction::ReplaceStr(s) if self.get(tag).is_some() => {
                self.put(DataElement::new(
                    tag,
                    current_vr(),
                    PrimitiveValue::from(s.into_owned()),
                ));
            }
            _ => {}
        }
        Ok(())
    }

    /// Attach a [`FileMetaTable`] built from a [`crate::FileMetaTableBuilder`], producing a
    /// [`crate::FileDicomObject`].
    pub fn with_meta(
        self,
        builder: crate::FileMetaTableBuilder,
    ) -> Result<crate::FileDicomObject<Self>, crate::error::WithMetaError> {
        let meta = builder.build()?;
        Ok(crate::FileDicomObject { meta, object: self })
    }

    /// Read a bare data set (no Part 10 preamble/meta group) from `source`, using the given
    /// transfer syntax.
    ///
    /// A dataset-level transfer syntax (currently just Deflated Explicit VR Little Endian) needs
    /// its own byte-stream transform applied *before* element decoding even starts - unlike a
    /// pixel-data codec, which only ever touches one element's value. `source` is always boxed
    /// (not just when a codec applies) so this function has one concrete reader type to build a
    /// `DataSetReader` over regardless of transfer syntax.
    pub fn read_dataset_with_ts<'r, R: Read + 'r>(
        source: R,
        ts: &TransferSyntax,
    ) -> Result<Self, ReadError> {
        Self::read_dataset_with_ts_options(source, ts, DataSetReaderOptions::default())
    }

    /// [`Self::read_dataset_with_ts`] with explicit reader options, e.g.
    /// [`DataSetReaderOptions::flexible_decoding`].
    pub fn read_dataset_with_ts_options<'r, R: Read + 'r>(
        source: R,
        ts: &TransferSyntax,
        options: DataSetReaderOptions,
    ) -> Result<Self, ReadError> {
        Self::read_dataset_with_ts_cs_options(
            source,
            ts,
            dcmnorm_encoding::text::SpecificCharacterSet::default(),
            options,
        )
    }

    /// Like [`Self::read_dataset_with_ts`], seeded with an initial [`SpecificCharacterSet`]
    /// (e.g. when resuming a stream to read trailing elements after `PixelData`).
    pub fn read_dataset_with_ts_cs<'r, R: Read + 'r>(
        source: R,
        ts: &TransferSyntax,
        cs: dcmnorm_encoding::text::SpecificCharacterSet,
    ) -> Result<Self, ReadError> {
        Self::read_dataset_with_ts_cs_options(source, ts, cs, DataSetReaderOptions::default())
    }

    fn read_dataset_with_ts_cs_options<'r, R: Read + 'r>(
        source: R,
        ts: &TransferSyntax,
        cs: dcmnorm_encoding::text::SpecificCharacterSet,
        options: DataSetReaderOptions,
    ) -> Result<Self, ReadError> {
        let source: Box<dyn Read + 'r> = match ts.codec() {
            Codec::Dataset(Some(adapter)) => adapter.adapt_reader(Box::new(source)),
            _ => Box::new(source),
        };
        let mut reader = DataSetReader::new_with_ts_cs_options(source, ts, cs, options)
            .map_err(|source| ReadError::Dataset { source })?;
        build_dataset(&mut reader, false)
    }

    /// Returns the [`SpecificCharacterSet`] declared by `(0008,0005)` in this object, or the
    /// default character set if absent or unrecognized.
    pub fn specific_character_set(&self) -> dcmnorm_encoding::text::SpecificCharacterSet {
        const SPECIFIC_CHARACTER_SET: Tag = Tag(0x0008, 0x0005);
        match self.get(SPECIFIC_CHARACTER_SET).map(|e| e.value()) {
            Some(Value::Primitive(PrimitiveValue::Strs(parts))) => {
                dcmnorm_encoding::text::SpecificCharacterSet::from_codes(parts).unwrap_or_default()
            }
            Some(Value::Primitive(PrimitiveValue::Str(s))) => {
                dcmnorm_encoding::text::SpecificCharacterSet::from_codes(&[s.as_str()])
                    .unwrap_or_default()
            }
            _ => dcmnorm_encoding::text::SpecificCharacterSet::default(),
        }
    }

    #[doc(hidden)]
    pub fn into_elements(self) -> Vec<InMemElement> {
        self.elements
    }

    /// Write this object as a bare data set (no Part 10 preamble/meta group) using the given
    /// transfer syntax. See [`Self::read_dataset_with_ts`] for why `to` is always boxed.
    pub fn write_dataset_with_ts<'w, W: Write + 'w>(
        &self,
        to: W,
        ts: &TransferSyntax,
    ) -> Result<(), WriteError> {
        let to: Box<dyn Write + 'w> = match ts.codec() {
            Codec::Dataset(Some(adapter)) => adapter.adapt_writer(Box::new(to)),
            _ => Box::new(to),
        };
        let mut writer =
            DataSetWriter::with_ts(to, ts).map_err(|source| WriteError::Dataset { source })?;
        for element in &self.elements {
            write_element_tokens(&mut writer, element)?;
        }
        Ok(())
    }

    /// Write this object as a bare data set, splitting top-level elements around `(7FE0,0010)`
    /// and invoking `write_pixel_data` at the exact tag-order position of `PixelData` (skipping
    /// any `PixelData` stored in `self`).
    pub fn write_dataset_with_ts_and_pixel_data<'w, W, E, F>(
        &self,
        to: W,
        ts: &TransferSyntax,
        write_pixel_data: F,
    ) -> Result<(), E>
    where
        W: Write + 'w,
        E: From<WriteError>,
        F: FnOnce(
            &mut DataSetWriter<
                Box<dyn Write + 'w>,
                dcmnorm_encoding::transfer_syntax::DynEncoder<'w, Box<dyn Write + 'w>>,
            >,
        ) -> Result<(), E>,
    {
        const PIXEL_DATA: Tag = Tag(0x7FE0, 0x0010);
        let to: Box<dyn Write + 'w> = match ts.codec() {
            Codec::Dataset(Some(adapter)) => adapter.adapt_writer(Box::new(to)),
            _ => Box::new(to),
        };
        let mut writer =
            DataSetWriter::with_ts(to, ts).map_err(|source| WriteError::Dataset { source })?;
        let mut write_pixel_data = Some(write_pixel_data);
        for element in &self.elements {
            let tag = element.tag();
            if tag == PIXEL_DATA {
                continue;
            }
            if tag > PIXEL_DATA {
                if let Some(write_pixels) = write_pixel_data.take() {
                    write_pixels(&mut writer)?;
                }
            }
            write_element_tokens(&mut writer, element)?;
        }
        if let Some(write_pixels) = write_pixel_data.take() {
            write_pixels(&mut writer)?;
        }
        writer
            .flush()
            .map_err(|source| WriteError::Dataset { source })?;
        Ok(())
    }

    /// Write all elements in this object into an already-constructed `DataSetWriter` (e.g.
    /// trailing elements after streaming `PixelData` in a single-pass wire receiver).
    pub fn write_elements_to_writer<'w, W: Write>(
        &self,
        writer: &mut DataSetWriter<W, dcmnorm_encoding::transfer_syntax::DynEncoder<'w, W>>,
    ) -> Result<(), WriteError> {
        for element in &self.elements {
            write_element_tokens(writer, element)?;
        }
        Ok(())
    }

    /// Read a bare data set from a forward-only stream up to (not including) top-level
    /// `(7FE0,0010) PixelData`'s value, returning all elements read so far and where the stream
    /// stopped. Because `DataSetReader` performs no read-ahead past the element header in hand,
    /// `source` is left positioned at byte 0 of `PixelData`'s value (or at the Basic Offset Table
    /// item header for encapsulated pixel data).
    ///
    /// Does not apply dataset-level codecs (deflate) — callers must check `ts.codec()` first.
    pub fn read_dataset_until_pixel_data<R: Read>(
        source: R,
        ts: &TransferSyntax,
    ) -> Result<(Self, PixelDataStreamStop), ReadError> {
        const PIXEL_DATA: Tag = Tag(0x7FE0, 0x0010);
        let mut reader = DataSetReader::new_with_ts(source, ts)
            .map_err(|source| ReadError::Dataset { source })?;
        let mut elements = Vec::new();
        let mut stop = PixelDataStreamStop::Absent;

        while let Some(token) = reader.next() {
            match token? {
                DataToken::ElementHeader(header) if header.tag == PIXEL_DATA => {
                    let Some(length) = header.len.get() else {
                        return Err(ReadError::UnexpectedToken {
                            context: "undefined-length non-encapsulated PixelData",
                        });
                    };
                    stop = PixelDataStreamStop::Native {
                        vr: header.vr,
                        length,
                    };
                    break;
                }
                DataToken::ElementHeader(header) => {
                    let value = expect_primitive_value(&mut reader)?;
                    elements.push(DataElement::new(header.tag, header.vr, value));
                }
                DataToken::SequenceStart { tag, len } => {
                    let mut items: C<InMemDicomObject> = C::new();
                    loop {
                        match next_required(&mut reader)? {
                            DataToken::ItemStart { .. } => {
                                items.push(build_dataset(&mut reader, true)?);
                            }
                            DataToken::SequenceEnd => break,
                            _ => {
                                return Err(ReadError::UnexpectedToken {
                                    context: "expected ItemStart or SequenceEnd in sequence",
                                })
                            }
                        }
                    }
                    elements.push(DataElement::new(
                        tag,
                        VR::SQ,
                        Value::Sequence(DataSetSequence::new(items, len)),
                    ));
                }
                DataToken::PixelSequenceStart => {
                    stop = PixelDataStreamStop::Encapsulated;
                    break;
                }
                _ => {
                    return Err(ReadError::UnexpectedToken {
                        context: "unexpected token at data set top level",
                    })
                }
            }
        }

        elements.sort_by_key(|e| e.tag());
        Ok((InMemDicomObject { elements }, stop))
    }
}

fn vr_for_action_value(value: &PrimitiveValue) -> VR {
    // Best-effort: attribute-op Set values built by dcmnorm's own pixel data codecs are always
    // numeric (Photometric Interpretation aside, which goes through SetStr) - default to the
    // VR that matches the value's own shape.
    use dcmnorm_core::value::PrimitiveValue as PV;
    match value {
        PV::U16(_) => VR::US,
        PV::I16(_) => VR::SS,
        PV::U32(_) => VR::UL,
        PV::I32(_) => VR::SL,
        PV::Strs(_) | PV::Str(_) => VR::CS,
        _ => VR::UN,
    }
}

/// A required element was not present in the object.
#[derive(Debug, Clone, Copy)]
pub struct MissingElementError {
    pub tag: Tag,
}

impl std::fmt::Display for MissingElementError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "element {:?} not found", self.tag)
    }
}

impl std::error::Error for MissingElementError {}

/// An [`AttributeOp`] could not be applied.
#[derive(Debug, Clone, Copy)]
pub enum ApplyOpError {
    /// A required element was not present in the object.
    MissingElement(MissingElementError),
    /// The operation's selector was not a single top-level tag - see
    /// [`InMemDicomObject::apply`]'s doc comment.
    UnsupportedSelector,
}

impl From<MissingElementError> for ApplyOpError {
    fn from(source: MissingElementError) -> Self {
        ApplyOpError::MissingElement(source)
    }
}

impl std::fmt::Display for ApplyOpError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ApplyOpError::MissingElement(source) => write!(f, "{source}"),
            ApplyOpError::UnsupportedSelector => {
                write!(
                    f,
                    "attribute operation selector is not a single top-level tag"
                )
            }
        }
    }
}

impl std::error::Error for ApplyOpError {}

/// Fold a `DataToken` stream into a tree of elements. `in_item` controls the stop condition:
/// `false` runs until the token stream is exhausted (top-level data set); `true` runs until a
/// matching `ItemEnd` token (a sequence item's nested data set), consuming that `ItemEnd`.
fn build_dataset(
    tokens: &mut impl Iterator<Item = Result<DataToken, dcmnorm_parser::dataset::read::Error>>,
    in_item: bool,
) -> Result<InMemDicomObject, ReadError> {
    let mut elements = Vec::new();

    loop {
        let Some(token) = tokens.next() else {
            if in_item {
                return Err(ReadError::UnexpectedToken {
                    context: "expected ItemEnd, got end of stream",
                });
            }
            break;
        };
        let token = token?;

        match token {
            DataToken::ItemEnd if in_item => break,

            DataToken::ElementHeader(header) => {
                let value = expect_primitive_value(tokens)?;
                elements.push(DataElement::new(header.tag, header.vr, value));
            }

            DataToken::SequenceStart { tag, len } => {
                let mut items: C<InMemDicomObject> = C::new();
                loop {
                    match next_required(tokens)? {
                        DataToken::ItemStart { .. } => {
                            items.push(build_dataset(tokens, true)?);
                        }
                        DataToken::SequenceEnd => break,
                        _ => {
                            return Err(ReadError::UnexpectedToken {
                                context: "expected ItemStart or SequenceEnd in sequence",
                            })
                        }
                    }
                }
                let value = Value::Sequence(DataSetSequence::new(items, len));
                elements.push(DataElement::new(tag, VR::SQ, value));
            }

            DataToken::PixelSequenceStart => {
                let value = read_pixel_sequence(tokens)?;
                elements.push(DataElement::new(Tag(0x7FE0, 0x0010), VR::OB, value));
            }

            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "unexpected token at data set top level",
                })
            }
        }
    }

    elements.sort_by_key(|e| e.tag());
    Ok(InMemDicomObject { elements })
}

/// Like [`InMemDicomObject::read_dataset_with_ts`], but stops consuming the token stream as
/// soon as a top-level element's tag exceeds `stop_tag` - a fast path for partial/filtered
/// reads (`dcmnorm`'s `--filter` CLI flag) that don't need the rest of the data set. Doesn't
/// attempt early-stop *inside* nested sequences (real `--filter` usage targets top-level
/// tags), so a stop tag inside a sequence just falls back to reading that whole sequence.
///
/// Applies the same dataset-level codec as `read_dataset_with_ts`. Without it, a Deflated
/// Explicit VR Little Endian file's still-compressed bytes got decoded as element headers: the
/// first bogus "tag" was usually past `stop_tag`, so the read stopped "successfully" with an
/// empty data set - edge insert's `readTags` then saw no SOPInstanceUID ("Missing attribute:
/// T00080018") on every deflated DOC/SR a RamSoft PACS sent, and those studies never archived.
pub(crate) fn read_dataset_until<'r>(
    source: impl Read + 'r,
    ts: &TransferSyntax,
    stop_tag: Tag,
    options: DataSetReaderOptions,
) -> Result<InMemDicomObject, ReadError> {
    let source: Box<dyn Read + 'r> = match ts.codec() {
        Codec::Dataset(Some(adapter)) => adapter.adapt_reader(Box::new(source)),
        _ => Box::new(source),
    };
    let mut reader = DataSetReader::new_with_ts_options(source, ts, options)
        .map_err(|source| ReadError::Dataset { source })?;
    let mut elements = Vec::new();

    loop {
        let Some(token) = reader.next() else { break };
        let token = token?;
        match token {
            DataToken::ElementHeader(header) => {
                let tag = header.tag;
                if tag > stop_tag {
                    break;
                }
                let value = expect_primitive_value(&mut reader)?;
                elements.push(DataElement::new(tag, header.vr, value));
                if tag >= stop_tag {
                    break;
                }
            }
            DataToken::SequenceStart { tag, len } => {
                if tag > stop_tag {
                    break;
                }
                let mut items: C<InMemDicomObject> = C::new();
                loop {
                    match next_required(&mut reader)? {
                        DataToken::ItemStart { .. } => {
                            items.push(build_dataset(&mut reader, true)?)
                        }
                        DataToken::SequenceEnd => break,
                        _ => {
                            return Err(ReadError::UnexpectedToken {
                                context: "expected ItemStart or SequenceEnd in sequence",
                            })
                        }
                    }
                }
                elements.push(DataElement::new(
                    tag,
                    VR::SQ,
                    Value::Sequence(DataSetSequence::new(items, len)),
                ));
                if tag >= stop_tag {
                    break;
                }
            }
            DataToken::PixelSequenceStart => {
                if Tag(0x7FE0, 0x0010) > stop_tag {
                    break;
                }
                let value = read_pixel_sequence(&mut reader)?;
                elements.push(DataElement::new(Tag(0x7FE0, 0x0010), VR::OB, value));
                break;
            }
            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "unexpected token at data set top level",
                })
            }
        }
    }

    elements.sort_by_key(|e| e.tag());
    Ok(InMemDicomObject { elements })
}

/// Like [`read_dataset_until`], but stops right after reading a top-level native PixelData
/// element's *header*, leaving its value unread on `source` - see
/// `OpenFileOptions::open_file_until_pixel_data`. Returns `None` for the header when the data
/// set has no top-level native PixelData (absent, encapsulated, or an element past it was
/// reached first); the returned object is then incomplete and only useful as a signal to fall
/// back to a full read. The caller is responsible for not using this with a dataset-level codec
/// (deflate), whose byte positions don't correspond to the file's.
pub(crate) fn read_dataset_until_pixel_data_header<'r>(
    source: impl Read + 'r,
    ts: &TransferSyntax,
) -> Result<
    (
        InMemDicomObject,
        Option<dcmnorm_core::header::DataElementHeader>,
    ),
    ReadError,
> {
    const PIXEL_DATA: Tag = Tag(0x7FE0, 0x0010);
    let mut reader =
        DataSetReader::new_with_ts(source, ts).map_err(|source| ReadError::Dataset { source })?;
    let mut elements = Vec::new();
    let mut pixel_data_header = None;

    while let Some(token) = reader.next() {
        match token? {
            DataToken::ElementHeader(header) if header.tag == PIXEL_DATA => {
                pixel_data_header = Some(header);
                break;
            }
            DataToken::ElementHeader(header) if header.tag > PIXEL_DATA => break,
            DataToken::ElementHeader(header) => {
                let value = expect_primitive_value(&mut reader)?;
                elements.push(DataElement::new(header.tag, header.vr, value));
            }
            DataToken::SequenceStart { tag, len } => {
                let mut items: C<InMemDicomObject> = C::new();
                loop {
                    match next_required(&mut reader)? {
                        DataToken::ItemStart { .. } => {
                            items.push(build_dataset(&mut reader, true)?)
                        }
                        DataToken::SequenceEnd => break,
                        _ => {
                            return Err(ReadError::UnexpectedToken {
                                context: "expected ItemStart or SequenceEnd in sequence",
                            })
                        }
                    }
                }
                elements.push(DataElement::new(
                    tag,
                    VR::SQ,
                    Value::Sequence(DataSetSequence::new(items, len)),
                ));
                if tag > PIXEL_DATA {
                    break;
                }
            }
            DataToken::PixelSequenceStart => break,
            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "unexpected token at data set top level",
                })
            }
        }
    }

    elements.sort_by_key(|e| e.tag());
    Ok((InMemDicomObject { elements }, pixel_data_header))
}

/// Where a value that was skipped instead of read lives in the source file (absolute byte
/// offset of its first byte, and its length) - see [`DeferredValues`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeferredValueLocation {
    pub offset: u64,
    /// [`Self::UNDEFINED_LENGTH`] for a value whose end isn't known: encapsulated pixel data a
    /// read stopped at (`stop_at_pixel_data`) without walking its fragments.
    pub length: u64,
}

impl DeferredValueLocation {
    pub const UNDEFINED_LENGTH: u64 = u64::MAX;

    /// The value's length, or `None` for [`Self::UNDEFINED_LENGTH`].
    pub fn defined_length(&self) -> Option<u64> {
        (self.length != Self::UNDEFINED_LENGTH).then_some(self.length)
    }
}

/// The values a deferring read (`OpenFileOptions::open_file_deferring`) skipped rather than
/// loaded, mirroring the data set's shape: one entry per top-level tag that was either deferred
/// itself or is a sequence with deferred values somewhere inside its items.
///
/// A deferred element is still present in the object, with an empty placeholder value of the
/// same kind (an empty `U8` for a primitive value, an empty fragment sequence for encapsulated
/// pixel data) - so it is listed, filtered and removed like any other element, but its value
/// must be taken from here (e.g. as a DICOM JSON BulkDataURI), never from the object.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeferredValues {
    entries: std::collections::BTreeMap<Tag, DeferredEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum DeferredEntry {
    Value(DeferredValueLocation),
    /// One scope per item of the sequence, in item order.
    Items(Vec<DeferredValues>),
}

impl DeferredValues {
    /// The location of `tag`'s value at this level, if it was deferred.
    pub fn value(&self, tag: Tag) -> Option<DeferredValueLocation> {
        match self.entries.get(&tag) {
            Some(DeferredEntry::Value(location)) => Some(*location),
            _ => None,
        }
    }

    /// The deferred values inside item `index` of sequence `tag`, if it has any.
    pub fn item(&self, tag: Tag, index: usize) -> Option<&DeferredValues> {
        match self.entries.get(&tag) {
            Some(DeferredEntry::Items(items)) => items.get(index).filter(|item| !item.is_empty()),
            _ => None,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Record `tag`'s value at this level as deferred to `location` - for building the same
    /// description from another source of locations (e.g. a data set a caller already holds as
    /// references into its file), to write it with the deferred-aware JSON writer.
    pub fn insert_value(&mut self, tag: Tag, location: DeferredValueLocation) {
        self.entries.insert(tag, DeferredEntry::Value(location));
    }

    /// Record the per-item scopes of sequence `tag` (one per item, in item order; empty scopes
    /// for items with nothing deferred). Nothing is recorded when every scope is empty.
    pub fn insert_items(&mut self, tag: Tag, items: Vec<DeferredValues>) {
        if items.iter().any(|item| !item.is_empty()) {
            self.entries.insert(tag, DeferredEntry::Items(items));
        }
    }

    /// The end offset of the furthest deferred value, at any depth - lets a caller confirm the
    /// file really holds every deferred range (skipping by seeking can't detect truncation).
    pub fn max_end(&self) -> u64 {
        self.entries
            .values()
            .map(|entry| match entry {
                DeferredEntry::Value(location) => {
                    location.offset + location.defined_length().unwrap_or(0)
                }
                DeferredEntry::Items(items) => {
                    items.iter().map(DeferredValues::max_end).max().unwrap_or(0)
                }
            })
            .max()
            .unwrap_or(0)
    }
}

/// Like [`build_dataset`], but skips (seeks past) every primitive value `defer` accepts and,
/// when `defer_pixel_sequences` is set, every encapsulated pixel data value - recording where
/// each one was in [`DeferredValues`] instead. `base_offset` is the data set's offset in the
/// file, turning the reader's data-set-relative positions into absolute file offsets.
///
/// With `stop_at_pixel_data`, reading ends at the top-level PixelData header: its value is
/// recorded where it starts (with [`DeferredValueLocation::UNDEFINED_LENGTH`] for encapsulated
/// pixel data, whose end is only known by walking it) and nothing after it is read - the source
/// is never read past that header.
pub(crate) fn build_dataset_deferring<R: Read + std::io::Seek>(
    reader: &mut DataSetReader<dcmnorm_parser::stateful::decode::DynStatefulDecoder<R>>,
    in_item: bool,
    defer: &dyn Fn(&dcmnorm_core::header::DataElementHeader) -> bool,
    defer_pixel_sequences: bool,
    stop_at_pixel_data: bool,
    base_offset: u64,
) -> Result<(InMemDicomObject, DeferredValues), ReadError> {
    let mut elements = Vec::new();
    let mut deferred = DeferredValues::default();
    let to_location =
        |skipped: dcmnorm_parser::dataset::read::SkippedValue| DeferredValueLocation {
            offset: base_offset + skipped.position,
            length: skipped.length,
        };

    loop {
        let Some(token) = reader.next() else {
            if in_item {
                return Err(ReadError::UnexpectedToken {
                    context: "expected ItemEnd, got end of stream",
                });
            }
            break;
        };

        match token? {
            DataToken::ItemEnd if in_item => break,

            DataToken::ElementHeader(header)
                if stop_at_pixel_data && !in_item && header.tag == Tag(0x7FE0, 0x0010) =>
            {
                let location = DeferredValueLocation {
                    offset: base_offset + reader.source_position(),
                    length: header
                        .len
                        .get()
                        .map(u64::from)
                        .unwrap_or(DeferredValueLocation::UNDEFINED_LENGTH),
                };
                deferred
                    .entries
                    .insert(header.tag, DeferredEntry::Value(location));
                elements.push(DataElement::new(
                    header.tag,
                    header.vr,
                    PrimitiveValue::U8(C::new()),
                ));
                break;
            }

            DataToken::PixelSequenceStart if stop_at_pixel_data && !in_item => {
                let tag = Tag(0x7FE0, 0x0010);
                let location = DeferredValueLocation {
                    offset: base_offset + reader.source_position(),
                    length: DeferredValueLocation::UNDEFINED_LENGTH,
                };
                deferred.entries.insert(tag, DeferredEntry::Value(location));
                let placeholder =
                    PixelFragmentSequence::new(C::<u32>::new(), C::<InMemFragment>::new());
                elements.push(DataElement::new(
                    tag,
                    VR::OB,
                    Value::PixelSequence(placeholder),
                ));
                break;
            }

            DataToken::ElementHeader(header) if header.len.is_defined() && defer(&header) => {
                let skipped = reader.skip_value()?;
                deferred
                    .entries
                    .insert(header.tag, DeferredEntry::Value(to_location(skipped)));
                elements.push(DataElement::new(
                    header.tag,
                    header.vr,
                    PrimitiveValue::U8(C::new()),
                ));
            }

            DataToken::ElementHeader(header) => {
                let value = expect_primitive_value(reader)?;
                elements.push(DataElement::new(header.tag, header.vr, value));
            }

            DataToken::SequenceStart { tag, len } => {
                let mut items: C<InMemDicomObject> = C::new();
                let mut item_scopes = Vec::new();
                loop {
                    match next_required(reader)? {
                        DataToken::ItemStart { .. } => {
                            let (item, scope) = build_dataset_deferring(
                                reader,
                                true,
                                defer,
                                defer_pixel_sequences,
                                false,
                                base_offset,
                            )?;
                            items.push(item);
                            item_scopes.push(scope);
                        }
                        DataToken::SequenceEnd => break,
                        _ => {
                            return Err(ReadError::UnexpectedToken {
                                context: "expected ItemStart or SequenceEnd in sequence",
                            })
                        }
                    }
                }
                if item_scopes.iter().any(|scope| !scope.is_empty()) {
                    deferred
                        .entries
                        .insert(tag, DeferredEntry::Items(item_scopes));
                }
                let value = Value::Sequence(DataSetSequence::new(items, len));
                elements.push(DataElement::new(tag, VR::SQ, value));
            }

            DataToken::PixelSequenceStart if defer_pixel_sequences => {
                let skipped = reader.skip_pixel_sequence()?;
                let tag = Tag(0x7FE0, 0x0010);
                deferred
                    .entries
                    .insert(tag, DeferredEntry::Value(to_location(skipped)));
                let placeholder =
                    PixelFragmentSequence::new(C::<u32>::new(), C::<InMemFragment>::new());
                elements.push(DataElement::new(
                    tag,
                    VR::OB,
                    Value::PixelSequence(placeholder),
                ));
            }

            DataToken::PixelSequenceStart => {
                let value = read_pixel_sequence(reader)?;
                elements.push(DataElement::new(Tag(0x7FE0, 0x0010), VR::OB, value));
            }

            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "unexpected token at data set top level",
                })
            }
        }
    }

    elements.sort_by_key(|e| e.tag());
    Ok((InMemDicomObject { elements }, deferred))
}

/// Where [`InMemDicomObject::read_dataset_until_pixel_data`] stopped in a forward-only stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PixelDataStreamStop {
    /// End of stream reached with no top-level `(7FE0,0010) PixelData`.
    Absent,
    /// Stopped right after a defined-length native `(7FE0,0010)` element header.
    Native { vr: VR, length: u32 },
    /// Stopped right after an encapsulated `(7FE0,0010)` undefined-length header.
    Encapsulated,
}

/// Absolute file offset and byte length of one encapsulated pixel data fragment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FragmentLocation {
    pub offset: u64,
    pub length: u32,
}

/// Location of top-level `(7FE0,0010) PixelData` left on disk by
/// [`crate::OpenFileOptions::open_file_deferring_pixel_data`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeferredPixelData {
    Absent,
    Native {
        vr: VR,
        offset: u64,
        length: u32,
    },
    Encapsulated {
        offset_table: Vec<u32>,
        fragments: Vec<FragmentLocation>,
        end_offset: u64,
    },
}

impl DeferredPixelData {
    /// Furthest byte offset referenced in the source file (used to detect truncated files).
    pub fn max_end(&self) -> u64 {
        match self {
            Self::Absent => 0,
            Self::Native { offset, length, .. } => offset.saturating_add(u64::from(*length)),
            Self::Encapsulated {
                fragments,
                end_offset,
                ..
            } => fragments
                .iter()
                .map(|f| f.offset.saturating_add(u64::from(f.length)))
                .max()
                .unwrap_or(0)
                .max(*end_offset),
        }
    }
}

/// Read an entire data set while skipping ONLY top-level `(7FE0,0010) PixelData` (native or
/// encapsulated). Nested elements (such as `PixelData` inside `IconImageSequence`) and trailing
/// elements after `PixelData` are read normally.
pub(crate) fn build_dataset_deferring_pixel_data<R: Read + std::io::Seek>(
    reader: &mut DataSetReader<dcmnorm_parser::stateful::decode::DynStatefulDecoder<R>>,
    base_offset: u64,
) -> Result<(InMemDicomObject, DeferredPixelData), ReadError> {
    const PIXEL_DATA: Tag = Tag(0x7FE0, 0x0010);
    let mut elements = Vec::new();
    let mut pixel_data = DeferredPixelData::Absent;

    while let Some(token) = reader.next() {
        match token? {
            DataToken::ElementHeader(header)
                if header.tag == PIXEL_DATA && header.len.is_defined() =>
            {
                let skipped = reader.skip_value()?;
                let Ok(length) = u32::try_from(skipped.length) else {
                    return Err(ReadError::UnexpectedToken {
                        context: "native PixelData length exceeds u32::MAX",
                    });
                };
                pixel_data = DeferredPixelData::Native {
                    vr: header.vr,
                    offset: base_offset + skipped.position,
                    length,
                };
            }

            DataToken::ElementHeader(header) => {
                let value = expect_primitive_value(reader)?;
                elements.push(DataElement::new(header.tag, header.vr, value));
            }

            DataToken::SequenceStart { tag, len } => {
                let mut items: C<InMemDicomObject> = C::new();
                loop {
                    match next_required(reader)? {
                        DataToken::ItemStart { .. } => {
                            items.push(build_dataset(reader, true)?);
                        }
                        DataToken::SequenceEnd => break,
                        _ => {
                            return Err(ReadError::UnexpectedToken {
                                context: "expected ItemStart or SequenceEnd in sequence",
                            })
                        }
                    }
                }
                let value = Value::Sequence(DataSetSequence::new(items, len));
                elements.push(DataElement::new(tag, VR::SQ, value));
            }

            DataToken::PixelSequenceStart => {
                let skipped = reader.skip_pixel_sequence_indexed()?;
                let fragments = skipped
                    .fragments
                    .into_iter()
                    .map(|frag| FragmentLocation {
                        offset: base_offset + frag.position,
                        length: frag.length,
                    })
                    .collect();
                pixel_data = DeferredPixelData::Encapsulated {
                    offset_table: skipped.offset_table,
                    fragments,
                    end_offset: base_offset + skipped.end_position,
                };
            }

            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "unexpected token at data set top level",
                })
            }
        }
    }

    elements.sort_by_key(|e| e.tag());
    Ok((InMemDicomObject { elements }, pixel_data))
}

/// Read the token sequence following a `PixelSequenceStart` token (already consumed by the
/// caller). Per `dcmnorm_parser::dataset::read::DataSetReader`'s actual protocol (confirmed
/// against its own test fixtures): the offset table is itself framed as the *first item* -
/// `ItemStart { len }`, then `OffsetTable(vec)` only if `len > 0` (an empty offset table item
/// produces no `OffsetTable` token at all), then `ItemEnd` - followed by one
/// `ItemStart`/`ItemValue`/`ItemEnd` triple per fragment, terminated by `SequenceEnd`.
fn read_pixel_sequence(
    tokens: &mut impl Iterator<Item = Result<DataToken, dcmnorm_parser::dataset::read::Error>>,
) -> Result<Value<InMemDicomObject, InMemFragment>, ReadError> {
    let offset_table = match next_required(tokens)? {
        DataToken::ItemStart {
            len: dcmnorm_core::header::Length(0),
        } => {
            expect_item_end(tokens)?;
            Vec::new()
        }
        DataToken::ItemStart { .. } => match next_required(tokens)? {
            DataToken::OffsetTable(t) => {
                expect_item_end(tokens)?;
                t
            }
            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "expected OffsetTable in the first item of encapsulated pixel data",
                })
            }
        },
        _ => {
            return Err(ReadError::UnexpectedToken {
                context: "expected ItemStart for the offset table item",
            })
        }
    };

    let mut fragments: C<InMemFragment> = C::new();
    loop {
        match next_required(tokens)? {
            DataToken::ItemStart { .. } => {
                let bytes = match next_required(tokens)? {
                    DataToken::ItemValue(bytes) => bytes,
                    _ => {
                        return Err(ReadError::UnexpectedToken {
                            context: "expected ItemValue for pixel data fragment",
                        })
                    }
                };
                expect_item_end(tokens)?;
                fragments.push(bytes);
            }
            DataToken::SequenceEnd => break,
            _ => {
                return Err(ReadError::UnexpectedToken {
                    context: "expected ItemStart or SequenceEnd in pixel data sequence",
                })
            }
        }
    }

    Ok(Value::PixelSequence(PixelFragmentSequence::new(
        offset_table,
        fragments,
    )))
}

fn expect_item_end(
    tokens: &mut impl Iterator<Item = Result<DataToken, dcmnorm_parser::dataset::read::Error>>,
) -> Result<(), ReadError> {
    match next_required(tokens)? {
        DataToken::ItemEnd => Ok(()),
        _ => Err(ReadError::UnexpectedToken {
            context: "expected ItemEnd",
        }),
    }
}

fn next_required(
    tokens: &mut impl Iterator<Item = Result<DataToken, dcmnorm_parser::dataset::read::Error>>,
) -> Result<DataToken, ReadError> {
    tokens
        .next()
        .ok_or(ReadError::UnexpectedToken {
            context: "unexpected end of token stream",
        })?
        .map_err(ReadError::from)
}

fn expect_primitive_value(
    tokens: &mut impl Iterator<Item = Result<DataToken, dcmnorm_parser::dataset::read::Error>>,
) -> Result<PrimitiveValue, ReadError> {
    match next_required(tokens)? {
        DataToken::PrimitiveValue(v) => Ok(v),
        _ => Err(ReadError::UnexpectedToken {
            context: "expected PrimitiveValue after ElementHeader",
        }),
    }
}

/// Write one element (recursively, for sequences/pixel data) as its token sequence.
pub(crate) fn write_element_tokens<W: Write>(
    writer: &mut DataSetWriter<W, dcmnorm_encoding::transfer_syntax::DynEncoder<'_, W>>,
    element: &InMemElement,
) -> Result<(), WriteError> {
    match element.value() {
        Value::Primitive(pv) => {
            let header = dcmnorm_core::header::DataElementHeader::new(
                element.tag(),
                element.vr(),
                dcmnorm_core::header::Length::defined({
                    let len = pv.calculate_byte_len() as u32;
                    len + (len % 2)
                }),
            );
            writer
                .write_primitive_element(header, pv)
                .map_err(|source| WriteError::Dataset { source })?;
        }
        Value::Sequence(seq) => {
            writer
                .write(DataToken::SequenceStart {
                    tag: element.tag(),
                    len: seq.length(),
                })
                .map_err(|source| WriteError::Dataset { source })?;
            for item in seq.items() {
                writer
                    .write(DataToken::ItemStart {
                        len: dcmnorm_core::header::Length::UNDEFINED,
                    })
                    .map_err(|source| WriteError::Dataset { source })?;
                for item_element in item.iter() {
                    write_element_tokens(writer, item_element)?;
                }
                writer
                    .write(DataToken::ItemEnd)
                    .map_err(|source| WriteError::Dataset { source })?;
            }
            writer
                .write(DataToken::SequenceEnd)
                .map_err(|source| WriteError::Dataset { source })?;
        }
        Value::PixelSequence(pix) => {
            writer
                .write(DataToken::PixelSequenceStart)
                .map_err(|source| WriteError::Dataset { source })?;
            // The offset table is itself framed as the first item, matching the protocol
            // DataSetReader expects on read-back (see read_pixel_sequence's doc comment) - the
            // writer does not wrap DataToken::OffsetTable in an item on its own.
            let offset_table = pix.offset_table();
            writer
                .write(DataToken::ItemStart {
                    len: dcmnorm_core::header::Length::defined((offset_table.len() * 4) as u32),
                })
                .map_err(|source| WriteError::Dataset { source })?;
            if !offset_table.is_empty() {
                writer
                    .write(DataToken::OffsetTable(offset_table.to_vec()))
                    .map_err(|source| WriteError::Dataset { source })?;
            }
            writer
                .write(DataToken::ItemEnd)
                .map_err(|source| WriteError::Dataset { source })?;
            for fragment in pix.fragments() {
                writer
                    .write(DataToken::ItemStart {
                        len: dcmnorm_core::header::Length::defined(fragment.len() as u32),
                    })
                    .map_err(|source| WriteError::Dataset { source })?;
                writer
                    .write_item_value(fragment)
                    .map_err(|source| WriteError::Dataset { source })?;
                writer
                    .write(DataToken::ItemEnd)
                    .map_err(|source| WriteError::Dataset { source })?;
            }
            writer
                .write(DataToken::SequenceEnd)
                .map_err(|source| WriteError::Dataset { source })?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use dcmnorm_encoding::transfer_syntax::TransferSyntaxIndex;
    use dcmnorm_transcode::TransferSyntaxRegistry;

    /// Documents the actual, precise boundary of a real, currently-live constraint (not a bug
    /// to fix here - see below): the default character set codec used when no
    /// SpecificCharacterSet (0008,0005) is declared is `DefaultCharacterSetCodec`, which despite
    /// its "ISO_IR 6" name actually encodes as ISO-8859-1/Latin-1 (a strict superset of 7-bit
    /// ASCII), not strict 7-bit ASCII - inherited unchanged from the mechanically-ported
    /// `dcmnorm-encoding` (see its README; this crate's write orchestration was deliberately
    /// left behavior-preserving in Phase 4 of the dicom-rs removal plan). So Western-European
    /// accented text (French/German/Spanish names, etc.) already writes successfully without
    /// any declared charset - only text with characters *outside* Latin-1 (CJK, Cyrillic, Greek,
    /// emoji, ...) still fails. `dcmnorm`'s `scp.rs` unconditionally injects
    /// `SpecificCharacterSet=ISO_IR 192` (UTF-8) before writing synthesized datasets precisely
    /// to cover that remaining gap, since C-FIND results can carry PHI in any script. Making the
    /// writer natively permissive for the full Unicode range (removing the need for that
    /// workaround entirely) is a deliberate, not-yet-done follow-up: doing it safely for every
    /// caller - including the DIMSE streaming paths, which write directly into a
    /// caller-supplied sink rather than a buffer this crate could retry into - needs a
    /// buffering strategy that doesn't regress memory usage for large pixel-data payloads, not
    /// a change to make incidentally.
    #[test]
    fn default_charset_covers_latin1_but_not_wider_unicode() {
        let ts = TransferSyntaxRegistry
            .get(dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN)
            .unwrap();

        // Latin-1-representable accented text: succeeds even with no declared charset.
        let latin1_object = InMemDicomObject::from_element_iter([DataElement::new(
            Tag(0x0010, 0x0010),
            VR::PN,
            PrimitiveValue::from("M\u{fc}ller^J\u{f6}rg".to_owned()), // "Müller^Jörg"
        )]);
        let mut buf = Vec::new();
        latin1_object
            .write_dataset_with_ts(&mut buf, ts)
            .expect("Latin-1-representable text should write even without a declared charset");

        // Text outside Latin-1 (CJK): fails with no declared charset...
        let cjk_object = InMemDicomObject::from_element_iter([DataElement::new(
            Tag(0x0010, 0x0010),
            VR::PN,
            PrimitiveValue::from("\u{5f20}^\u{4f1f}".to_owned()), // "张^伟"
        )]);
        let mut buf2 = Vec::new();
        assert!(
            cjk_object.write_dataset_with_ts(&mut buf2, ts).is_err(),
            "expected non-Latin-1 text to fail to encode without a declared charset - if this \
             now succeeds, the default codec's behavior changed and scp.rs's \
             SpecificCharacterSet injection workaround may no longer be necessary"
        );

        // ...but succeeds once a UTF-8 charset is declared, matching scp.rs's workaround.
        let cjk_with_charset = InMemDicomObject::from_element_iter([
            DataElement::new(
                Tag(0x0008, 0x0005),
                VR::CS,
                PrimitiveValue::from("ISO_IR 192".to_owned()),
            ),
            DataElement::new(
                Tag(0x0010, 0x0010),
                VR::PN,
                PrimitiveValue::from("\u{5f20}^\u{4f1f}".to_owned()),
            ),
        ]);
        let mut buf3 = Vec::new();
        cjk_with_charset
            .write_dataset_with_ts(&mut buf3, ts)
            .expect("declared SpecificCharacterSet=ISO_IR 192 should make CJK text writable");
    }

    /// `apply()` only implements single-step, top-level tag selectors (dcmnorm's own codec
    /// adapters never build anything else). Before this was hardened, a nested-sequence
    /// selector silently did nothing instead of erroring - this proves the fix: such a selector
    /// now returns `ApplyOpError::UnsupportedSelector`, and (per the trait's "no changes on
    /// error" contract) leaves the object untouched.
    #[test]
    fn apply_rejects_nested_selector_instead_of_silently_no_opping() {
        use dcmnorm_core::ops::{AttributeAction, AttributeSelector, AttributeSelectorStep};

        let sequence_tag = Tag(0x0008, 0x1140); // Referenced Image Sequence
        let inner_tag = Tag(0x0008, 0x1150); // Referenced SOP Class UID

        let mut object = InMemDicomObject::from_element_iter([]);
        let selector = AttributeSelector::new([
            AttributeSelectorStep::Tag(sequence_tag), // auto-reinterpreted as Nested{item: 0}
            AttributeSelectorStep::Tag(inner_tag),
        ])
        .expect("well-formed two-step selector");
        let op = AttributeOp::new(
            selector,
            AttributeAction::SetStr("1.2.840.10008.5.1.4.1.1.7".into()),
        );

        let result = object.apply(op);
        assert!(
            matches!(result, Err(ApplyOpError::UnsupportedSelector)),
            "expected UnsupportedSelector, got {result:?}"
        );
        assert!(object.is_empty(), "object must be left untouched on error");
    }

    fn fixture_path(name: &str) -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("test")
            .join("files")
            .join(name)
    }

    fn open_fixture(name: &str) -> crate::file::DefaultDicomObject {
        crate::file::DefaultDicomObject::open_file(fixture_path(name))
            .unwrap_or_else(|e| panic!("{name} should open: {e}"))
    }

    // The deflate-wiring regression test lives in the top-level `dcmnorm` crate's test suite
    // (src/dicom_io), not here: this crate's own Cargo.toml depends on dcmnorm-transcode with
    // `default-features = false` and no explicit `deflate` feature, so `FlateAdapter` isn't even
    // compiled in when this crate is tested standalone - only `dcmnorm`'s own build (which does
    // request the `deflate` feature) actually exercises the fix.

    /// dcmnorm-core has its own fork-specific fix for nonstandard `xs`/`ox` ambiguous-VR
    /// shorthand bytes (see `dcmnorm-core/src/header.rs`); this exercises that same code path
    /// end-to-end against a real file that actually contains one, rather than only a synthetic
    /// byte pattern.
    #[test]
    fn nonstandard_vr_shorthand_file_parses_without_desyncing() {
        let object = open_fixture("bad_vr.dcm");
        assert!(!object.is_empty());
    }

    #[test]
    fn vr_un_element_parses_without_error() {
        let object = open_fixture("vr_un.dcm");
        assert!(!object.is_empty());
    }

    #[test]
    fn nested_private_sequence_parses_without_error() {
        let object = open_fixture("nested_private_sq.dcm");
        assert!(!object.is_empty());
    }

    #[test]
    fn private_sequence_parses_without_error() {
        let object = open_fixture("private_sq.dcm");
        assert!(!object.is_empty());
    }

    #[test]
    fn empty_specific_character_set_parses_without_error() {
        let object = open_fixture("empty_charset.dcm");
        assert!(!object.is_empty());
    }

    /// A malformed/unusual sequence structure must not desync or panic the parser - dcmnorm's
    /// tolerant parser accepts this particular file rather than erroring, which is itself worth
    /// pinning down (a future change that makes this start erroring, or panicking, should have
    /// to touch this assertion deliberately).
    #[test]
    fn malformed_sequence_file_parses_tolerantly() {
        let object = open_fixture("bad_sequence.dcm");
        assert_eq!(
            object
                .get(dcmnorm_dictionary::tags::MODALITY)
                .and_then(|e| e.to_str().ok())
                .as_deref(),
            Some("CT")
        );
    }

    #[test]
    fn missing_transfer_syntax_uid_is_a_clean_error_not_a_panic() {
        let result =
            crate::file::DefaultDicomObject::open_file(fixture_path("meta_missing_tsyntax.dcm"));
        assert!(result.is_err(), "expected an error, got {result:?}");
    }

    #[test]
    fn missing_meta_group_length_is_a_clean_error_not_a_panic() {
        let result =
            crate::file::DefaultDicomObject::open_file(fixture_path("nometa_group_length.dcm"));
        assert!(result.is_err(), "expected an error, got {result:?}");
    }

    #[test]
    fn truncated_pixel_data_is_a_clean_error_not_a_panic() {
        let result = crate::file::DefaultDicomObject::open_file(fixture_path("mr_truncated.dcm"));
        assert!(result.is_err(), "expected an error, got {result:?}");
    }

    #[test]
    fn truncated_rtplan_is_a_clean_error_not_a_panic() {
        let result =
            crate::file::DefaultDicomObject::open_file(fixture_path("rtplan_truncated.dcm"));
        assert!(result.is_err(), "expected an error, got {result:?}");
    }

    #[test]
    fn odd_length_pixel_data_parses_with_correct_dimensions() {
        let object = open_fixture("sc_odd_length.dcm");
        assert_eq!(
            object
                .get(dcmnorm_dictionary::tags::ROWS)
                .and_then(|e| e.uint16().ok()),
            Some(3)
        );
        assert_eq!(
            object
                .get(dcmnorm_dictionary::tags::COLUMNS)
                .and_then(|e| e.uint16().ok()),
            Some(3)
        );
    }

    #[test]
    fn odd_length_jpeg_pixel_data_parses_correctly() {
        let object = open_fixture("sc_odd_length_jpeg.dcm");
        assert_eq!(
            object
                .get(dcmnorm_dictionary::tags::ROWS)
                .and_then(|e| e.uint16().ok()),
            Some(3)
        );
    }

    /// Deeply nested sequences (RT Structure Set's ROI Contour -> Contour Sequence -> Contour
    /// Data, several levels deep) are a good generic-parser stress test distinct from the
    /// mostly-flat CT/MR/US fixtures the rest of this suite uses. This particular fixture is
    /// itself a bare Implicit VR LE data set (no 128-byte preamble/"DICM" magic), so it's read
    /// via `read_dataset_with_ts` rather than `open_file`.
    #[test]
    fn rtstruct_with_deeply_nested_sequences_parses_without_error() {
        let ts = dcmnorm_transcode::TransferSyntaxRegistry
            .get(dcmnorm_dictionary::uids::IMPLICIT_VR_LITTLE_ENDIAN)
            .unwrap();
        let bytes = std::fs::read(fixture_path("rtstruct.dcm")).unwrap();
        let object = InMemDicomObject::read_dataset_with_ts(std::io::Cursor::new(bytes), ts)
            .expect("rtstruct.dcm should parse as a bare Implicit VR LE data set");
        assert_eq!(
            object
                .get(dcmnorm_dictionary::tags::MODALITY)
                .and_then(|e| e.to_str().ok())
                .as_deref(),
            Some("RTSTRUCT")
        );
    }

    #[test]
    fn rtdose_object_parses_without_error() {
        let object = open_fixture("rtdose.dcm");
        assert_eq!(
            object
                .get(dcmnorm_dictionary::tags::MODALITY)
                .and_then(|e| e.to_str().ok())
                .as_deref(),
            Some("RTDOSE")
        );
    }

    /// Matches the upstream `dicom-rs` test this fork deliberately didn't port (see
    /// `dcmnorm-transcode/README.md`'s "What was left out") - fragment count, offset table, and
    /// the JPEG2000 codestream's own SOC (0xFF4F)/EOC (0xFFD9) marker bytes at the fragment's
    /// boundaries, now checked against a real (if tiny) local fixture instead of a network-
    /// fetched one.
    #[test]
    fn jpeg2000_pixel_sequence_has_the_expected_fragment_and_offset_table_shape() {
        let object = open_fixture("jpeg2000_tiny.dcm");
        let element = object
            .element(dcmnorm_dictionary::tags::PIXEL_DATA)
            .unwrap();
        match element.value() {
            Value::PixelSequence(seq) => {
                assert_eq!(seq.offset_table().len(), 0);
                assert_eq!(seq.fragments().len(), 1);
                let fragment = &seq.fragments()[0];
                assert_eq!(
                    fragment[0..2],
                    [0xFF, 0x4F],
                    "fragment should start with the JPEG2000 SOC marker"
                );
                assert_eq!(
                    fragment[fragment.len() - 2..],
                    [0xFF, 0xD9],
                    "fragment should end with the JPEG2000 EOC marker"
                );
            }
            other => panic!("expected a pixel sequence, got {other:?}"),
        }
    }

    #[test]
    fn read_until_stops_before_reading_pixel_data_after_stop_tag() {
        use dcmnorm_encoding::transfer_syntax::TransferSyntaxIndex;

        // Build a sparse dataset: (0008,0018) SOPInstanceUID immediately followed by a
        // (7FE0,0010) PixelData header declaring 100 MiB of payload, with ZERO payload bytes
        // present. `read_until(Tag(0x0008, 0x0019))` must stop at the header without trying to
        // read or allocate the 100 MiB PixelData value.
        let ts = dcmnorm_transcode::TransferSyntaxRegistry
            .get(dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN)
            .unwrap();
        let mut raw = Vec::new();
        let mut head = InMemDicomObject::new_empty();
        head.put(DataElement::new(
            dcmnorm_dictionary::tags::SOP_INSTANCE_UID,
            VR::UI,
            PrimitiveValue::from("1.2.3.4.5".to_owned()),
        ));
        head.write_dataset_with_ts(&mut raw, ts).unwrap();
        // Append Explicit VR LE header for (7FE0,0010) OB with declared length = 100 MiB, no bytes.
        raw.extend_from_slice(&0x7FE0u16.to_le_bytes());
        raw.extend_from_slice(&0x0010u16.to_le_bytes());
        raw.extend_from_slice(b"OB");
        raw.extend_from_slice(&0u16.to_le_bytes());
        raw.extend_from_slice(&(100u32 * 1024 * 1024).to_le_bytes());

        let parsed = read_dataset_until(
            std::io::Cursor::new(raw),
            ts,
            Tag(0x0008, 0x0019),
            DataSetReaderOptions::default(),
        )
        .expect("read_until must stop at PixelData header without reading its value");
        assert_eq!(
            parsed
                .element(dcmnorm_dictionary::tags::SOP_INSTANCE_UID)
                .unwrap()
                .to_str()
                .unwrap(),
            "1.2.3.4.5"
        );
        assert!(parsed
            .element(dcmnorm_dictionary::tags::PIXEL_DATA)
            .is_err());
    }
}