dcmnorm 0.20.1

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
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
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use dcmnorm_core::value::{PixelFragmentSequence, Value as DicomValue};
use dcmnorm_core::{PrimitiveValue, Tag, VR};
use dcmnorm_dictionary::{tags, uids};
use serde_json::{Map as JsonMap, Value as JsonValue};
use std::fs;

use super::common::invalid_json_value;
use super::types::{
    BulkRepresentation, DicomJsonBulkDataMode, DicomJsonError, DicomJsonWriteOptions,
    ElementLocation, ParsedHeader, TransferSyntaxInfo, ITEM_DELIMITATION_TAG, ITEM_TAG,
    SEQUENCE_DELIMITATION_TAG,
};

pub(crate) const INLINE_BINARY_URI_THRESHOLD: usize = 32;

pub(super) fn bulk_json_value<I, P>(
    tag: Tag,
    vr: VR,
    value: &DicomValue<I, P>,
    options: DicomJsonWriteOptions<'_>,
) -> Result<JsonValue, DicomJsonError>
where
    P: AsRef<[u8]>,
{
    let mut object = JsonMap::new();
    match bulk_representation(tag, vr, value, options)? {
        BulkRepresentation::Uri(uri) => {
            object.insert("BulkDataURI".to_owned(), JsonValue::String(uri));
        }
        BulkRepresentation::InlineBinary(data) => {
            object.insert("InlineBinary".to_owned(), JsonValue::String(data));
        }
    }
    Ok(JsonValue::Object(object))
}

pub(super) fn bulk_representation<I, P>(
    tag: Tag,
    vr: VR,
    value: &DicomValue<I, P>,
    options: DicomJsonWriteOptions<'_>,
) -> Result<BulkRepresentation, DicomJsonError>
where
    P: AsRef<[u8]>,
{
    if let Some(location) = options
        .deferred_bulk_data
        .and_then(|deferred| deferred.value(tag))
    {
        // Never loaded, so it can only be referenced: the location came from the parser
        // itself, so unlike a bulk_data_source scan there is nothing to locate or verify.
        if options.bulk_data_mode != DicomJsonBulkDataMode::Uri {
            return Err(DicomJsonError::InvalidBulkDataUri(format!(
                "{tag} was deferred (not loaded) but must be written inline"
            )));
        }
        let uri = options.bulk_data_uri(tag, vr, location.offset, location.defined_length());
        return Ok(BulkRepresentation::Uri(uri));
    }

    let raw_bytes = raw_value_bytes(tag, vr, value, None)?;
    let expected_bytes_for_lookup = match value {
        DicomValue::PixelSequence(_) => None,
        _ => Some(raw_bytes.as_ref()),
    };

    if options.bulk_data_mode == DicomJsonBulkDataMode::Uri {
        if let Some(source) = options.bulk_data_source {
            if raw_bytes.len() <= INLINE_BINARY_URI_THRESHOLD {
                return Ok(BulkRepresentation::InlineBinary(
                    BASE64_STANDARD.encode(&raw_bytes),
                ));
            }

            // locate_element_value re-scans the raw file by hand (tag by tag, from the start of
            // the dataset) to find this element's byte range - it's a best-effort accelerator
            // that lets the client fetch large values on demand instead of inlining them here,
            // not something JSON generation should ever hard-fail on. Real-world files can
            // contain constructs this hand-rolled scanner doesn't model correctly (e.g. a
            // Siemens CSA header stored as a private sequence of VR=UN elements with undefined
            // length, which per DICOM PS3.5 6.2.2 requires switching to Implicit VR parsing for
            // its nested content - a rule this scanner doesn't implement) and desync partway
            // through the dataset - if that happens, fall back to inlining THIS element (we
            // already have its correctly decoded bytes via the proper parser, in raw_bytes)
            // rather than failing the entire study's metadata - a working (if occasionally
            // larger) response beats a broken one.
            //
            // Once the scan has failed once for this source, bulk_scan_failed (set by the
            // caller, shared across every element of the same file/write pass) short-circuits
            // every later attempt: every bulk element restarts its scan from the same beginning
            // position, so if one already desynced, all the rest are equally doomed - retrying
            // each independently turned one failure into every bulk element paying its own full
            // failed scan (a multi-second stall for files with several such elements, since
            // there's no early delimiter to find and the scan runs to EOF each time).
            let already_broken = options.bulk_scan_failed.is_some_and(|cell| cell.get());
            if !already_broken {
                // bulk_scan_cursor: elements are visited by the JSON writer in ascending tag
                // order, which for a conformant DICOM dataset is also ascending file-offset
                // order (top-level elements and, within a sequence, its items are both required
                // to appear in that order). So each successful lookup can hand the NEXT one a
                // hint to resume scanning from, instead of restarting at the dataset's start
                // every time. This matters most for a tag that repeats across many sibling
                // sequence items (e.g. a private per-item block) - without the hint, finding the
                // Nth occurrence means walking past all N-1 earlier non-matching ones from
                // scratch, for every one of the N elements: O(N^2) total instead of O(N).
                // Purely a speed hint, not a correctness assumption: if scanning from the hint
                // doesn't find the tag, locate_element_value retries once from the true start
                // before giving up, so an out-of-order visit can never cause a false miss.
                let resume_hint = options.bulk_scan_cursor.map(|cell| cell.get()).unwrap_or(0);
                let value_width = primitive_value_width(value);
                match locate_element_value(
                    source,
                    tag,
                    expected_bytes_for_lookup,
                    value_width,
                    resume_hint,
                ) {
                    Ok(Some(location)) => {
                        if let Some(cell) = options.bulk_scan_cursor {
                            let end = location.offset + location.length;
                            if end > cell.get() {
                                cell.set(end);
                            }
                        }
                        let uri = options.bulk_data_uri(
                            tag,
                            vr,
                            location.offset as u64,
                            Some(location.length as u64),
                        );
                        return Ok(BulkRepresentation::Uri(uri));
                    }
                    Ok(None) => {}
                    Err(_) => {
                        if let Some(cell) = options.bulk_scan_failed {
                            cell.set(true);
                        }
                    }
                }
            }

            return Ok(BulkRepresentation::InlineBinary(
                BASE64_STANDARD.encode(&raw_bytes),
            ));
        }
    }

    Ok(BulkRepresentation::InlineBinary(
        BASE64_STANDARD.encode(&raw_bytes),
    ))
}

