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
//! DICOM JSON deserialization module

use std::{marker::PhantomData, str::FromStr};

use crate::DicomJson;
use dicom_core::{
    value::{InMemFragment, Value, C},
    DataDictionary, DataElement, PrimitiveValue, Tag, VR,
};
use dicom_object::InMemDicomObject;
use serde::de::{Deserialize, DeserializeOwned, Error as _, Visitor};

use self::value::{DicomJsonPerson, NumberOrText};

mod value;

/// Deserialize a piece of DICOM data from a string of JSON.
pub fn from_str<'a, T>(string: &'a str) -> Result<T, serde_json::Error>
where
    DicomJson<T>: Deserialize<'a>,
{
    serde_json::from_str::<DicomJson<T>>(string).map(DicomJson::into_inner)
}

/// Deserialize a piece of DICOM data from a byte slice.
pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T, serde_json::Error>
where
    DicomJson<T>: Deserialize<'a>,
{
    serde_json::from_slice::<DicomJson<T>>(slice).map(DicomJson::into_inner)
}

/// Deserialize a piece of DICOM data from a standard byte reader.
pub fn from_reader<R, T>(reader: R) -> Result<T, serde_json::Error>
where
    R: std::io::Read,
    DicomJson<T>: DeserializeOwned,
{
    serde_json::from_reader::<_, DicomJson<T>>(reader).map(DicomJson::into_inner)
}

/// Deserialize a piece of DICOM data from a serde JSON value.
pub fn from_value<T>(value: serde_json::Value) -> Result<T, serde_json::Error>
where
    DicomJson<T>: DeserializeOwned,
{
    serde_json::from_value::<DicomJson<T>>(value).map(DicomJson::into_inner)
}

#[derive(Debug)]
struct InMemDicomObjectVisitor<D>(PhantomData<D>);

impl<D> Default for InMemDicomObjectVisitor<D> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<'de, D> Visitor<'de> for InMemDicomObjectVisitor<D>
where
    D: Default + DataDictionary + Clone,
{
    type Value = InMemDicomObject<D>;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a DICOM data set map")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let mut obj = InMemDicomObject::<D>::new_empty_with_dict(D::default());
        while let Some(e) = map.next_entry::<DicomJson<Tag>, JsonDataElement<D>>()? {
            let (DicomJson(tag), JsonDataElement { vr, value }) = e;
            obj.put(DataElement::new(tag, vr, value));
        }
        Ok(obj)
    }
}

impl<'de, I> Deserialize<'de> for DicomJson<InMemDicomObject<I>>
where
    I: Default + Clone + DataDictionary,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer
            .deserialize_map(InMemDicomObjectVisitor::default())
            .map(DicomJson::from)
            .map_err(From::from)
    }
}

#[derive(Debug)]
struct JsonDataElement<D> {
    vr: VR,
    value: Value<InMemDicomObject<D>, InMemFragment>,
}

#[derive(Debug)]
struct DataElementVisitor<D>(PhantomData<D>);

