dcmnorm 0.23.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
use dcmnorm_core::header::EmptyObject;
use dcmnorm_core::value::Value as DicomValue;
use dcmnorm_core::{Length, PrimitiveValue, Tag, VR};
use dcmnorm_dictionary::tags;
use dcmnorm_object::{DefaultDicomObject, InMemDicomObject};
use serde_json::{Map as JsonMap, Number as JsonNumber, Value as JsonValue};

use super::bulk_data::{
    bulk_representation, is_bulk_value, primitive_is_bulk, raw_bytes_to_dicom_value,
    resolve_standard_bulk_bytes,
};
use super::common::{
    apply_meta_element, extract_transfer_syntax_from_standard, json_number_from_f32,
    json_number_from_f64, json_value_to_numbers, json_value_to_text, keyword_for_tag, tag_key,
};
use super::types::{
    BulkRepresentation, DicomJsonBulkDataMode, DicomJsonError, DicomJsonWriteOptions,
};

pub(super) fn write_standard_json_value(
    object: &DefaultDicomObject,
    options: DicomJsonWriteOptions<'_>,
) -> Result<JsonValue, DicomJsonError> {
    let mut json = JsonMap::new();

    for element in object.meta().to_element_iter() {
        if element.header().tag == tags::FILE_META_INFORMATION_GROUP_LENGTH {
            continue;
        }

        let value =
            write_standard_element(element.header().tag, element.vr(), element.value(), options)?;

        json.insert(
            tag_key(element.header().tag),
            if options.omit_keyword_vm {
                value
            } else {
                decorate_standard_element_json(
                    value,
                    element.header().tag,
                    standard_vm(element.header().tag, element.vr(), element.value()),
                )?
            },
        );
    }

    for element in object.iter() {
        let value =
            write_standard_element(element.header().tag, element.vr(), element.value(), options)?;

        json.insert(
            tag_key(element.header().tag),
            if options.omit_keyword_vm {
                value
            } else {
                decorate_standard_element_json(
                    value,
                    element.header().tag,
                    standard_vm(element.header().tag, element.vr(), element.value()),
                )?
            },
        );
    }

    Ok(JsonValue::Object(json))
}

pub(super) fn read_standard_json_value(
    value: &JsonValue,
    bulk_data_source: Option<&[u8]>,
) -> Result<DefaultDicomObject, DicomJsonError> {
    let JsonValue::Object(entries) = value else {
        return Err(DicomJsonError::InvalidJsonRoot);
    };

    let transfer_syntax_uid = extract_transfer_syntax_from_standard(entries)
        .unwrap_or_else(|| dcmnorm_dictionary::uids::EXPLICIT_VR_LITTLE_ENDIAN.to_owned());

    let mut dataset_elements = Vec::new();
    let mut meta_builder = dcmnorm_object::FileMetaTableBuilder::new();

    for (tag_text, element_json) in entries {
        let tag = tag_text
            .parse()
            .map_err(|_| DicomJsonError::InvalidStandardElement {
                tag: tag_text.clone(),
                message: "invalid tag key".to_owned(),
            })?;

        if tag == tags::FILE_META_INFORMATION_GROUP_LENGTH {
            continue;
        }

        let (vr, value) = read_standard_element(
            tag_text,
            tag,
            element_json,
            bulk_data_source,
            transfer_syntax_uid.as_str(),
        )?;
        let element = dcmnorm_core::DataElement::new(tag, vr, value);

        if tag.group() == 0x0002 {
            apply_meta_element(&mut meta_builder, &element)?;
        } else {
            dataset_elements.push(element);
        }
    }

    let dataset = InMemDicomObject::from_element_iter(dataset_elements);
    Ok(dataset.with_meta(meta_builder.transfer_syntax(transfer_syntax_uid))?)
}