pub(super) fn raw_value_bytes<'a, I, P>(
    tag: Tag,
    vr: VR,
    value: &'a DicomValue<I, P>,
    bulk_data_source: Option<&'a [u8]>,
) -> Result<std::borrow::Cow<'a, [u8]>, DicomJsonError>
where
    P: AsRef<[u8]>,
{
    // Borrowed wherever possible: for native byte data (e.g. a multi-frame PixelData) an owned
    // copy here was a whole-value memcpy just to compare/encode it.
    if let Some(source) = bulk_data_source {
        if let Some(location) = locate_element_value(source, tag, None, 1, 0)? {
            return Ok(std::borrow::Cow::Borrowed(
                &source[location.offset..location.offset + location.length],
            ));
        }
    }

    match value {
        DicomValue::Primitive(primitive) => Ok(primitive.to_bytes()),
        DicomValue::PixelSequence(pixel_sequence) => Ok(std::borrow::Cow::Owned(
            pixel_sequence_to_bytes(pixel_sequence),
        )),
        DicomValue::Sequence(_) => Err(DicomJsonError::UnsupportedBulkDataVr { tag, vr }),
    }
}

pub(super) fn resolve_flat_bulk_bytes(
    keyword: &str,
    json: &JsonValue,
    bulk_data_source: Option<&[u8]>,
) -> Result<Option<Vec<u8>>, DicomJsonError> {
    let JsonValue::Object(object) = json else {
        return Ok(None);
    };

    if let Some(JsonValue::String(encoded)) = object.get("InlineBinary") {
        let bytes = BASE64_STANDARD
            .decode(encoded)
            .map_err(|_| invalid_json_value(keyword, "InlineBinary is not valid base64"))?;
        return Ok(Some(bytes));
    }

    if let Some(JsonValue::String(uri)) = object.get("BulkDataURI") {
        return Ok(Some(resolve_bulk_data_uri_with_optional_source(
            uri,
            bulk_data_source,
        )?));
    }

    Ok(None)
}

pub(super) fn resolve_standard_bulk_bytes(
    tag: Tag,
    vr: VR,
    object: &JsonMap<String, JsonValue>,
    bulk_data_source: Option<&[u8]>,
) -> Result<Option<Vec<u8>>, DicomJsonError> {
    if let Some(JsonValue::String(encoded)) = object.get("InlineBinary") {
        let bytes = BASE64_STANDARD.decode(encoded).map_err(|_| {
            DicomJsonError::InvalidStandardElement {
                tag: super::common::tag_key(tag),
                message: "InlineBinary is not valid base64".to_owned(),
            }
        })?;
        return Ok(Some(bytes));
    }

    if let Some(JsonValue::String(uri)) = object.get("BulkDataURI") {
        return Ok(Some(resolve_bulk_data_uri_with_optional_source(
            uri,
            bulk_data_source,
        )?));
    }

    if is_bulk_vr(vr) && tag == tags::PIXEL_DATA {
        return Ok(None);
    }

    // No InlineBinary/BulkDataURI given for a non-PixelData bulk element (VM 0):
    // this is how a legitimately empty OB/OW/UN/etc. element round-trips, since
    // the writer omits both keys rather than emit an empty one of them (see
    // write_standard_json_value). PixelData is excluded above since an empty
    // image is never legitimate and more likely signals a caller bug.
    Ok(Some(Vec::new()))
}

/// `inline_binary`: where `bytes` came from. A BulkDataURI's bytes are the source file's, in the
/// document's transfer syntax byte order. InlineBinary always holds what the writer got from
/// `PrimitiveValue::to_bytes`: little-endian, whatever the transfer syntax.
pub(super) fn raw_bytes_to_dicom_value(
    tag: Tag,
    vr: VR,
    bytes: &[u8],
    transfer_syntax_uid: &str,
    inline_binary: bool,
) -> Result<DicomValue<dcmnorm_object::InMemDicomObject>, DicomJsonError> {
    if tag == tags::PIXEL_DATA && is_encapsulated_transfer_syntax(transfer_syntax_uid) {
        return pixel_sequence_from_bytes(bytes);
    }

    let little_endian = is_little_endian_transfer_syntax(transfer_syntax_uid)? || inline_binary;

    let primitive = match vr {
        VR::OB | VR::UN => PrimitiveValue::U8(bytes.to_vec().into()),
        VR::OW => PrimitiveValue::U16(decode_u16_values(tag, vr, bytes, little_endian)?.into()),
        VR::OF => PrimitiveValue::F32(decode_f32_values(tag, vr, bytes, little_endian)?.into()),
        VR::OD => PrimitiveValue::F64(decode_f64_values(tag, vr, bytes, little_endian)?.into()),
        VR::OL => PrimitiveValue::U32(decode_u32_values(tag, vr, bytes, little_endian)?.into()),
        VR::OV => PrimitiveValue::U64(decode_u64_values(tag, vr, bytes, little_endian)?.into()),
        _ => return Err(DicomJsonError::UnsupportedBulkDataVr { tag, vr }),
    };

    Ok(primitive.into())
}

