dicom_encoding/transfer_syntax/
mod.rs

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
//! Module containing the DICOM Transfer Syntax data structure and related methods.
//! Similar to the DcmCodec in DCMTK, the `TransferSyntax` contains all of the necessary
//! algorithms for decoding and encoding DICOM data in a certain transfer syntax.
//!
//! This crate does not host specific transfer syntaxes. Instead, they are created in
//! other crates and registered in the global transfer syntax registry,
//! which implements [`TransferSyntaxIndex`].
//! For more information, please see the [`dicom-transfer-syntax-registry`] crate,
//! which provides built-in implementations.
//!
//! This module allows you to register your own transfer syntaxes.
//! With the `inventory-registry` Cargo feature,
//! you can use the macro [`submit_transfer_syntax`](crate::submit_transfer_syntax)
//! or [`submit_ele_transfer_syntax`](crate::submit_ele_transfer_syntax)
//! to instruct the compiler to include your implementation in the registry.
//! Without the `inventory`-based registry
//! (in case your environment does not support it),
//! you can still roll your own [transfer syntax index][1].
//!
//! [1]: TransferSyntaxIndex
//! [`dicom-transfer-syntax-registry`]: https://docs.rs/dicom-transfer-syntax-registry

use crate::adapters::{
    DynPixelDataReader, DynPixelDataWriter, NeverPixelAdapter, PixelDataReader, PixelDataWriter,
};
use crate::decode::{
    basic::BasicDecoder, explicit_be::ExplicitVRBigEndianDecoder,
    explicit_le::ExplicitVRLittleEndianDecoder, implicit_le::ImplicitVRLittleEndianDecoder,
    DecodeFrom,
};
use crate::encode::{
    explicit_be::ExplicitVRBigEndianEncoder, explicit_le::ExplicitVRLittleEndianEncoder,
    implicit_le::ImplicitVRLittleEndianEncoder, EncodeTo, EncoderFor,
};
use std::io::{Read, Write};

pub use byteordered::Endianness;

/// A decoder with its type erased.
pub type DynDecoder<S> = Box<dyn DecodeFrom<S>>;

/// An encoder with its type erased.
pub type DynEncoder<'w, W> = Box<dyn EncodeTo<W> + 'w>;

/// A DICOM transfer syntax specifier.
///
/// Custom encoding and decoding capabilities
/// are defined via the parameter types `D` and `P`,
/// The type parameter `D` specifies
/// an adapter for reading and writing data sets,
/// whereas `P` specifies the encoder and decoder of encapsulated pixel data.
///
/// This type is usually consumed in its "type erased" form,
/// with its default parameter types.
/// On the other hand, implementers of `TransferSyntax` will typically specify
/// concrete types for `D` and `P`,
/// which are type-erased before registration.
/// If the transfer syntax requires no data set codec,
/// `D` can be assigned to the utility type [`NeverAdapter`].
/// If pixel data encoding/decoding is not needed or not supported,
/// you can assign `P` to [`NeverPixelAdapter`].
#[derive(Debug)]
pub struct TransferSyntax<D = DynDataRWAdapter, R = DynPixelDataReader, W = DynPixelDataWriter> {
    /// The unique identifier of the transfer syntax.
    uid: &'static str,
    /// The name of the transfer syntax.
    name: &'static str,
    /// The byte order of data.
    byte_order: Endianness,
    /// Whether the transfer syntax mandates an explicit value representation,
    /// or the VR is implicit.
    explicit_vr: bool,
    /// The transfer syntax' requirements and implemented capabilities.
    codec: Codec<D, R, W>,
}

/// Wrapper type for a provider of transfer syntax descriptors.
///
/// This is a piece of the plugin interface for
/// registering and collecting transfer syntaxes.
/// Implementers and consumers of transfer syntaxes
/// will usually not interact with it directly.
/// In order to register a new transfer syntax,
/// see the macro [`submit_transfer_syntax`](crate::submit_transfer_syntax).
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TransferSyntaxFactory(pub fn() -> TransferSyntax);