/// Serializes a single element (top-level or nested inside a sequence item)
/// to its standard-JSON representation, recursing into `Value` for `SQ`.
/// Applying the same bulk-data handling at every nesting depth is what keeps
/// bulk data inside sequences consistent with top-level bulk data.
fn write_standard_element<I, P>(
    tag: Tag,
    vr: VR,
    value: &DicomValue<I, P>,
    options: DicomJsonWriteOptions<'_>,
) -> Result<JsonValue, DicomJsonError>
where
    I: StandardJsonItem,
    P: AsRef<[u8]>,
{
    let mut object = JsonMap::new();
    object.insert(
        "vr".to_owned(),
        JsonValue::String(vr.to_string().to_owned()),
    );

    match value {
        // PS3.18 F.2.5: a sequence with no items (zero length) has no "Value"; an empty item
        // is `{}` in a non-empty "Value"
        DicomValue::Sequence(sequence) if sequence.items().is_empty() => {}
        DicomValue::Sequence(sequence) => {
            let items = sequence
                .items()
                .iter()
                .enumerate()
                .map(|(index, item)| {
                    item.to_standard_json(options.for_sequence_item(tag, index))
                        .map(JsonValue::Object)
                })
                .collect::<Result<Vec<_>, DicomJsonError>>()?;
            object.insert("Value".to_owned(), JsonValue::Array(items));
        }
        DicomValue::PixelSequence(_) => {
            insert_bulk_representation(&mut object, tag, vr, value, options)?;
        }
        DicomValue::Primitive(PrimitiveValue::Empty) => {}
        DicomValue::Primitive(_) if primitive_is_bulk(vr) => {
            insert_bulk_representation(&mut object, tag, vr, value, options)?;
        }
        DicomValue::Primitive(primitive) => {
            object.insert(
                "Value".to_owned(),
                standard_primitive_to_json(vr, primitive),
            );
        }
    }

    Ok(JsonValue::Object(object))
}

/// `WaveformData` is conventionally always inlined rather than referenced by
/// `BulkDataURI`, matching the read side's [`super::bulk_data::is_bulk_value`]
/// exclusion; every other bulk VR is eligible for a URI in URI mode.
fn insert_bulk_representation<I, P>(
    object: &mut JsonMap<String, JsonValue>,
    tag: Tag,
    vr: VR,
    value: &DicomValue<I, P>,
    options: DicomJsonWriteOptions<'_>,
) -> Result<(), DicomJsonError>
where
    P: AsRef<[u8]>,
{
    let effective_options = if tag == tags::WAVEFORM_DATA {
        DicomJsonWriteOptions {
            bulk_data_mode: DicomJsonBulkDataMode::InlineBinary,
            ..options
        }
    } else {
        options
    };

    match bulk_representation(tag, vr, value, effective_options)? {
        BulkRepresentation::Uri(uri) => {
            object.insert("BulkDataURI".to_owned(), JsonValue::String(uri));
        }
        BulkRepresentation::InlineBinary(encoded) => {
            object.insert("InlineBinary".to_owned(), JsonValue::String(encoded));
        }
    }

    Ok(())
}

fn decorate_standard_element_json(
    value: JsonValue,
    tag: Tag,
    multiplicity: u32,
) -> Result<JsonValue, DicomJsonError> {
    let JsonValue::Object(mut object) = value else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_key(tag),
            message: "expected an object value".to_owned(),
        });
    };

    object.insert(
        "Keyword".to_owned(),
        JsonValue::String(keyword_for_tag(tag)),
    );
    object.insert(
        "VM".to_owned(),
        JsonValue::Number(JsonNumber::from(multiplicity)),
    );
    Ok(JsonValue::Object(object))
}

/// Per PS3.18 Annex F, PN is an array of `{"Alphabetic": ..., "Ideographic":
/// ..., "Phonetic": ...}` objects and numeric VRs prefer JSON numbers (with
/// "NaN"/"inf"/"-inf" string tokens for non-finite floats); everything else
/// is a plain string array.
///
/// An empty component of a multi-valued attribute (`one\\three`) is `null` (PS3.18 F.2.5), and
/// an AT value is the referenced tag as eight uppercase hex digits, `"00181063"` (F.2.3).
fn standard_primitive_to_json(vr: VR, primitive: &PrimitiveValue) -> JsonValue {
    match vr {
        VR::PN => JsonValue::Array(
            primitive
                .to_multi_str()
                .iter()
                .map(|name| {
                    if name.is_empty() {
                        JsonValue::Null
                    } else {
                        person_name_to_json(name)
                    }
                })
                .collect(),
        ),
        VR::AT => match primitive {
            PrimitiveValue::Tags(tags) => JsonValue::Array(
                tags.iter()
                    .map(|tag| {
                        JsonValue::String(format!("{:04X}{:04X}", tag.group(), tag.element()))
                    })
                    .collect(),
            ),
            // an AT read as raw integers: each pair of 16-bit words is (group, element)
            PrimitiveValue::U16(words) => JsonValue::Array(
                words
                    .chunks_exact(2)
                    .map(|pair| JsonValue::String(format!("{:04X}{:04X}", pair[0], pair[1])))
                    .collect(),
            ),
            PrimitiveValue::U32(values) => JsonValue::Array(
                values
                    .iter()
                    .map(|v| JsonValue::String(format!("{v:08X}")))
                    .collect(),
            ),
            other => text_values_json(other),
        },
        VR::FD | VR::IS | VR::FL | VR::DS | VR::SL | VR::SS | VR::SV | VR::UL | VR::US | VR::UV => {
            standard_numbers_json(primitive)
        }
        _ => text_values_json(primitive),
    }
}