pub(super) fn is_bulk_value<I, P>(tag: Tag, vr: VR, value: &DicomValue<I, P>) -> bool {
    matches!(value, DicomValue::PixelSequence(_))
        || (primitive_is_bulk(vr) && tag != tags::WAVEFORM_DATA)
}

pub(super) fn primitive_is_bulk(vr: VR) -> bool {
    matches!(
        vr,
        VR::OB | VR::OD | VR::OF | VR::OL | VR::OV | VR::OW | VR::UN
    )
}

pub(super) fn is_bulk_vr(vr: VR) -> bool {
    primitive_is_bulk(vr)
}

pub(super) fn resolve_bulk_data_uri(uri: &str, source: &[u8]) -> Result<Vec<u8>, DicomJsonError> {
    let (offset, length) = parse_bulk_data_uri(uri)?;
    let end = offset.saturating_add(length);
    if end > source.len() {
        return Err(DicomJsonError::BulkDataOutOfRange {
            uri: uri.to_owned(),
            length: source.len(),
        });
    }

    Ok(source[offset..end].to_vec())
}

fn resolve_bulk_data_uri_with_optional_source(
    uri: &str,
    bulk_data_source: Option<&[u8]>,
) -> Result<Vec<u8>, DicomJsonError> {
    // "file://" is a self-contained reference to an arbitrary file on disk and
    // never depends on bulk_data_source - check it first, regardless of whether
    // a source was given, so a document can mix "?offset=..&length=.." elements
    // (resolved against bulk_data_source) with "file://" elements (resolved
    // independently) in the same write.
    if let Some(source) = try_read_bulk_data_uri_source(uri)? {
        return resolve_bulk_data_uri(uri, source.as_slice());
    }

    if let Some(source) = bulk_data_source {
        return resolve_bulk_data_uri(uri, source);
    }

    Err(DicomJsonError::MissingBulkDataSource(uri.to_owned()))
}

fn try_read_bulk_data_uri_source(uri: &str) -> Result<Option<Vec<u8>>, DicomJsonError> {
    let Some(path) = file_path_from_bulk_data_uri(uri)? else {
        return Ok(None);
    };

    fs::read(path)
        .map(Some)
        .map_err(|_| DicomJsonError::MissingBulkDataSource(uri.to_owned()))
}

fn file_path_from_bulk_data_uri(uri: &str) -> Result<Option<String>, DicomJsonError> {
    if !uri.starts_with("file://") {
        return Ok(None);
    }

    let after_scheme = &uri[7..];
    let path_part = after_scheme
        .split_once('?')
        .map(|(path, _)| path)
        .unwrap_or(after_scheme);

    if path_part.is_empty() {
        return Err(DicomJsonError::InvalidBulkDataUri(uri.to_owned()));
    }

    let local_path = if let Some(path) = path_part.strip_prefix("localhost/") {
        format!("/{path}")
    } else {
        path_part.to_owned()
    };

    percent_decode_uri_path(local_path.as_str())
        .map(Some)
        .ok_or_else(|| DicomJsonError::InvalidBulkDataUri(uri.to_owned()))
}

fn percent_decode_uri_path(path: &str) -> Option<String> {
    let bytes = path.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;

    while index < bytes.len() {
        if bytes[index] == b'%' {
            if index + 2 >= bytes.len() {
                return None;
            }

            let hi = decode_hex_nibble(bytes[index + 1])?;
            let lo = decode_hex_nibble(bytes[index + 2])?;
            decoded.push((hi << 4) | lo);
            index += 3;
            continue;
        }

        decoded.push(bytes[index]);
        index += 1;
    }

    String::from_utf8(decoded).ok()
}

fn decode_hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

fn parse_bulk_data_uri(uri: &str) -> Result<(usize, usize), DicomJsonError> {
    let query = uri
        .split_once('?')
        .map(|(_, query)| query)
        .unwrap_or_else(|| uri.trim_start_matches('?'));

    let mut offset = None;
    let mut length = None;

    for part in query.split('&') {
        let Some((key, value)) = part.split_once('=') else {
            continue;
        };

        match key {
            "offset" => offset = value.parse::<usize>().ok(),
            "length" => length = value.parse::<usize>().ok(),
            _ => {}
        }
    }

    match (offset, length) {
        (Some(offset), Some(length)) => Ok((offset, length)),
        _ => Err(DicomJsonError::InvalidBulkDataUri(uri.to_owned())),
    }
}

// Upper bound on how many elements/items a single scan attempt (locate_tag_in_dataset,
// skip_undefined_length_value, and locate_element_value_by_matching_bytes each get their own
// fresh budget) will walk before giving up. A well-formed DICOM dataset - even a large one with
// thousands of per-frame functional-group items - stays well under this; it exists purely to
// bound the worst case when the scan has desynced (e.g. into high-entropy compressed pixel data,
// where nearly any 2 bytes can look like a plausible tag) and would otherwise treat a multi-MB
// remaining byte range as an unbounded number of tiny fake elements before finally hitting EOF -
// observed taking upwards of 15-20 SECONDS for a single ~500KB file before this cap existed.
const MAX_SCAN_STEPS: usize = 20_000;