#[cfg(feature = "inventory-registry")]
// Collect transfer syntax specifiers from other crates.
inventory::collect!(TransferSyntaxFactory);

/// Trait for a container/repository of transfer syntax specifiers.
///
/// Types implementing this trait are held responsible for populating
/// themselves with a set of transfer syntaxes, which can be fully supported,
/// partially supported, or not supported. Usually, only one implementation
/// of this trait is used for the entire program,
/// the most common one being the `TransferSyntaxRegistry` type
/// from [`transfer-syntax-registry`].
///
/// [`transfer-syntax-registry`]: https://docs.rs/dicom-transfer-syntax-registry
pub trait TransferSyntaxIndex {
    /// Obtain a DICOM transfer syntax by its respective UID.
    ///
    /// Implementations of this method should be robust to the possible
    /// presence of trailing null characters (`\0`) in `uid`.
    fn get(&self, uid: &str) -> Option<&TransferSyntax>;
}

impl<T: ?Sized> TransferSyntaxIndex for &T
where
    T: TransferSyntaxIndex,
{
    fn get(&self, uid: &str) -> Option<&TransferSyntax> {
        (**self).get(uid)
    }
}

#[cfg(feature = "inventory-registry")]
#[macro_export]
/// Submit a transfer syntax specifier to be supported by the
/// program's runtime. This is to be used by crates wishing to provide
/// additional support for a certain transfer syntax using the
/// main transfer syntax registry.
///
/// This macro does not actually "run" anything, so place it outside of a
/// function body at the root of the crate.
/// The expression is evaluated when the transfer syntax registry is populated
/// upon the first request,
/// and must resolve to a value of type [`TransferSyntax<D, P>`],
/// for valid definitions of the parameter types `D` and `P`.
/// The macro will type-erase these parameters automatically.
///
/// # Example
///
/// One common use case is wanting to read data sets
/// of DICOM objects in a private transfer syntax,
/// even when a decoder for that pixel data is not available.
/// By writing a simple stub at your project's root,
/// the rest of the ecosystem will know
/// how to read and write data sets in that transfer syntax.
///
/// ```
/// use dicom_encoding::{
///     submit_transfer_syntax, AdapterFreeTransferSyntax, Codec, Endianness,
/// };
///
/// submit_transfer_syntax!(AdapterFreeTransferSyntax::new(
///     // Transfer Syntax UID
///     "1.3.46.670589.33.1.4.1",
///     // Name/alias
///     "CT Private ELE",
///     // Data set byte order
///     Endianness::Little,
///     // Explicit VR (true) or Implicit VR (false)
///     true,
///     Codec::EncapsulatedPixelData(None, None),  // pixel data codec
/// ));
/// ```
///
/// With [`Codec::EncapsulatedPixelData(None, None)`][1],
/// we are indicating that the transfer syntax uses encapsulated pixel data.
/// albeit without the means to decode or encode it.
/// See the [`adapters`](crate::adapters) module
/// to know how to write pixel data encoders and decoders.
///
/// [1]: Codec::EncapsulatedPixelData
macro_rules! submit_transfer_syntax {
    ($ts: expr) => {
        $crate::inventory::submit! {
            $crate::transfer_syntax::TransferSyntaxFactory(|| ($ts).erased())
        }
    };
}

#[cfg(not(feature = "inventory-registry"))]
#[macro_export]
/// Submit a transfer syntax specifier to be supported by the
/// program's runtime. This is to be used by crates wishing to provide
/// additional support for a certain transfer syntax using the
/// main transfer syntax registry.
///
/// This macro does actually "run" anything, so place it outside of a
/// function body at the root of the crate.
///
/// Without the `inventory-registry` feature, this request is ignored.
macro_rules! submit_transfer_syntax {
    ($ts: expr) => {
        // ignore request
    };
}