/// A string array, with `null` for each empty component (PS3.18 F.2.5).
fn text_values_json(primitive: &PrimitiveValue) -> JsonValue {
    JsonValue::Array(
        primitive
            .to_multi_str()
            .iter()
            .map(|text| text_or_null(text))
            .collect(),
    )
}

fn text_or_null(text: &str) -> JsonValue {
    if text.is_empty() {
        JsonValue::Null
    } else {
        JsonValue::String(text.to_owned())
    }
}

fn person_name_to_json(raw: &str) -> JsonValue {
    let mut parts = raw.splitn(3, '=');
    let mut object = JsonMap::new();

    if let Some(alphabetic) = parts.next() {
        if !alphabetic.is_empty() {
            object.insert(
                "Alphabetic".to_owned(),
                JsonValue::String(alphabetic.to_owned()),
            );
        }
    }
    if let Some(ideographic) = parts.next() {
        if !ideographic.is_empty() {
            object.insert(
                "Ideographic".to_owned(),
                JsonValue::String(ideographic.to_owned()),
            );
        }
    }
    if let Some(phonetic) = parts.next() {
        if !phonetic.is_empty() {
            object.insert(
                "Phonetic".to_owned(),
                JsonValue::String(phonetic.to_owned()),
            );
        }
    }

    JsonValue::Object(object)
}

/// Mirrors the actual stored [`PrimitiveValue`] variant (not just the VR),
/// since values read from a file often keep DS/IS as text (`Strs`) while
/// values built programmatically may already be typed numbers.
fn standard_numbers_json(primitive: &PrimitiveValue) -> JsonValue {
    match primitive {
        PrimitiveValue::Empty => JsonValue::Array(Vec::new()),
        PrimitiveValue::Str(text) => JsonValue::Array(vec![text_or_null(text.trim())]),
        PrimitiveValue::Strs(strings) => JsonValue::Array(
            strings
                .iter()
                .map(|text| text_or_null(text.trim()))
                .collect(),
        ),
        PrimitiveValue::U8(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| JsonValue::Number((*v).into()))
                .collect(),
        ),
        PrimitiveValue::I16(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| JsonValue::Number(JsonNumber::from(*v)))
                .collect(),
        ),
        PrimitiveValue::U16(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| JsonValue::Number((*v).into()))
                .collect(),
        ),
        PrimitiveValue::I32(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| JsonValue::Number(JsonNumber::from(*v)))
                .collect(),
        ),
        PrimitiveValue::U32(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| JsonValue::Number((*v).into()))
                .collect(),
        ),
        PrimitiveValue::I64(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| match i32::try_from(*v) {
                    Ok(narrowed) => JsonValue::Number(JsonNumber::from(narrowed)),
                    Err(_) => JsonValue::String(v.to_string()),
                })
                .collect(),
        ),
        PrimitiveValue::U64(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| match i32::try_from(*v) {
                    Ok(narrowed) => JsonValue::Number(JsonNumber::from(narrowed)),
                    Err(_) => JsonValue::String(v.to_string()),
                })
                .collect(),
        ),
        PrimitiveValue::F32(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| match json_number_from_f32(*v) {
                    Some(number) => number,
                    None if v.is_nan() => JsonValue::String("NaN".to_owned()),
                    None if v.is_sign_positive() => JsonValue::String("inf".to_owned()),
                    None => JsonValue::String("-inf".to_owned()),
                })
                .collect(),
        ),
        PrimitiveValue::F64(values) => JsonValue::Array(
            values
                .iter()
                .map(|v| match json_number_from_f64(*v) {
                    Some(number) => number,
                    None if v.is_nan() => JsonValue::String("NaN".to_owned()),
                    None if v.is_sign_positive() => JsonValue::String("inf".to_owned()),
                    None => JsonValue::String("-inf".to_owned()),
                })
                .collect(),
        ),
        _ => JsonValue::Array(Vec::new()),
    }
}