fn take_scan_step(steps: &mut usize) -> Result<(), DicomJsonError> {
    if *steps == 0 {
        return Err(DicomJsonError::InvalidBulkDataUri(
            "scan exceeded maximum step budget".to_owned(),
        ));
    }
    *steps -= 1;
    Ok(())
}

// The byte-content fallback search (locate_element_value_by_matching_bytes) has a fundamentally
// different cost shape than the tag-walking scan above: each outer-loop iteration calls
// find_subslice, whose own cost is proportional to how much of the remaining buffer it has to
// examine (up to the whole thing), not to a fixed per-iteration step. So it gets its own, much
// smaller attempt budget, plus a cap on the needle size: an element big enough to matter here
// should already have been found by the direct tag scan, and matching a large needle by content
// against a large haystack (e.g. long zero-padding runs, common in private/CSA blobs) is exactly
// the shape that made a single scan attempt take upwards of 10+ seconds before this cap existed.
const MAX_MATCH_NEEDLE_LEN: usize = 64 * 1024;
const MAX_MATCH_SCAN_ATTEMPTS: usize = 2_000;

/// `value_width`: the size of one number in `expected_bytes` (see [`primitive_value_width`]), for
/// comparing them with a big-endian file's bytes.
fn locate_element_value(
    source: &[u8],
    target: Tag,
    expected_bytes: Option<&[u8]>,
    value_width: usize,
    resume_hint: usize,
) -> Result<Option<ElementLocation>, DicomJsonError> {
    let has_part10_preamble = source.len() >= 132 && &source[128..132] == b"DICM";

    let mut position = if has_part10_preamble { 132 } else { 0 };
    let mut transfer_syntax_uid = if has_part10_preamble {
        uids::EXPLICIT_VR_LITTLE_ENDIAN.to_owned()
    } else {
        uids::IMPLICIT_VR_LITTLE_ENDIAN.to_owned()
    };

    if has_part10_preamble {
        let mut meta_steps = MAX_SCAN_STEPS;
        while position + 8 <= source.len() {
            take_scan_step(&mut meta_steps)?;
            let header = parse_element_header(source, position, true, true)?;
            if header.tag.group() != 0x0002 {
                break;
            }

            let value_offset = position + header.header_length;
            let Some(value_length) = header.length else {
                return Err(DicomJsonError::InvalidBulkDataUri(
                    "file meta group contains undefined-length element".to_owned(),
                ));
            };

            if header.tag == target
                && value_matches(source, value_offset, value_length, expected_bytes)
            {
                return Ok(Some(ElementLocation {
                    offset: value_offset,
                    length: value_length,
                }));
            }

            if header.tag == tags::TRANSFER_SYNTAX_UID {
                transfer_syntax_uid =
                    decode_dicom_text(&source[value_offset..value_offset + value_length]);
            }

            position = value_offset + value_length;
        }
    }

    let syntax = transfer_syntax_from_uid(transfer_syntax_uid.as_str())?;
    // expected_bytes are decoded (little-endian), so in a big-endian data set the value's bytes
    // in the file are those with each number reversed. Only the data set: the meta group above
    // is little-endian in every transfer syntax.
    let big_endian_expected = expected_bytes
        .filter(|_| !syntax.little_endian && value_width > 1)
        .map(|expected| reverse_each_value(expected, value_width));
    let expected_bytes = big_endian_expected.as_deref().or(expected_bytes);
    let dataset_start = position;
    let scan_from = resume_hint.max(dataset_start);

    if scan_from > dataset_start {
        let mut steps = MAX_SCAN_STEPS;
        if let Some(location) = locate_tag_in_dataset(
            source,
            scan_from,
            target,
            syntax.explicit_vr,
            syntax.little_endian,
            expected_bytes,
            &mut steps,
        )? {
            return Ok(Some(location));
        }
        // Not found from the hint onward - retry once from the true dataset start, in case this
        // particular tag actually precedes the hint (an out-of-order visit relative to file
        // layout). This keeps the hint a pure speed optimization, never a correctness risk.
    }

    let mut steps = MAX_SCAN_STEPS;
    if let Some(location) = locate_tag_in_dataset(
        source,
        dataset_start,
        target,
        syntax.explicit_vr,
        syntax.little_endian,
        expected_bytes,
        &mut steps,
    )? {
        return Ok(Some(location));
    }

    // Not a top-level element - walk into sequence items. Only reached after the top-level scan
    // misses, so top-level lookups (PixelData etc.) never pay for descending into large
    // sequences such as per-frame functional groups. Errors (e.g. an exhausted step budget on a
    // construct the scanner doesn't model) just mean "not found here": the byte-content fallback
    // below still gets its chance, exactly as before this pass existed.
    let mut steps = MAX_SCAN_STEPS;
    if let Ok(Some(location)) = locate_tag_in_nested_dataset(
        source,
        dataset_start,
        source.len(),
        target,
        syntax.explicit_vr,
        syntax.little_endian,
        expected_bytes,
        &mut steps,
        0,
    ) {
        return Ok(Some(location));
    }

    if let Some(expected) = expected_bytes {
        return locate_element_value_by_matching_bytes(
            source,
            target,
            expected,
            syntax.explicit_vr,
            syntax.little_endian,
        );
    }

    Ok(None)
}