#[cfg(feature = "inventory-registry")]
#[macro_export]
/// Submit an explicit VR little endian transfer syntax specifier
/// to be supported by the program's runtime.
///
/// This macro is equivalent in behavior as [`submit_transfer_syntax`](crate::submit_transfer_syntax),
/// but it is easier to use when
/// writing support for compressed pixel data formats,
/// which are usually in explicit VR little endian.
///
/// This macro does not actually "run" anything, so place it outside of a
/// function body at the root of the crate.
/// The expression is evaluated when the transfer syntax registry is populated
/// upon the first request,
/// and must resolve to a value of type [`Codec<D, R, W>`],
/// for valid definitions of the parameter types `D`, `R`, and `W`.
/// The macro will type-erase these parameters automatically.
///
/// # Example
///
/// One common use case is wanting to read data sets
/// of DICOM objects in a private transfer syntax,
/// even when a decoder for that pixel data is not available.
/// By writing a simple stub at your project's root,
/// the rest of the ecosystem will know
/// how to read and write data sets in that transfer syntax.
///
/// ```
/// use dicom_encoding::{submit_ele_transfer_syntax, Codec};
///
/// submit_ele_transfer_syntax!(
///     // Transfer Syntax UID
///     "1.3.46.670589.33.1.4.1",
///     // Name/alias
///     "CT Private ELE",
///     // pixel data codec
///     Codec::EncapsulatedPixelData(None, None)
/// );
/// ```
///
/// With [`Codec::EncapsulatedPixelData(None, None)`][1],
/// we are indicating that the transfer syntax uses encapsulated pixel data.
/// albeit without the means to decode or encode it.
/// See the [`adapters`](crate::adapters) module
/// to know how to write pixel data encoders and decoders.
///
/// [1]: Codec::EncapsulatedPixelData
macro_rules! submit_ele_transfer_syntax {
    ($uid: expr, $name: expr, $codec: expr) => {
        $crate::submit_transfer_syntax! {
            $crate::AdapterFreeTransferSyntax::new_ele(
                $uid,
                $name,
                $codec
            )
        }
    };
}

#[cfg(not(feature = "inventory-registry"))]
#[macro_export]
/// Submit an explicit VR little endian transfer syntax specifier
/// to be supported by the program's runtime.
///
/// This macro is equivalent in behavior as [`submit_transfer_syntax`],
/// but it is easier to use when
/// writing support for compressed pixel data formats,
/// which are usually in explicit VR little endian.
///
/// This macro does actually "run" anything, so place it outside of a
/// function body at the root of the crate.
///
/// Without the `inventory-registry` feature, this request is ignored.
macro_rules! submit_ele_transfer_syntax {
    ($uid: literal, $name: literal, $codec: expr) => {
        // ignore request
    };
}

/// A description and possible implementation regarding
/// the encoding and decoding requirements of a transfer syntax.
/// This is also used as a means to describe whether pixel data is encapsulated
/// and whether this implementation supports decoding and/or encoding it.
///
/// ### Type parameters
///
/// - `D` should implement [`DataRWAdapter`]
///   and defines how one should read and write DICOM data sets,
///   such as in the case for deflated data.
///   When no special considerations for data set reading and writing
///   are necessary, this can be set to [`NeverAdapter`].
/// - `R` should implement [`PixelDataReader`],
///   and enables programs to convert encapsulated pixel data fragments
///   into native pixel data.
/// - `W` should implement [`PixelDataWriter`],
///   and enables programs to convert native pixel data
///   into encapsulated pixel data.
///
#[derive(Debug, Clone, PartialEq)]
pub enum Codec<D, R, W> {
    /// No codec is required for this transfer syntax.
    ///
    /// Pixel data, if any, should be in its _native_, unencapsulated format.
    None,
    /// Pixel data for this transfer syntax is encapsulated
    /// and likely subjected to a specific encoding process.
    /// The first part of the tuple struct contains the pixel data decoder,
    /// whereas the second item is for the pixel data encoder.
    ///
    /// Decoding of the pixel data is not supported
    /// if the decoder is `None`.
    /// In this case, the program should still be able to
    /// parse DICOM data sets
    /// and fetch the pixel data in its encapsulated form.
    EncapsulatedPixelData(Option<R>, Option<W>),
    /// A custom data set codec is required for reading and writing data sets.
    ///
    /// If the item in the tuple struct is `None`,
    /// then no reading and writing whatsoever is supported.
    /// This could be used by a stub of
    /// _Deflated Explicit VR Little Endian_, for example.
    Dataset(Option<D>),
}