impl<D> Default for DataElementVisitor<D> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<'de, D> Visitor<'de> for DataElementVisitor<D>
where
    D: Default + Clone + DataDictionary,
{
    type Value = JsonDataElement<D>;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a data element object")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let mut values: Option<_> = None;
        let mut inline_binary = None;

        // first field should be "vr"
        let key: String = map
            .next_key()?
            .ok_or_else(|| A::Error::custom("\"vr\" is not set"))?;

        if key != "vr" {
            eprintln!("First field is \"{}\" instead of \"vr\"", key);
            return Err(A::Error::custom("expected \"vr\" to be the first field"));
        }

        // read VR
        let val: String = map.next_value()?;
        let vr = VR::from_str(&val).unwrap_or(
            // unrecognized VR
            VR::UN,
        );

        while let Some(key) = map.next_key::<String>()? {
            match &*key {
                "vr" => {
                    return Err(A::Error::custom("\"vr\" should only be set once"));
                }
                "Value" => {
                    if inline_binary.is_some() {
                        return Err(A::Error::custom(
                            "\"Value\" conflicts with \"InlineBinary\"",
                        ));
                    }

                    // deserialize value in different ways
                    // depending on VR
                    match vr {
                        // sequence
                        VR::SQ => {
                            let items: Vec<DicomJson<InMemDicomObject<D>>> = map.next_value()?;
                            let items: Vec<_> =
                                items.into_iter().map(DicomJson::into_inner).collect();
                            values = Some(Value::Sequence(items.into()));
                        }
                        // always text
                        VR::AE
                        | VR::AS
                        | VR::CS
                        | VR::DA
                        | VR::DT
                        | VR::LO
                        | VR::LT
                        | VR::SH
                        | VR::ST
                        | VR::UT
                        | VR::UR
                        | VR::TM
                        | VR::UC
                        | VR::UI => {
                            let items: Vec<String> = map.next_value()?;
                            values = Some(PrimitiveValue::Strs(items.into()).into());
                        }

                        // should always be signed 16-bit integers
                        VR::SS => {
                            let items: Vec<i16> = map.next_value()?;
                            values = Some(PrimitiveValue::I16(items.into()).into());
                        }
                        // should always be unsigned 16-bit integers
                        VR::US | VR::OW => {
                            let items: Vec<u16> = map.next_value()?;
                            values = Some(PrimitiveValue::U16(items.into()).into());
                        }
                        // should always be signed 32-bit integers
                        VR::SL => {
                            let items: Vec<i32> = map.next_value()?;
                            values = Some(PrimitiveValue::I32(items.into()).into());
                        }
                        VR::OB => {
                            let items: Vec<u8> = map.next_value()?;
                            values = Some(PrimitiveValue::U8(items.into()).into());
                        }
                        // sometimes numbers, sometimes text,
                        // should parse on the spot
                        VR::FL | VR::OF => {
                            let items: Vec<NumberOrText<f32>> = map.next_value()?;
                            let items: C<f32> = items
                                .into_iter()
                                .map(|v| v.to_num())
                                .collect::<Result<C<f32>, _>>()
                                .map_err(A::Error::custom)?;
                            values = Some(PrimitiveValue::F32(items).into());
                        }
                        VR::FD | VR::OD => {
                            let items: Vec<NumberOrText<f64>> = map.next_value()?;
                            let items: C<f64> = items
                                .into_iter()
                                .map(|v| v.to_num())
                                .collect::<Result<C<f64>, _>>()
                                .map_err(A::Error::custom)?;
                            values = Some(PrimitiveValue::F64(items).into());
                        }
                        VR::SV => {
                            let items: Vec<NumberOrText<i64>> = map.next_value()?;
                            let items: C<i64> = items
                                .into_iter()
                                .map(|v| v.to_num())
                                .collect::<Result<C<i64>, _>>()
                                .map_err(A::Error::custom)?;
                            values = Some(PrimitiveValue::I64(items).into());
                        }
                        VR::UL | VR::OL => {
                            let items: Vec<NumberOrText<u32>> = map.next_value()?;
                            let items: C<u32> = items
                                .into_iter()
                                .map(|v| v.to_num())
                                .collect::<Result<C<u32>, _>>()
                                .map_err(A::Error::custom)?;
                            values = Some(PrimitiveValue::U32(items).into());
                        }
                        VR::UV | VR::OV => {
                            let items: Vec<NumberOrText<u64>> = map.next_value()?;
                            let items: C<u64> = items
                                .into_iter()
                                .map(|v| v.to_num())
                                .collect::<Result<C<u64>, _>>()
                                .map_err(A::Error::custom)?;
                            values = Some(PrimitiveValue::U64(items).into());
                        }
                        // sometimes numbers, sometimes text,
                        // but retain string form
                        VR::DS => {
                            let items: Vec<NumberOrText<f64>> = map.next_value()?;
                            let items: C<String> =
                                items.into_iter().map(|v| v.to_string()).collect();
                            values = Some(PrimitiveValue::Strs(items).into());
                        }
                        VR::IS => {
                            let items: Vec<NumberOrText<f64>> = map.next_value()?;
                            let items: C<String> =
                                items.into_iter().map(|v| v.to_string()).collect();
                            values = Some(PrimitiveValue::Strs(items).into());
                        }
                        // person names
                        VR::PN => {
                            let items: Vec<DicomJsonPerson> = map.next_value()?;
                            let items: C<String> =
                                items.into_iter().map(|v| v.to_string()).collect();
                            values = Some(PrimitiveValue::Strs(items).into());
                        }
                        // tags
                        VR::AT => {
                            let items: Vec<DicomJson<Tag>> = map.next_value()?;
                            let items: C<Tag> =
                                items.into_iter().map(DicomJson::into_inner).collect();
                            values = Some(PrimitiveValue::Tags(items).into());
                        }
                        // unknown
                        VR::UN => return Err(A::Error::custom("can't parse JSON Value in UN")),
                    }
                }
                "InlineBinary" => {
                    if values.is_some() {
                        return Err(A::Error::custom(
                            "\"InlineBinary\" conflicts with \"Value\"",
                        ));
                    }
                    // read value as string
                    let val: String = map.next_value()?;
                    inline_binary = Some(val);
                }
                _ => {
                    return Err(A::Error::custom("Unrecognized data element field"));
                }
            }
        }

        let value = match (values, inline_binary) {
            (None, None) => PrimitiveValue::Empty.into(),
            (None, Some(inline_binary)) => {
                // decode from Base64
                use base64::Engine;
                let data = base64::engine::general_purpose::STANDARD
                    .decode(inline_binary)
                    .map_err(|_| A::Error::custom("inline binary data is not valid base64"))?;
                PrimitiveValue::from(data).into()
            }
            (Some(values), None) => values,
            (Some(_), Some(_)) => unreachable!(),
        };

        Ok(JsonDataElement { vr, value })
    }
}

