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
//! This module includes a high level abstraction over a DICOM data element's value.

use crate::error::CastValueError;
use crate::header::{Length, Tag};
use chrono::{DateTime, Datelike, FixedOffset, NaiveDate, NaiveTime, Timelike};
use itertools::Itertools;
use smallvec::SmallVec;
use std::borrow::Cow;

/// An aggregation of one or more elements in a value.
pub type C<T> = SmallVec<[T; 2]>;

/// Representation of a full DICOM value, which may be either primitive or
/// another DICOM object.
#[derive(Debug, Clone, PartialEq)]
pub enum Value<I> {
    /// Primitive value
    Primitive(PrimitiveValue),
    /// A complex sequence of items
    Sequence {
        /// Item collection.
        items: C<I>,
        /// The size in bytes.
        size: Length,
    },
}

impl<I> Value<I>
where
    I: DicomValueType,
{
    /// Obtain the number of individual values.
    /// In a sequence item, this is the number of items.
    pub fn multiplicity(&self) -> u32 {
        match *self {
            Value::Primitive(ref v) => v.multiplicity(),
            Value::Sequence { ref items, .. } => items.len() as u32,
        }
    }

    /// Gets a reference to the primitive value.
    pub fn primitive(&self) -> Option<&PrimitiveValue> {
        match *self {
            Value::Primitive(ref v) => Some(v),
            _ => None,
        }
    }

    /// Gets a reference to the items.
    pub fn item(&self) -> Option<&[I]> {
        match *self {
            Value::Sequence { ref items, .. } => Some(items),
            _ => None,
        }
    }

    /// Retrieves the primitive value.
    pub fn into_primitive(self) -> Option<PrimitiveValue> {
        match self {
            Value::Primitive(v) => Some(v),
            _ => None,
        }
    }

    /// Retrieves the items.
    pub fn into_item(self) -> Option<C<I>> {
        match self {
            Value::Sequence { items, .. } => Some(items),
            _ => None,
        }
    }

    /// Retrieves the primitive value as a single string.
    ///
    /// If the value contains multiple strings, they are concatenated
    /// (separated by `'\\'`) into an owned string.
    pub fn to_str(&self) -> Result<Cow<str>, CastValueError> {
        match self {
            Value::Primitive(PrimitiveValue::Str(v)) => Ok(Cow::from(v.as_str())),
            Value::Primitive(PrimitiveValue::Strs(v)) => Ok(Cow::from(v.into_iter().join("\\"))),
            _ => Err(CastValueError {
                requested: "string",
                got: self.value_type(),
            }),
        }
    }

    /// Retrieves the primitive value as a sequence of unsigned bytes.
    pub fn as_u8(&self) -> Result<&[u8], CastValueError> {
        match self {
            Value::Primitive(PrimitiveValue::U8(v)) => Ok(&v),
            _ => Err(CastValueError {
                requested: "u8",
                got: self.value_type(),
            }),
        }
    }

    /// Retrieves the primitive value as a sequence of signed 32-bit integers.
    pub fn as_i32(&self) -> Result<&[i32], CastValueError> {
        match self {
            Value::Primitive(PrimitiveValue::I32(v)) => Ok(&v),
            _ => Err(CastValueError {
                requested: "i32",
                got: self.value_type(),
            }),
        }
    }

    /// Retrieves the primitive value as a DICOM tag.
    pub fn to_tag(&self) -> Result<Tag, CastValueError> {
        match self {
            Value::Primitive(PrimitiveValue::Tags(v)) => Ok(v[0]),
            _ => Err(CastValueError {
                requested: "tag",
                got: self.value_type(),
            }),
        }
    }

    /// Retrieves the primitive value as a sequence of DICOM tags.
    pub fn as_tags(&self) -> Result<&[Tag], CastValueError> {
        match self {
            Value::Primitive(PrimitiveValue::Tags(v)) => Ok(&v),
            _ => Err(CastValueError {
                requested: "tag",
                got: self.value_type(),
            }),
        }
    }
}

impl<I> From<PrimitiveValue> for Value<I> {
    fn from(v: PrimitiveValue) -> Self {
        Value::Primitive(v)
    }
}