/// An alias for a transfer syntax specifier with no pixel data encapsulation
/// nor data set deflating.
pub type AdapterFreeTransferSyntax =
    TransferSyntax<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter>;

/// An adapter of byte read and write streams.
pub trait DataRWAdapter<R, W> {
    /// The type of the adapted reader.
    type Reader: Read;
    /// The type of the adapted writer.
    type Writer: Write;

    /// Adapt a byte reader.
    fn adapt_reader(&self, reader: R) -> Self::Reader
    where
        R: Read;

    /// Adapt a byte writer.
    fn adapt_writer(&self, writer: W) -> Self::Writer
    where
        W: Write;
}

/// Alias type for a dynamically dispatched data adapter.
pub type DynDataRWAdapter = Box<
    dyn DataRWAdapter<
            Box<dyn Read>,
            Box<dyn Write>,
            Reader = Box<dyn Read>,
            Writer = Box<dyn Write>,
        > + Send
        + Sync,
>;

impl<T, R, W> DataRWAdapter<R, W> for &'_ T
where
    T: DataRWAdapter<R, W>,
    R: Read,
    W: Write,
{
    type Reader = <T as DataRWAdapter<R, W>>::Reader;
    type Writer = <T as DataRWAdapter<R, W>>::Writer;

    /// Adapt a byte reader.
    fn adapt_reader(&self, reader: R) -> Self::Reader
    where
        R: Read,
    {
        (**self).adapt_reader(reader)
    }

    /// Adapt a byte writer.
    fn adapt_writer(&self, writer: W) -> Self::Writer
    where
        W: Write,
    {
        (**self).adapt_writer(writer)
    }
}

/// An immaterial type representing a data set adapter which is never required,
/// and as such is never instantiated.
/// Most transfer syntaxes use this,
/// as they do not have to adapt readers and writers
/// for encoding and decoding data sets.
/// The main exception is in the family of
/// _Deflated Explicit VR Little Endian_ transfer syntaxes.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum NeverAdapter {}

impl<R, W> DataRWAdapter<R, W> for NeverAdapter {
    type Reader = Box<dyn Read>;
    type Writer = Box<dyn Write>;

    fn adapt_reader(&self, _reader: R) -> Self::Reader
    where
        R: Read,
    {
        unreachable!()
    }

    fn adapt_writer(&self, _writer: W) -> Self::Writer
    where
        W: Write,
    {
        unreachable!()
    }
}

impl<D, R, W> TransferSyntax<D, R, W> {
    /// Create a new transfer syntax descriptor.
    ///
    /// Note that only transfer syntax implementers are expected to
    /// construct TS descriptors from scratch.
    /// For a practical usage of transfer syntaxes,
    /// one should look up an existing transfer syntax registry by UID.
    ///
    /// # Example
    ///
    /// To register a private transfer syntax in your program,
    /// use [`submit_transfer_syntax`](crate::submit_transfer_syntax)
    /// outside of a function body:
    ///  
    /// ```no_run
    /// # use dicom_encoding::{
    /// #     submit_transfer_syntax, Codec, Endianness,
    /// #     NeverAdapter, NeverPixelAdapter, TransferSyntax,
    /// # };
    /// submit_transfer_syntax! {
    ///     TransferSyntax::<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter>::new(
    ///         "1.3.46.670589.33.1.4.1",
    ///         "CT-Private-ELE",
    ///         Endianness::Little,
    ///         true,
    ///         Codec::EncapsulatedPixelData(None, None),
    ///     )
    /// }
    /// ```
    pub const fn new(
        uid: &'static str,
        name: &'static str,
        byte_order: Endianness,
        explicit_vr: bool,
        codec: Codec<D, R, W>,
    ) -> Self {
        TransferSyntax {
            uid,
            name,
            byte_order,
            explicit_vr,
            codec,
        }
    }