/// Mirror of [`write_standard_element`] for reading: recurses into `Value`
/// for `SQ` and requires `InlineBinary`/`BulkDataURI` for bulk VRs at every
/// nesting depth, so a sequence-nested bulk element round-trips the same way
/// a top-level one does.
fn read_standard_element(
    tag_text: &str,
    tag: Tag,
    element_json: &JsonValue,
    bulk_data_source: Option<&[u8]>,
    transfer_syntax_uid: &str,
) -> Result<(VR, DicomValue<InMemDicomObject>), DicomJsonError> {
    let cleaned = clean_standard_element_json(tag_text, element_json)?;
    let vr = standard_element_vr(tag_text, &cleaned)?;

    let JsonValue::Object(object) = &cleaned else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "expected an object".to_owned(),
        });
    };

    if vr == VR::SQ {
        let items = match object.get("Value") {
            Some(JsonValue::Array(items)) => items.as_slice(),
            None | Some(JsonValue::Null) => &[],
            _ => {
                return Err(DicomJsonError::InvalidStandardElement {
                    tag: tag_text.to_owned(),
                    message: "expected an array of sequence items".to_owned(),
                })
            }
        };

        let mut sequence_items = Vec::with_capacity(items.len());
        for item in items {
            let JsonValue::Object(item_object) = item else {
                return Err(DicomJsonError::InvalidStandardElement {
                    tag: tag_text.to_owned(),
                    message: "expected each sequence item to be a JSON object".to_owned(),
                });
            };

            sequence_items.push(read_standard_dataset_object(
                item_object,
                bulk_data_source,
                transfer_syntax_uid,
            )?);
        }

        return Ok((
            VR::SQ,
            DicomValue::new_sequence(sequence_items, Length::UNDEFINED),
        ));
    }

    if primitive_is_bulk(vr) {
        return match resolve_standard_bulk_bytes(tag, vr, object, bulk_data_source)? {
            Some(bytes) => Ok((
                vr,
                raw_bytes_to_dicom_value(
                    tag,
                    vr,
                    &bytes,
                    transfer_syntax_uid,
                    object.contains_key("InlineBinary"),
                )?,
            )),
            None => Err(DicomJsonError::InvalidStandardElement {
                tag: tag_text.to_owned(),
                message: "bulk data requires InlineBinary or BulkDataURI".to_owned(),
            }),
        };
    }

    let value_json = object.get("Value").cloned().unwrap_or(JsonValue::Null);
    let primitive = standard_json_to_primitive(tag_text, vr, &value_json)?;
    Ok((vr, primitive.into()))
}

fn read_standard_dataset_object(
    object: &JsonMap<String, JsonValue>,
    bulk_data_source: Option<&[u8]>,
    transfer_syntax_uid: &str,
) -> Result<InMemDicomObject, DicomJsonError> {
    let mut elements = Vec::with_capacity(object.len());

    for (tag_text, element_json) in object {
        let tag = tag_text
            .parse()
            .map_err(|_| DicomJsonError::InvalidStandardElement {
                tag: tag_text.clone(),
                message: "invalid tag key".to_owned(),
            })?;

        let (vr, value) = read_standard_element(
            tag_text,
            tag,
            element_json,
            bulk_data_source,
            transfer_syntax_uid,
        )?;
        elements.push(dcmnorm_core::DataElement::new(tag, vr, value));
    }

    Ok(InMemDicomObject::from_element_iter(elements))
}

fn clean_standard_element_json(
    tag_text: &str,
    element_json: &JsonValue,
) -> Result<JsonValue, DicomJsonError> {
    let JsonValue::Object(object) = element_json else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "expected an object".to_owned(),
        });
    };

    let mut cleaned = object.clone();
    cleaned.remove("Keyword");
    cleaned.remove("keyword");
    cleaned.remove("VM");
    cleaned.remove("vm");
    Ok(JsonValue::Object(cleaned))
}

fn standard_element_vr(tag_text: &str, element_json: &JsonValue) -> Result<VR, DicomJsonError> {
    let JsonValue::Object(object) = element_json else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "expected an object".to_owned(),
        });
    };

    let Some(JsonValue::String(vr)) = object.get("vr") else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "missing vr field".to_owned(),
        });
    };

    vr.parse()
        .map_err(|_| DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: format!("invalid VR {vr}"),
        })
}