/// An enum representing a primitive value from a DICOM element. The result of decoding
/// an element's data value may be one of the enumerated types depending on its content
/// and value representation.
#[derive(Debug, PartialEq, Clone)]
pub enum PrimitiveValue {
    /// No data. Used for SQ (regardless of content) and any value of length 0.
    Empty,

    /// A sequence of strings.
    /// Used for AE, AS, PN, SH, CS, LO, UI and UC.
    /// Can also be used for IS, SS, DS, DA, DT and TM when decoding
    /// with format preservation.
    Strs(C<String>),

    /// A single string.
    /// Used for ST, LT, UT and UR, which are never multi-valued.
    Str(String),

    /// A sequence of attribute tags.
    /// Used specifically for AT.
    Tags(C<Tag>),

    /// The value is a sequence of unsigned 16-bit integers.
    /// Used for OB and UN.
    U8(C<u8>),

    /// The value is a sequence of signed 16-bit integers.
    /// Used for SS.
    I16(C<i16>),

    /// A sequence of unsigned 168-bit integers.
    /// Used for US and OW.
    U16(C<u16>),

    /// A sequence of signed 32-bit integers.
    /// Used for SL and IS.
    I32(C<i32>),

    /// A sequence of unsigned 32-bit integers.
    /// Used for UL and OL.
    U32(C<u32>),

    /// A sequence of signed 64-bit integers.
    /// Used for SV.
    I64(C<i64>),

    /// A sequence of unsigned 64-bit integers.
    /// Used for UV and OV.
    U64(C<u64>),

    /// The value is a sequence of 32-bit floating point numbers.
    /// Used for OF and FL.
    F32(C<f32>),

    /// The value is a sequence of 64-bit floating point numbers.
    /// Used for OD and FD, DS.
    F64(C<f64>),

    /// A sequence of dates.
    /// Used for the DA representation.
    Date(C<NaiveDate>),

    /// A sequence of date-time values.
    /// Used for the DT representation.
    DateTime(C<DateTime<FixedOffset>>),

    /// A sequence of time values.
    /// Used for the TM representation.
    Time(C<NaiveTime>),
}

impl PrimitiveValue {
    /// Obtain the number of individual elements. This number may not
    /// match the DICOM value multiplicity in some value representations.
    pub fn multiplicity(&self) -> u32 {
        use self::PrimitiveValue::*;
        match self {
            Empty => 0,
            Str(_) => 1,
            Strs(c) => c.len() as u32,
            Tags(c) => c.len() as u32,
            U8(c) => c.len() as u32,
            I16(c) => c.len() as u32,
            U16(c) => c.len() as u32,
            I32(c) => c.len() as u32,
            U32(c) => c.len() as u32,
            I64(c) => c.len() as u32,
            U64(c) => c.len() as u32,
            F32(c) => c.len() as u32,
            F64(c) => c.len() as u32,
            Date(c) => c.len() as u32,
            DateTime(c) => c.len() as u32,
            Time(c) => c.len() as u32,
        }
    }

    /// Get a single string value. If it contains multiple strings,
    /// only the first one is returned.
    pub fn string(&self) -> Option<&str> {
        use self::PrimitiveValue::*;
        match self {
            Strs(c) => c.first().map(String::as_str),
            Str(s) => Some(s),
            _ => None,
        }
    }

    /// Get a sequence of string values.
    pub fn strings(&self) -> Option<Vec<&str>> {
        use self::PrimitiveValue::*;
        match self {
            Strs(c) => Some(c.iter().map(String::as_str).collect()),
            Str(s) => Some(vec![&s]),
            _ => None,
        }
    }

    /// Get a single DICOM tag.
    pub fn tag(&self) -> Option<Tag> {
        use self::PrimitiveValue::*;
        match self {
            Tags(c) => c.first().map(Clone::clone),
            _ => None,
        }
    }

    /// Get a sequence of DICOM tags.
    pub fn tags(&self) -> Option<&[Tag]> {
        use self::PrimitiveValue::*;
        match self {
            Tags(c) => Some(&c),
            _ => None,
        }
    }