impl<'de, I> Deserialize<'de> for JsonDataElement<I>
where
    I: Default + Clone + DataDictionary,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "DataElement",
            &["vr", "Value", "InlineData", "BulkDataURI"],
            DataElementVisitor(PhantomData),
        )
    }
}

#[derive(Debug)]
struct TagVisitor;

impl Visitor<'_> for TagVisitor {
    type Value = Tag;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a DICOM tag string in the form \"GGGGEEEE\"")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        v.parse().map_err(E::custom)
    }
}

impl<'de> Deserialize<'de> for DicomJson<Tag> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(TagVisitor).map(DicomJson)
    }
}

#[cfg(test)]
mod tests {
    use super::from_str;
    use dicom_core::{DataElement, Tag, VR};
    use dicom_object::InMemDicomObject;

    #[test]
    fn can_parse_tags() {
        let serialized = "\"00080010\"";
        let tag: Tag = from_str(serialized).unwrap();
        assert_eq!(tag, Tag(0x0008, 0x0010));

        let serialized = "\"00200013\"";
        let tag: Tag = from_str(serialized).unwrap();
        assert_eq!(tag, Tag(0x0020, 0x0013));
    }

    #[test]
    fn can_parse_simple_data_sets() {
        let serialized = serde_json::json!({
            "00080005": {
                "vr": "CS",
                "Value": [ "ISO_IR 192" ]
            },
            "00080020": {
                "vr": "DA",
                "Value": [ "20130409" ]
            },
            "00080061": {
                "vr": "CS",
                "Value": [
                    "CT",
                    "PET"
                ]
            },
            "00080090": {
                "vr": "PN",
                "Value": [
                  {
                    "Alphabetic": "^Bob^^Dr."
                  }
                ]
            },
            "00091002": {
                "vr": "UN",
                "InlineBinary": "z0x9c8v7"
            },
            "00101010": {
                "vr": "AS",
                "Value": [ "30Y" ]
            }
        });

        let obj: InMemDicomObject = super::from_value(serialized).unwrap();

        let tag = Tag(0x0008, 0x0005);
        assert_eq!(
            obj.get(tag),
            Some(&DataElement::new(tag, VR::CS, "ISO_IR 192")),
        )
    }
}