fn locate_tag_in_dataset(
    source: &[u8],
    mut position: usize,
    target: Tag,
    explicit_vr: bool,
    little_endian: bool,
    expected_bytes: Option<&[u8]>,
    steps: &mut usize,
) -> Result<Option<ElementLocation>, DicomJsonError> {
    while position + 8 <= source.len() {
        take_scan_step(steps)?;
        let header = parse_element_header(source, position, explicit_vr, little_endian)?;
        let value_offset = position + header.header_length;
        // Undefined-length values are scanned ONCE (not once for the length, then again for the
        // next position) - both are derived from the same skip_undefined_length_value call.
        let (length, next_position) = if let Some(length) = header.length {
            (length, value_offset + length)
        } else {
            let end_position = skip_undefined_length_value(
                source,
                value_offset,
                explicit_vr,
                little_endian,
                steps,
            )?;
            (end_position.saturating_sub(value_offset), end_position + 8)
        };

        if header.tag == target && value_matches(source, value_offset, length, expected_bytes) {
            return Ok(Some(ElementLocation {
                offset: value_offset,
                length,
            }));
        }

        position = next_position;
    }

    Ok(None)
}

const MAX_NESTED_SCAN_DEPTH: usize = 16;

/// Like `locate_tag_in_dataset`, but bounded to `[position, end)` and descending into the items
/// of every sequence it passes, so it can find elements nested at any depth (e.g. ICCProfile
/// inside OpticalPathSequence). Without this, a nested bulk value was only findable by the
/// byte-content fallback, which caps its needle at `MAX_MATCH_NEEDLE_LEN` - so a large nested
/// value (a whole-slide image's ~140 KB ICC profile) silently degraded to InlineBinary.
#[allow(clippy::too_many_arguments)]
fn locate_tag_in_nested_dataset(
    source: &[u8],
    mut position: usize,
    end: usize,
    target: Tag,
    explicit_vr: bool,
    little_endian: bool,
    expected_bytes: Option<&[u8]>,
    steps: &mut usize,
    depth: usize,
) -> Result<Option<ElementLocation>, DicomJsonError> {
    let end = end.min(source.len());
    while position + 8 <= end {
        take_scan_step(steps)?;
        let tag = read_tag(source, position, little_endian)?;
        if tag == ITEM_DELIMITATION_TAG || tag == SEQUENCE_DELIMITATION_TAG {
            return Ok(None);
        }

        let header = parse_element_header(source, position, explicit_vr, little_endian)?;
        let value_offset = position + header.header_length;
        let (length, next_position) = if let Some(length) = header.length {
            (length, value_offset + length)
        } else {
            let end_position = skip_undefined_length_value(
                source,
                value_offset,
                explicit_vr,
                little_endian,
                steps,
            )?;
            (end_position.saturating_sub(value_offset), end_position + 8)
        };

        if header.tag == target && value_matches(source, value_offset, length, expected_bytes) {
            return Ok(Some(ElementLocation {
                offset: value_offset,
                length,
            }));
        }

        if depth < MAX_NESTED_SCAN_DEPTH
            && is_sequence_value(
                source,
                position,
                header.tag,
                value_offset,
                explicit_vr,
                little_endian,
            )
        {
            if let Some(location) = locate_tag_in_sequence_items(
                source,
                value_offset,
                value_offset + length,
                target,
                explicit_vr,
                little_endian,
                expected_bytes,
                steps,
                depth + 1,
            )? {
                return Ok(Some(location));
            }
        }

        position = next_position;
    }

    Ok(None)
}

/// Whether the element whose header starts at `position` holds a sequence of items. Explicit VR
/// says so directly; implicit VR has no VR on the wire, so a value that opens with an Item tag is
/// taken as a sequence. Encapsulated PixelData is item-structured too but holds fragments, not
/// datasets, so it is excluded. Undefined-length explicit-VR UN values (whose nested content is
/// implicit VR, PS3.5 6.2.2) are not descended into - this scanner doesn't model the switch.
fn is_sequence_value(
    source: &[u8],
    position: usize,
    tag: Tag,
    value_offset: usize,
    explicit_vr: bool,
    little_endian: bool,
) -> bool {
    if tag == tags::PIXEL_DATA {
        return false;
    }
    if explicit_vr {
        source.get(position + 4..position + 6) == Some(b"SQ".as_slice())
    } else {
        matches!(read_tag(source, value_offset, little_endian), Ok(t) if t == ITEM_TAG)
    }
}

#[allow(clippy::too_many_arguments)]
fn locate_tag_in_sequence_items(
    source: &[u8],
    mut position: usize,
    end: usize,
    target: Tag,
    explicit_vr: bool,
    little_endian: bool,
    expected_bytes: Option<&[u8]>,
    steps: &mut usize,
    depth: usize,
) -> Result<Option<ElementLocation>, DicomJsonError> {
    let end = end.min(source.len());
    while position + 8 <= end {
        take_scan_step(steps)?;
        if read_tag(source, position, little_endian)? != ITEM_TAG {
            break;
        }
        let item_length = read_u32(source, position + 4, little_endian)?;
        let item_start = position + 8;
        let (item_end, next_position) = if item_length == u32::MAX {
            let item_end =
                skip_undefined_length_value(source, item_start, explicit_vr, little_endian, steps)?;
            (item_end, item_end + 8)
        } else {
            let item_end = item_start + item_length as usize;
            (item_end, item_end)
        };

        if let Some(location) = locate_tag_in_nested_dataset(
            source,
            item_start,
            item_end,
            target,
            explicit_vr,
            little_endian,
            expected_bytes,
            steps,
            depth,
        )? {
            return Ok(Some(location));
        }

        position = next_position;
    }

    Ok(None)
}