fn standard_json_to_primitive(
    tag_text: &str,
    vr: VR,
    value: &JsonValue,
) -> Result<PrimitiveValue, DicomJsonError> {
    if value.is_null() {
        return Ok(PrimitiveValue::Empty);
    }

    if vr == VR::AT {
        return Ok(PrimitiveValue::Tags(
            standard_json_to_tags(tag_text, value)?.into(),
        ));
    }

    match vr {
        VR::SS => {
            return Ok(PrimitiveValue::I16(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::US => {
            return Ok(PrimitiveValue::U16(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::SL => {
            return Ok(PrimitiveValue::I32(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::UL => {
            return Ok(PrimitiveValue::U32(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::SV => {
            return Ok(PrimitiveValue::I64(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::UV => {
            return Ok(PrimitiveValue::U64(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::FL => {
            return Ok(PrimitiveValue::F32(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        VR::FD => {
            return Ok(PrimitiveValue::F64(
                json_value_to_numbers(tag_text, value)?.into(),
            ))
        }
        _ => {}
    }

    let JsonValue::Array(items) = value else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "expected \"Value\" to be a JSON array".to_owned(),
        });
    };

    if items.is_empty() {
        return Ok(PrimitiveValue::Empty);
    }

    // a `null` item is an empty component (PS3.18 F.2.5)
    if vr == VR::PN {
        let names = items
            .iter()
            .map(|item| match item {
                JsonValue::Null => Ok(String::new()),
                item => standard_json_to_person_name(tag_text, item),
            })
            .collect::<Result<Vec<_>, _>>()?;
        return Ok(PrimitiveValue::Strs(names.into()));
    }

    let strings = items
        .iter()
        .map(|item| match item {
            JsonValue::Null => Ok(String::new()),
            item => json_value_to_text(tag_text, item),
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok(PrimitiveValue::Strs(strings.into()))
}

fn standard_json_to_person_name(
    tag_text: &str,
    item: &JsonValue,
) -> Result<String, DicomJsonError> {
    let JsonValue::Object(object) = item else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "expected a person name object".to_owned(),
        });
    };

    let alphabetic = match object.get("Alphabetic") {
        Some(JsonValue::String(text)) => text.as_str(),
        _ => "",
    };
    let ideographic = match object.get("Ideographic") {
        Some(JsonValue::String(text)) => Some(text.as_str()),
        _ => None,
    };
    let phonetic = match object.get("Phonetic") {
        Some(JsonValue::String(text)) => Some(text.as_str()),
        _ => None,
    };

    Ok(match (ideographic, phonetic) {
        (None, None) => alphabetic.to_owned(),
        (Some(ideographic), None) => format!("{alphabetic}={ideographic}"),
        (None, Some(phonetic)) => format!("{alphabetic}=={phonetic}"),
        (Some(ideographic), Some(phonetic)) => {
            format!("{alphabetic}={ideographic}={phonetic}")
        }
    })
}

fn standard_json_to_tags(tag_text: &str, value: &JsonValue) -> Result<Vec<Tag>, DicomJsonError> {
    let JsonValue::Array(items) = value else {
        return Err(DicomJsonError::InvalidStandardElement {
            tag: tag_text.to_owned(),
            message: "expected \"Value\" to be a JSON array".to_owned(),
        });
    };

    items
        .iter()
        .map(|item| {
            let JsonValue::String(text) = item else {
                return Err(DicomJsonError::InvalidStandardElement {
                    tag: tag_text.to_owned(),
                    message: "expected a hexadecimal tag string".to_owned(),
                });
            };
            text.parse()
                .map_err(|_| DicomJsonError::InvalidStandardElement {
                    tag: tag_text.to_owned(),
                    message: format!("invalid tag reference: {text}"),
                })
        })
        .collect()
}

fn standard_vm<I, P>(tag: Tag, vr: VR, value: &DicomValue<I, P>) -> u32 {
    if is_bulk_value(tag, vr, value) {
        match value {
            DicomValue::Primitive(PrimitiveValue::Empty) => 0,
            _ => 1,
        }
    } else {
        value.multiplicity()
    }
}

trait StandardJsonItem {
    fn to_standard_json(
        &self,
        options: DicomJsonWriteOptions<'_>,
    ) -> Result<JsonMap<String, JsonValue>, DicomJsonError>;
}

impl StandardJsonItem for InMemDicomObject {
    fn to_standard_json(
        &self,
        options: DicomJsonWriteOptions<'_>,
    ) -> Result<JsonMap<String, JsonValue>, DicomJsonError> {
        let mut object = JsonMap::new();

        for element in self.iter() {
            let value = write_standard_element(
                element.header().tag,
                element.vr(),
                element.value(),
                options,
            )?;
            object.insert(tag_key(element.header().tag), value);
        }

        Ok(object)
    }
}

impl StandardJsonItem for EmptyObject {
    fn to_standard_json(
        &self,
        _options: DicomJsonWriteOptions<'_>,
    ) -> Result<JsonMap<String, JsonValue>, DicomJsonError> {
        Ok(JsonMap::new())
    }
}