    /// Create a new descriptor
    /// for a transfer syntax in explicit VR little endian.
    ///
    /// Note that only transfer syntax implementers are expected to
    /// construct TS descriptors from scratch.
    /// For a practical usage of transfer syntaxes,
    /// one should look up an existing transfer syntax registry by UID.
    ///
    /// # Example
    ///
    /// To register a private transfer syntax in your program,
    /// use [`submit_transfer_syntax`](crate::submit_transfer_syntax)
    /// outside of a function body:
    ///  
    /// ```no_run
    /// # use dicom_encoding::{
    /// #     submit_transfer_syntax, Codec,
    /// #     NeverAdapter, NeverPixelAdapter, TransferSyntax,
    /// # };
    /// submit_transfer_syntax! {
    ///     TransferSyntax::<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter>::new_ele(
    ///         "1.3.46.670589.33.1.4.1",
    ///         "CT-Private-ELE",
    ///         Codec::EncapsulatedPixelData(None, None),
    ///     )
    /// }
    /// ```
    ///
    /// See [`submit_ele_transfer_syntax`](crate::submit_ele_transfer_syntax)
    /// for an alternative.
    pub const fn new_ele(uid: &'static str, name: &'static str, codec: Codec<D, R, W>) -> Self {
        TransferSyntax {
            uid,
            name,
            byte_order: Endianness::Little,
            explicit_vr: true,
            codec,
        }
    }