fn locate_element_value_by_matching_bytes(
    source: &[u8],
    target: Tag,
    expected: &[u8],
    explicit_vr: bool,
    little_endian: bool,
) -> Result<Option<ElementLocation>, DicomJsonError> {
    if expected.is_empty() || expected.len() > MAX_MATCH_NEEDLE_LEN {
        return Ok(None);
    }

    let mut search_start = 0;
    let mut attempts = MAX_MATCH_SCAN_ATTEMPTS;
    let mut steps = MAX_SCAN_STEPS;
    while search_start + expected.len() <= source.len() {
        take_scan_step(&mut attempts)?;
        let Some(relative_match) = find_subslice(&source[search_start..], expected) else {
            break;
        };
        let value_offset = search_start + relative_match;

        if let Some(location) = try_locate_header_for_value_offset(
            source,
            target,
            value_offset,
            expected.len(),
            explicit_vr,
            little_endian,
            &mut steps,
        )? {
            return Ok(Some(location));
        }

        search_start = value_offset + 1;
    }

    Ok(None)
}

fn try_locate_header_for_value_offset(
    source: &[u8],
    target: Tag,
    value_offset: usize,
    expected_length: usize,
    explicit_vr: bool,
    little_endian: bool,
    steps: &mut usize,
) -> Result<Option<ElementLocation>, DicomJsonError> {
    let header_lengths: &[usize] = if explicit_vr { &[8, 12] } else { &[8] };

    for header_length in header_lengths {
        if value_offset < *header_length {
            continue;
        }

        let header_offset = value_offset - *header_length;
        let Ok(header) = parse_element_header(source, header_offset, explicit_vr, little_endian)
        else {
            continue;
        };

        if header.tag != target {
            continue;
        }

        if header_offset + header.header_length != value_offset {
            continue;
        }

        let length = if let Some(length) = header.length {
            length
        } else {
            skip_undefined_length_value(source, value_offset, explicit_vr, little_endian, steps)?
                .saturating_sub(value_offset)
        };

        if length == expected_length {
            return Ok(Some(ElementLocation {
                offset: value_offset,
                length,
            }));
        }
    }

    Ok(None)
}

fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || needle.len() > haystack.len() {
        return None;
    }

    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

/// The size in bytes of one number of a decoded value, i.e. what `PrimitiveValue::to_bytes` lays
/// out in little-endian order. 1 for anything a byte order doesn't apply to.
fn primitive_value_width<I, P>(value: &DicomValue<I, P>) -> usize {
    match value {
        DicomValue::Primitive(PrimitiveValue::U16(_) | PrimitiveValue::I16(_)) => 2,
        DicomValue::Primitive(
            PrimitiveValue::U32(_) | PrimitiveValue::I32(_) | PrimitiveValue::F32(_),
        ) => 4,
        DicomValue::Primitive(
            PrimitiveValue::U64(_) | PrimitiveValue::I64(_) | PrimitiveValue::F64(_),
        ) => 8,
        _ => 1,
    }
}

fn reverse_each_value(bytes: &[u8], width: usize) -> Vec<u8> {
    let mut reversed = bytes.to_vec();
    reversed.chunks_exact_mut(width).for_each(<[u8]>::reverse);
    reversed
}

fn value_matches(
    source: &[u8],
    value_offset: usize,
    value_length: usize,
    expected_bytes: Option<&[u8]>,
) -> bool {
    let Some(expected) = expected_bytes else {
        return true;
    };

    value_length == expected.len()
        && source
            .get(value_offset..value_offset + value_length)
            .map(|bytes| bytes == expected)
            .unwrap_or(false)
}

fn skip_undefined_length_value(
    source: &[u8],
    mut position: usize,
    explicit_vr: bool,
    little_endian: bool,
    steps: &mut usize,
) -> Result<usize, DicomJsonError> {
    while position + 8 <= source.len() {
        take_scan_step(steps)?;
        let tag = read_tag(source, position, little_endian)?;
        if tag == SEQUENCE_DELIMITATION_TAG || tag == ITEM_DELIMITATION_TAG {
            return Ok(position);
        }

        if tag == ITEM_TAG {
            let item_length = read_u32(source, position + 4, little_endian)? as usize;
            position += 8;
            position = if item_length == u32::MAX as usize {
                skip_undefined_length_value(source, position, explicit_vr, little_endian, steps)?
                    + 8
            } else {
                position + item_length
            };
            continue;
        }

        let header = parse_element_header(source, position, explicit_vr, little_endian)?;
        let value_offset = position + header.header_length;
        position = if let Some(length) = header.length {
            value_offset + length
        } else {
            skip_undefined_length_value(source, value_offset, explicit_vr, little_endian, steps)?
                + 8
        };
    }

    Err(DicomJsonError::InvalidBulkDataUri(
        "unterminated undefined-length value".to_owned(),
    ))
}