    /// Get a single 64-bit signed integer value.
    pub fn int64(&self) -> Option<i64> {
        use self::PrimitiveValue::*;
        match self {
            I64(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 64-bit unsigned integer value.
    pub fn uint64(&self) -> Option<u64> {
        use self::PrimitiveValue::*;
        match self {
            U64(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 32-bit signed integer value.
    pub fn int32(&self) -> Option<i32> {
        use self::PrimitiveValue::*;
        match self {
            I32(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 32-bit unsigned integer value.
    pub fn uint32(&self) -> Option<u32> {
        use self::PrimitiveValue::*;
        match self {
            U32(ref c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 16-bit signed integer value.
    pub fn int16(&self) -> Option<i16> {
        use self::PrimitiveValue::*;
        match self {
            I16(ref c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 16-bit unsigned integer value.
    pub fn uint16(&self) -> Option<u16> {
        use self::PrimitiveValue::*;
        match self {
            U16(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 8-bit unsigned integer value.
    pub fn uint8(&self) -> Option<u8> {
        use self::PrimitiveValue::*;
        match self {
            U8(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 32-bit floating point number value.
    pub fn float32(&self) -> Option<f32> {
        use self::PrimitiveValue::*;
        match self {
            F32(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Get a single 64-bit floating point number value.
    pub fn float64(&self) -> Option<f64> {
        use self::PrimitiveValue::*;
        match self {
            F64(c) => c.first().cloned(),
            _ => None,
        }
    }

    /// Determine the minimum number of bytes that this value would need to
    /// occupy in a DICOM file, without compression and without the header.
    /// As mandated by the standard, it is always even.
    /// The calculated number does not need to match the size of the original
    /// byte stream.
    pub fn calculate_byte_len(&self) -> usize {
        use self::PrimitiveValue::*;
        match self {
            Empty => 0,
            U8(c) => c.len(),
            I16(c) => c.len() * 2,
            U16(c) => c.len() * 2,
            U32(c) => c.len() * 4,
            I32(c) => c.len() * 4,
            U64(c) => c.len() * 8,
            I64(c) => c.len() * 8,
            F32(c) => c.len() * 4,
            F64(c) => c.len() * 8,
            Tags(c) => c.len() * 4,
            Date(c) => c.len() * 8,
            Str(s) => s.as_bytes().len(),
            Strs(c) if c.is_empty() => 0,
            Strs(c) => {
                c.iter()
                    .map(|s| ((s.as_bytes().len() + 1) & !1) + 1)
                    .sum::<usize>()
                    - 1
            }
            Time(c) if c.is_empty() => 0,
            Time(c) => {
                c.iter()
                    .map(|t| ((PrimitiveValue::tm_byte_len(*t) + 1) & !1) + 1)
                    .sum::<usize>()
                    - 1
            }
            DateTime(c) if c.is_empty() => 0,
            DateTime(c) => {
                c.iter()
                    .map(|dt| ((PrimitiveValue::dt_byte_len(*dt) + 1) & !1) + 1)
                    .sum::<usize>()
                    - 1
            }
        }
    }

    fn tm_byte_len(time: NaiveTime) -> usize {
        match (time.hour(), time.minute(), time.second(), time.nanosecond()) {
            (_, 0, 0, 0) => 2,
            (_, _, 0, 0) => 4,
            (_, _, _, 0) => 6,
            (_, _, _, nano) => {
                let mut frac = nano / 1000; // nano to microseconds
                let mut trailing_zeros = 0;
                while frac % 10 == 0 {
                    frac /= 10;
                    trailing_zeros += 1;
                }
                7 + 6 - trailing_zeros
            }
        }
    }

    fn dt_byte_len(datetime: DateTime<FixedOffset>) -> usize {
        // !!! the current local definition of datetime is inaccurate, because
        // it cannot distinguish unspecified components from their defaults
        // (e.g. 201812 should be different from 20181201). This will have to
        // be changed at some point.
        (match (datetime.month(), datetime.day()) {
            (1, 1) => 0,
            (_, 1) => 2,
            _ => 4,
        }) + 8
            + PrimitiveValue::tm_byte_len(datetime.time())
            + if datetime.offset() == &FixedOffset::east(0) {
                0
            } else {
                5
            }
    }
}

/// An enum representing an abstraction of a DICOM element's data value type.
/// This should be the equivalent of `PrimitiveValue` without the content,
/// plus the `Item` entry.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ValueType {
    /// No data. Used for any value of length 0.
    Empty,

    /// An item. Used for elements in a SQ, regardless of content.
    Item,

    /// A sequence of strings.
    /// Used for AE, AS, PN, SH, CS, LO, UI and UC.
    /// Can also be used for IS, SS, DS, DA, DT and TM when decoding
    /// with format preservation.
    Strs,

    /// A single string.
    /// Used for ST, LT, UT and UR, which are never multi-valued.
    Str,

    /// A sequence of attribute tags.
    /// Used specifically for AT.
    Tags,

    /// The value is a sequence of unsigned 16-bit integers.
    /// Used for OB and UN.
    U8,

    /// The value is a sequence of signed 16-bit integers.
    /// Used for SS.
    I16,

    /// A sequence of unsigned 168-bit integers.
    /// Used for US and OW.
    U16,

    /// A sequence of signed 32-bit integers.
    /// Used for SL and IS.
    I32,

    /// A sequence of unsigned 32-bit integers.
    /// Used for UL and OL.
    U32,

    /// A sequence of signed 64-bit integers.
    /// Used for SV.
    I64,

    /// A sequence of unsigned 64-bit integers.
    /// Used for UV and OV.
    U64,

    /// The value is a sequence of 32-bit floating point numbers.
    /// Used for OF and FL.
    F32,

    /// The value is a sequence of 64-bit floating point numbers.
    /// Used for OD, FD and DS.
    F64,

    /// A sequence of dates.
    /// Used for the DA representation.
    Date,

    /// A sequence of date-time values.
    /// Used for the DT representation.
    DateTime,

    /// A sequence of time values.
    /// Used for the TM representation.
    Time,
}

/// A trait for a value that maps to a DICOM element data value.
pub trait DicomValueType {
    /// Retrieve the specific type of this value.
    fn value_type(&self) -> ValueType;

    /// Retrieve the number of values contained.
    fn size(&self) -> Length;

    /// Check whether the value is empty (0 length).
    fn is_empty(&self) -> bool {
        self.size() == Length(0)
    }
}

impl DicomValueType for PrimitiveValue {
    fn value_type(&self) -> ValueType {
        use self::PrimitiveValue::*;
        match *self {
            Empty => ValueType::Empty,
            Date(_) => ValueType::Date,
            DateTime(_) => ValueType::DateTime,
            F32(_) => ValueType::F32,
            F64(_) => ValueType::F64,
            I16(_) => ValueType::I16,
            I32(_) => ValueType::I32,
            I64(_) => ValueType::I64,
            Str(_) => ValueType::Str,
            Strs(_) => ValueType::Strs,
            Tags(_) => ValueType::Tags,
            Time(_) => ValueType::Time,
            U16(_) => ValueType::U16,
            U32(_) => ValueType::U32,
            U64(_) => ValueType::U64,
            U8(_) => ValueType::U8,
        }
    }

    fn size(&self) -> Length {
        use self::PrimitiveValue::*;
        Length::defined(match self {
            Empty => 0,
            Str(_) => 1,
            Date(b) => b.len() as u32,
            DateTime(b) => b.len() as u32,
            F32(b) => b.len() as u32,
            F64(b) => b.len() as u32,
            I16(b) => b.len() as u32,
            I32(b) => b.len() as u32,
            I64(b) => b.len() as u32,
            Strs(b) => b.len() as u32,
            Tags(b) => b.len() as u32,
            Time(b) => b.len() as u32,
            U16(b) => b.len() as u32,
            U32(b) => b.len() as u32,
            U64(b) => b.len() as u32,
            U8(b) => b.len() as u32,
        })
    }
}

impl<I> DicomValueType for Value<I>
where
    I: DicomValueType,
{
    fn value_type(&self) -> ValueType {
        match *self {
            Value::Primitive(ref v) => v.value_type(),
            Value::Sequence { .. } => ValueType::Item,
        }
    }

    fn size(&self) -> Length {
        match *self {
            Value::Primitive(ref v) => v.size(),
            Value::Sequence { size, .. } => size,
        }
    }
}