    /// Obtain this transfer syntax' unique identifier.
    pub const fn uid(&self) -> &'static str {
        self.uid
    }

    /// Obtain the name of this transfer syntax.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Obtain this transfer syntax' expected endianness.
    pub const fn endianness(&self) -> Endianness {
        self.byte_order
    }

    /// Obtain this transfer syntax' codec specification.
    pub fn codec(&self) -> &Codec<D, R, W> {
        &self.codec
    }

    /// Check whether this transfer syntax specifier provides a complete
    /// implementation,
    /// meaning that it can both decode and encode in this transfer syntax.
    pub fn is_fully_supported(&self) -> bool {
        matches!(
            self.codec,
            Codec::None | Codec::Dataset(Some(_)) | Codec::EncapsulatedPixelData(Some(_), Some(_)),
        )
    }

    /// Check whether no codecs are required for this transfer syntax,
    /// meaning that a complete implementation is available
    /// and no pixel data conversion is required.
    pub fn is_codec_free(&self) -> bool {
        matches!(self.codec, Codec::None)
    }

    /// Check whether neither reading nor writing of data sets is supported.
    /// If this is `true`, encoding and decoding will not be available.
    pub fn is_unsupported(&self) -> bool {
        matches!(self.codec, Codec::Dataset(None))
    }

    /// Check whether reading and writing the pixel data is unsupported.
    /// If this is `true`, encoding and decoding of the data set may still
    /// be possible, but the pixel data will only be available in its
    /// encapsulated form.
    pub fn is_unsupported_pixel_encapsulation(&self) -> bool {
        matches!(
            self.codec,
            Codec::Dataset(None) | Codec::EncapsulatedPixelData(None, None)
        )
    }

    /// Check whether this codec can fully decode
    /// both data sets and pixel data.
    pub fn can_decode_all(&self) -> bool {
        matches!(
            self.codec,
            Codec::None | Codec::Dataset(Some(_)) | Codec::EncapsulatedPixelData(Some(_), _)
        )
    }

    /// Check whether this codec can decode the data set.
    pub fn can_decode_dataset(&self) -> bool {
        matches!(
            self.codec,
            Codec::None | Codec::Dataset(Some(_)) | Codec::EncapsulatedPixelData(..)
        )
    }

    /// Retrieve the appropriate data element decoder for this transfer syntax.
    /// Can yield none if decoding is not supported.
    ///
    /// The resulting decoder does not consider pixel data encapsulation or
    /// data set compression rules. This means that the consumer of this method
    /// needs to adapt the reader before using the decoder.
    pub fn decoder<'s>(&self) -> Option<DynDecoder<dyn Read + 's>> {
        self.decoder_for()
    }

    /// Retrieve the appropriate data element decoder for this transfer syntax
    /// and given reader type (this method is not object safe).
    /// Can yield none if decoding is not supported.
    ///
    /// The resulting decoder does not consider pixel data encapsulation or
    /// data set compression rules. This means that the consumer of this method
    /// needs to adapt the reader before using the decoder.
    pub fn decoder_for<S>(&self) -> Option<DynDecoder<S>>
    where
        Self: Sized,
        S: ?Sized + Read,
    {
        match (self.byte_order, self.explicit_vr) {
            (Endianness::Little, false) => Some(Box::<ImplicitVRLittleEndianDecoder<_>>::default()),
            (Endianness::Little, true) => Some(Box::<ExplicitVRLittleEndianDecoder>::default()),
            (Endianness::Big, true) => Some(Box::<ExplicitVRBigEndianDecoder>::default()),
            _ => None,
        }
    }

    /// Retrieve the appropriate data element encoder for this transfer syntax.
    /// Can yield none if encoding is not supported. The resulting encoder does not
    /// consider pixel data encapsulation or data set compression rules.
    pub fn encoder<'w>(&self) -> Option<DynEncoder<'w, dyn Write + 'w>> {
        self.encoder_for()
    }

    /// Retrieve the appropriate data element encoder for this transfer syntax
    /// and the given writer type (this method is not object safe).
    /// Can yield none if encoding is not supported. The resulting encoder does not
    /// consider pixel data encapsulation or data set compression rules.
    pub fn encoder_for<'w, T>(&self) -> Option<DynEncoder<'w, T>>
    where
        Self: Sized,
        T: ?Sized + Write + 'w,
    {
        match (self.byte_order, self.explicit_vr) {
            (Endianness::Little, false) => Some(Box::new(EncoderFor::new(
                ImplicitVRLittleEndianEncoder::default(),
            ))),
            (Endianness::Little, true) => Some(Box::new(EncoderFor::new(
                ExplicitVRLittleEndianEncoder::default(),
            ))),
            (Endianness::Big, true) => Some(Box::new(EncoderFor::new(
                ExplicitVRBigEndianEncoder::default(),
            ))),
            _ => None,
        }
    }

    /// Obtain a dynamic basic decoder, based on this transfer syntax' expected endianness.
    pub fn basic_decoder(&self) -> BasicDecoder {
        BasicDecoder::from(self.endianness())
    }

    /// Type-erase the pixel data or data set codec.
    pub fn erased(self) -> TransferSyntax
    where
        D: Send + Sync + 'static,
        D: DataRWAdapter<
            Box<dyn Read>,
            Box<dyn Write>,
            Reader = Box<dyn Read>,
            Writer = Box<dyn Write>,
        >,
        R: Send + Sync + 'static,
        R: PixelDataReader,
        W: Send + Sync + 'static,
        W: PixelDataWriter,
    {
        let codec = match self.codec {
            Codec::Dataset(d) => Codec::Dataset(d.map(|d| Box::new(d) as _)),
            Codec::EncapsulatedPixelData(r, w) => Codec::EncapsulatedPixelData(
                r.map(|r| Box::new(r) as _),
                w.map(|w| Box::new(w) as _),
            ),
            Codec::None => Codec::None,
        };

        TransferSyntax {
            uid: self.uid,
            name: self.name,
            byte_order: self.byte_order,
            explicit_vr: self.explicit_vr,
            codec,
        }
    }
}