fn parse_element_header(
    source: &[u8],
    position: usize,
    explicit_vr: bool,
    little_endian: bool,
) -> Result<ParsedHeader, DicomJsonError> {
    let tag = read_tag(source, position, little_endian)?;

    if explicit_vr {
        if position + 8 > source.len() {
            return Err(DicomJsonError::InvalidBulkDataUri(
                "truncated explicit-VR element header".to_owned(),
            ));
        }

        let vr_bytes = [source[position + 4], source[position + 5]];
        let vr = VR::from_binary(vr_bytes).unwrap_or(VR::UN);
        if matches!(
            vr,
            VR::OB
                | VR::OD
                | VR::OF
                | VR::OL
                | VR::OV
                | VR::OW
                | VR::SQ
                | VR::UC
                | VR::UR
                | VR::UT
                | VR::UN
        ) {
            if position + 12 > source.len() {
                return Err(DicomJsonError::InvalidBulkDataUri(
                    "truncated extended explicit-VR element header".to_owned(),
                ));
            }

            let length = read_u32(source, position + 8, little_endian)?;
            Ok(ParsedHeader {
                tag,
                header_length: 12,
                length: if length == u32::MAX {
                    None
                } else {
                    Some(length as usize)
                },
            })
        } else {
            let length = read_u16(source, position + 6, little_endian)? as usize;
            Ok(ParsedHeader {
                tag,
                header_length: 8,
                length: Some(length),
            })
        }
    } else {
        if position + 8 > source.len() {
            return Err(DicomJsonError::InvalidBulkDataUri(
                "truncated implicit-VR element header".to_owned(),
            ));
        }

        let length = read_u32(source, position + 4, little_endian)?;
        Ok(ParsedHeader {
            tag,
            header_length: 8,
            length: if length == u32::MAX {
                None
            } else {
                Some(length as usize)
            },
        })
    }
}

fn read_tag(source: &[u8], position: usize, little_endian: bool) -> Result<Tag, DicomJsonError> {
    Ok(Tag(
        read_u16(source, position, little_endian)?,
        read_u16(source, position + 2, little_endian)?,
    ))
}

fn read_u16(source: &[u8], position: usize, little_endian: bool) -> Result<u16, DicomJsonError> {
    let bytes = source
        .get(position..position + 2)
        .ok_or_else(|| DicomJsonError::InvalidBulkDataUri("truncated 16-bit value".to_owned()))?;

    Ok(if little_endian {
        u16::from_le_bytes([bytes[0], bytes[1]])
    } else {
        u16::from_be_bytes([bytes[0], bytes[1]])
    })
}

fn read_u32(source: &[u8], position: usize, little_endian: bool) -> Result<u32, DicomJsonError> {
    let bytes = source
        .get(position..position + 4)
        .ok_or_else(|| DicomJsonError::InvalidBulkDataUri("truncated 32-bit value".to_owned()))?;

    Ok(if little_endian {
        u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
    } else {
        u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
    })
}

fn read_u16_le(source: &[u8], position: usize) -> Result<u16, DicomJsonError> {
    let bytes = source
        .get(position..position + 2)
        .ok_or_else(|| DicomJsonError::InvalidBulkDataUri("truncated 16-bit value".to_owned()))?;
    Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}

fn read_u32_le(source: &[u8], position: usize) -> Result<u32, DicomJsonError> {
    let bytes = source
        .get(position..position + 4)
        .ok_or_else(|| DicomJsonError::InvalidBulkDataUri("truncated 32-bit value".to_owned()))?;
    Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}

fn decode_dicom_text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes)
        .trim_matches(char::from(0))
        .trim_end()
        .to_owned()
}

/// Deliberately does NOT include Deflated Explicit VR Little Endian
/// (`1.2.840.10008.1.2.1.99`, `uids::DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN`): this file's whole
/// scanning approach walks `source` as literal DICOM element bytes at fixed offsets, but for a
/// deflated dataset those bytes (everything after the never-deflated file meta group) are
/// compressed - there is no file-byte-offset that identifies a decompressed element's value, so
/// `BulkDataURI`'s `?offset=..&length=..` addressing is fundamentally inapplicable here, not
/// just unimplemented. Falling through to the `Err` arm below is intentional: it makes
/// `locate_element_value` fail once per file (setting `bulk_scan_failed`, see
/// `bulk_representation`), after which every bulk element in the file inlines cheaply instead of
/// each independently scanning obviously-compressed bytes as if they were plain element headers.
fn transfer_syntax_from_uid(uid: &str) -> Result<TransferSyntaxInfo, DicomJsonError> {
    match uid {
        uids::IMPLICIT_VR_LITTLE_ENDIAN => Ok(TransferSyntaxInfo {
            explicit_vr: false,
            little_endian: true,
        }),
        uids::EXPLICIT_VR_LITTLE_ENDIAN
        | "1.2.840.10008.1.2.4.90"
        | "1.2.840.10008.1.2.4.91"
        | "1.2.840.10008.1.2.5" => Ok(TransferSyntaxInfo {
            explicit_vr: true,
            little_endian: true,
        }),
        "1.2.840.10008.1.2.2" => Ok(TransferSyntaxInfo {
            explicit_vr: true,
            little_endian: false,
        }),
        other if other.starts_with("1.2.840.10008.1.2.4.") => Ok(TransferSyntaxInfo {
            explicit_vr: true,
            little_endian: true,
        }),
        other => Err(DicomJsonError::UnsupportedTransferSyntax(other.to_owned())),
    }
}

fn is_little_endian_transfer_syntax(uid: &str) -> Result<bool, DicomJsonError> {
    Ok(transfer_syntax_from_uid(uid)?.little_endian)
}

fn is_encapsulated_transfer_syntax(uid: &str) -> bool {
    !matches!(
        uid,
        uids::IMPLICIT_VR_LITTLE_ENDIAN
            | uids::EXPLICIT_VR_LITTLE_ENDIAN
            | "1.2.840.10008.1.2.2"
            | "1.2.840.10008.1.2.1.99"
    )
}

fn pixel_sequence_from_bytes(
    bytes: &[u8],
) -> Result<DicomValue<dcmnorm_object::InMemDicomObject>, DicomJsonError> {
    let mut cursor = 0usize;
    let mut offset_table = Vec::new();
    let mut fragments = Vec::new();
    let mut first_item = true;

    while cursor + 8 <= bytes.len() {
        let tag = Tag(read_u16_le(bytes, cursor)?, read_u16_le(bytes, cursor + 2)?);
        let length = read_u32_le(bytes, cursor + 4)? as usize;
        cursor += 8;

        if tag == SEQUENCE_DELIMITATION_TAG {
            break;
        }

        if tag != ITEM_TAG {
            return Err(DicomJsonError::InvalidBulkDataUri(
                "encapsulated pixel data does not start with an item tag".to_owned(),
            ));
        }

        if cursor + length > bytes.len() {
            return Err(DicomJsonError::InvalidBulkDataUri(
                "encapsulated pixel data item exceeds available bytes".to_owned(),
            ));
        }

        let item_bytes = &bytes[cursor..cursor + length];
        if first_item {
            if !item_bytes.len().is_multiple_of(4) {
                return Err(DicomJsonError::InvalidBulkDataUri(
                    "basic offset table length is not divisible by 4".to_owned(),
                ));
            }

            for chunk in item_bytes.chunks_exact(4) {
                offset_table.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
            }
            first_item = false;
        } else {
            fragments.push(item_bytes.to_vec());
        }

        cursor += length;
    }

    Ok(DicomValue::<dcmnorm_object::InMemDicomObject>::from(
        PixelFragmentSequence::new(offset_table, fragments),
    ))
}

fn pixel_sequence_to_bytes<P>(pixel_sequence: &PixelFragmentSequence<P>) -> Vec<u8>
where
    P: AsRef<[u8]>,
{
    let mut bytes = Vec::new();
    let offset_table = pixel_sequence.offset_table();

    bytes.extend_from_slice(&ITEM_TAG.group().to_le_bytes());
    bytes.extend_from_slice(&ITEM_TAG.element().to_le_bytes());
    bytes.extend_from_slice(&((offset_table.len() * 4) as u32).to_le_bytes());
    for offset in offset_table {
        bytes.extend_from_slice(&offset.to_le_bytes());
    }

    for fragment in pixel_sequence.fragments() {
        bytes.extend_from_slice(&ITEM_TAG.group().to_le_bytes());
        bytes.extend_from_slice(&ITEM_TAG.element().to_le_bytes());
        bytes.extend_from_slice(&(fragment.as_ref().len() as u32).to_le_bytes());
        bytes.extend_from_slice(fragment.as_ref());
    }

    bytes.extend_from_slice(&SEQUENCE_DELIMITATION_TAG.group().to_le_bytes());
    bytes.extend_from_slice(&SEQUENCE_DELIMITATION_TAG.element().to_le_bytes());
    bytes.extend_from_slice(&0_u32.to_le_bytes());
    bytes
}

fn decode_u16_values(
    tag: Tag,
    vr: VR,
    bytes: &[u8],
    little_endian: bool,
) -> Result<Vec<u16>, DicomJsonError> {
    decode_fixed_width_values(bytes, 2, |chunk| {
        if little_endian {
            u16::from_le_bytes([chunk[0], chunk[1]])
        } else {
            u16::from_be_bytes([chunk[0], chunk[1]])
        }
    })
    .map_err(|_| DicomJsonError::InvalidBulkDataLength {
        tag,
        vr,
        length: bytes.len(),
    })
}

fn decode_u32_values(
    tag: Tag,
    vr: VR,
    bytes: &[u8],
    little_endian: bool,
) -> Result<Vec<u32>, DicomJsonError> {
    decode_fixed_width_values(bytes, 4, |chunk| {
        if little_endian {
            u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])
        } else {
            u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])
        }
    })
    .map_err(|_| DicomJsonError::InvalidBulkDataLength {
        tag,
        vr,
        length: bytes.len(),
    })
}

fn decode_u64_values(
    tag: Tag,
    vr: VR,
    bytes: &[u8],
    little_endian: bool,
) -> Result<Vec<u64>, DicomJsonError> {
    decode_fixed_width_values(bytes, 8, |chunk| {
        if little_endian {
            u64::from_le_bytes([
                chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
            ])
        } else {
            u64::from_be_bytes([
                chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
            ])
        }
    })
    .map_err(|_| DicomJsonError::InvalidBulkDataLength {
        tag,
        vr,
        length: bytes.len(),
    })
}

fn decode_f32_values(
    tag: Tag,
    vr: VR,
    bytes: &[u8],
    little_endian: bool,
) -> Result<Vec<f32>, DicomJsonError> {
    decode_fixed_width_values(bytes, 4, |chunk| {
        let bits = if little_endian {
            u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])
        } else {
            u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])
        };
        f32::from_bits(bits)
    })
    .map_err(|_| DicomJsonError::InvalidBulkDataLength {
        tag,
        vr,
        length: bytes.len(),
    })
}

fn decode_f64_values(
    tag: Tag,
    vr: VR,
    bytes: &[u8],
    little_endian: bool,
) -> Result<Vec<f64>, DicomJsonError> {
    decode_fixed_width_values(bytes, 8, |chunk| {
        let bits = if little_endian {
            u64::from_le_bytes([
                chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
            ])
        } else {
            u64::from_be_bytes([
                chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
            ])
        };
        f64::from_bits(bits)
    })
    .map_err(|_| DicomJsonError::InvalidBulkDataLength {
        tag,
        vr,
        length: bytes.len(),
    })
}

fn decode_fixed_width_values<T>(
    bytes: &[u8],
    width: usize,
    convert: impl Fn(&[u8]) -> T,
) -> Result<Vec<T>, ()> {
    if !bytes.len().is_multiple_of(width) {
        return Err(());
    }

    Ok(bytes.chunks_exact(width).map(convert).collect())
}