dicom-ul 0.9.1

Types and methods for interacting with the DICOM Upper Layer Protocol
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
/// PDU writer module
use crate::pdu::*;
use byteordered::byteorder::{BigEndian, WriteBytesExt};
use dicom_encoding::text::TextCodec;
use snafu::{Backtrace, ResultExt, Snafu};
use std::io::Write;

pub type Error = crate::pdu::WriteError;

pub type Result<T> = std::result::Result<T, WriteError>;

#[derive(Debug, Snafu)]
pub enum WriteChunkError {
    #[snafu(display("Failed to build chunk"))]
    BuildChunk {
        #[snafu(backtrace)]
        source: Box<WriteError>,
    },
    #[snafu(display("Failed to write chunk length"))]
    WriteLength {
        backtrace: Backtrace,
        source: std::io::Error,
    },
    #[snafu(display("Failed to write chunk data"))]
    WriteData {
        backtrace: Backtrace,
        source: std::io::Error,
    },
}

fn write_chunk_u32<F>(writer: &mut dyn Write, func: F) -> std::result::Result<(), WriteChunkError>
where
    F: FnOnce(&mut Vec<u8>) -> Result<()>,
{
    let mut data = vec![];
    func(&mut data)
        .map_err(Box::from)
        .context(BuildChunkSnafu)?;

    let length = data.len() as u32;
    writer
        .write_u32::<BigEndian>(length)
        .context(WriteLengthSnafu)?;

    writer.write_all(&data).context(WriteDataSnafu)?;

    Ok(())
}

fn write_chunk_u16<F>(writer: &mut dyn Write, func: F) -> std::result::Result<(), WriteChunkError>
where
    F: FnOnce(&mut Vec<u8>) -> Result<()>,
{
    let mut data = vec![];
    func(&mut data)
        .map_err(Box::from)
        .context(BuildChunkSnafu)?;

    let length = data.len() as u16;
    writer
        .write_u16::<BigEndian>(length)
        .context(WriteLengthSnafu)?;

    writer.write_all(&data).context(WriteDataSnafu)?;

    Ok(())
}

pub fn write_pdu<W>(writer: &mut W, pdu: &Pdu) -> Result<()>
where
    W: Write,
{
    let codec = dicom_encoding::text::DefaultCharacterSetCodec;
    match pdu {
        Pdu::AssociationRQ(AssociationRQ {
            protocol_version,
            calling_ae_title,
            called_ae_title,
            application_context_name,
            presentation_contexts,
            user_variables,
        }) => {
            // A-ASSOCIATE-RQ PDU Structure

            // 1 - PDU-type - 01H
            writer
                .write_u8(0x01)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not
            // tested to this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                // 7-8  Protocol-version - This two byte field shall use one bit to identify
                // each version of the DICOM UL protocol supported by the calling end-system.
                // This is Version 1 and shall be identified with bit 0 set. A receiver of this
                // PDU implementing only this version of the DICOM UL protocol shall only test
                // that bit 0 is set.
                writer
                    .write_u16::<BigEndian>(*protocol_version)
                    .context(WriteFieldSnafu {
                        field: "Protocol-version",
                    })?;

                // 9-10 - Reserved - This reserved field shall be sent with a value 0000H but
                // not tested to this value when received.
                writer
                    .write_u16::<BigEndian>(0x00)
                    .context(WriteReservedSnafu { bytes: 2_u32 })?;

                // 11-26 - Called-AE-title - Destination DICOM Application Name. It shall be
                // encoded as 16 characters as defined by the ISO 646:1990-Basic G0 Set with
                // leading and trailing spaces (20H) being non-significant. The value made of 16
                // spaces (20H) meaning "no Application Name specified" shall not be used. For a
                // complete description of the use of this field, see Section 7.1.1.4.
                let mut ae_title_bytes =
                    codec.encode(called_ae_title).context(EncodeFieldSnafu {
                        field: "Called-AE-title",
                    })?;
                ae_title_bytes.resize(16, b' ');
                writer.write_all(&ae_title_bytes).context(WriteFieldSnafu {
                    field: "Called-AE-title",
                })?;

                // 27-42 - Calling-AE-title - Source DICOM Application Name. It shall be encoded
                // as 16 characters as defined by the ISO 646:1990-Basic G0 Set with leading and
                // trailing spaces (20H) being non-significant. The value made of 16 spaces
                // (20H) meaning "no Application Name specified" shall not be used. For a
                // complete description of the use of this field, see Section 7.1.1.3.
                let mut ae_title_bytes =
                    codec.encode(calling_ae_title).context(EncodeFieldSnafu {
                        field: "Calling-AE-title",
                    })?;
                ae_title_bytes.resize(16, b' ');
                writer.write_all(&ae_title_bytes).context(WriteFieldSnafu {
                    field: "Called-AE-title",
                })?;

                // 43-74 - Reserved - This reserved field shall be sent with a value 00H for all
                // bytes but not tested to this value when received
                writer
                    .write_all(&[0; 32])
                    .context(WriteReservedSnafu { bytes: 32_u32 })?;

                write_pdu_variable_application_context_name(
                    writer,
                    application_context_name,
                    &codec,
                )?;

                for presentation_context in presentation_contexts {
                    write_pdu_variable_presentation_context_proposed(
                        writer,
                        presentation_context,
                        &codec,
                    )?;
                }

                write_pdu_variable_user_variables(writer, user_variables, &codec)?;

                Ok(())
            })
            .context(WriteChunkSnafu {
                name: "A-ASSOCIATE-RQ",
            })?;

            Ok(())
        }
        Pdu::AssociationAC(AssociationAC {
            protocol_version,
            application_context_name,
            called_ae_title,
            calling_ae_title,
            presentation_contexts,
            user_variables,
        }) => {
            // A-ASSOCIATE-AC PDU Structure

            // 1 - PDU-type - 02H
            writer
                .write_u8(0x02)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to
            // this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                // 7-8 - Protocol-version - This two byte field shall use one bit to identify each
                // version of the DICOM UL protocol supported by the calling end-system. This is
                // Version 1 and shall be identified with bit 0 set. A receiver of this PDU
                // implementing only this version of the DICOM UL protocol shall only test that bit
                // 0 is set.
                writer
                    .write_u16::<BigEndian>(*protocol_version)
                    .context(WriteFieldSnafu {
                        field: "Protocol-version",
                    })?;

                // 9-10 - Reserved - This reserved field shall be sent with a value 0000H but not
                // tested to this value when received.
                writer
                    .write_u16::<BigEndian>(0x00)
                    .context(WriteReservedSnafu { bytes: 2_u32 })?;

                // 11-26 - Reserved - This reserved field shall be sent with a value identical to
                // the value received in the same field of the A-ASSOCIATE-RQ PDU, but its value
                // shall not be tested when received.
                let mut ae_title_bytes =
                    codec.encode(called_ae_title).context(EncodeFieldSnafu {
                        field: "Called-AE-title",
                    })?;
                ae_title_bytes.resize(16, b' ');
                writer.write_all(&ae_title_bytes).context(WriteFieldSnafu {
                    field: "Called-AE-title",
                })?;
                // 27-42 - Reserved - This reserved field shall be sent with a value identical to
                // the value received in the same field of the A-ASSOCIATE-RQ PDU, but its value
                // shall not be tested when received.
                let mut ae_title_bytes =
                    codec.encode(calling_ae_title).context(EncodeFieldSnafu {
                        field: "Calling-AE-title",
                    })?;
                ae_title_bytes.resize(16, b' ');
                writer.write_all(&ae_title_bytes).context(WriteFieldSnafu {
                    field: "Calling-AE-title",
                })?;

                // 43-74 - Reserved - This reserved field shall be sent with a value identical to
                // the value received in the same field of the A-ASSOCIATE-RQ PDU, but its value
                // shall not be tested when received.
                writer
                    .write_all(&[0; 32])
                    .context(WriteReservedSnafu { bytes: 32_u32 })?;

                // 75-xxx - Variable items - This variable field shall contain the following items:
                // one Application Context Item, one or more Presentation Context Item(s) and one
                // User Information Item. For a complete description of these items see Section
                // 7.1.1.2, Section 7.1.1.14, and Section 7.1.1.6.
                write_pdu_variable_application_context_name(
                    writer,
                    application_context_name,
                    &codec,
                )?;

                for presentation_context in presentation_contexts {
                    write_pdu_variable_presentation_context_result(
                        writer,
                        presentation_context,
                        &codec,
                    )?;
                }

                write_pdu_variable_user_variables(writer, user_variables, &codec)?;

                Ok(())
            })
            .context(WriteChunkSnafu {
                name: "A-ASSOCIATE-AC",
            })
        }
        Pdu::AssociationRJ(AssociationRJ { result, source }) => {
            // 1 - PDU-type - 03H
            writer
                .write_u8(0x03)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                // 7 - Reserved - This reserved field shall be sent with a value 00H but not tested to this value when received.
                writer.write_u8(0x00).context(WriteReservedSnafu { bytes: 1_u32 })?;

                // 8 - Result - This Result field shall contain an integer value encoded as an unsigned binary number. One of the following values shall be used:
                // - 1 - rejected-permanent
                // - 2 - rejected-transient
                writer.write_u8(match result {
                    AssociationRJResult::Permanent => {
                        0x01
                    }
                    AssociationRJResult::Transient => {
                        0x02
                    }
                }).context(WriteFieldSnafu { field: "AssociationRJResult" })?;

                // 9 - Source - This Source field shall contain an integer value encoded as an unsigned binary number. One of the following values shall be used:
                // - 1 - DICOM UL service-user
                // - 2 - DICOM UL service-provider (ACSE related function)
                // - 3 - DICOM UL service-provider (Presentation related function)
                // 10 - Reason/Diag - This field shall contain an integer value encoded as an unsigned binary number.
                // If the Source field has the value (1) "DICOM UL service-user", it shall take one of the following:
                // - 1 - no-reason-given
                // - 2 - application-context-name-not-supported
                // - 3 - calling-AE-title-not-recognized
                // - 4-6 - reserved
                // - 7 - called-AE-title-not-recognized
                // - 8-10 - reserved
                // If the Source field has the value (2) "DICOM UL service provided (ACSE related function)", it shall take one of the following:
                // - 1 - no-reason-given
                // - 2 - protocol-version-not-supported
                // If the Source field has the value (3) "DICOM UL service provided (Presentation related function)", it shall take one of the following:
                // 0 - reserved
                // 1 - temporary-congestion
                // 2 - local-limit-exceeded
                // 3-7 - reserved
                match source {
                    AssociationRJSource::ServiceUser(reason) => {
                        writer.write_u8(0x01).context(WriteFieldSnafu { field: "AssociationRJServiceUserReason" })?;
                        writer.write_u8(match reason {
                            AssociationRJServiceUserReason::NoReasonGiven => {
                                0x01
                            }
                            AssociationRJServiceUserReason::ApplicationContextNameNotSupported => {
                                0x02
                            }
                            AssociationRJServiceUserReason::CallingAETitleNotRecognized => {
                                0x03
                            }
                            AssociationRJServiceUserReason::CalledAETitleNotRecognized => {
                                0x07
                            }
                            AssociationRJServiceUserReason::Reserved(data) => {
                                *data
                            }
                        }).context(WriteFieldSnafu { field: "AssociationRJServiceUserReason (2)" })?;
                    }
                    AssociationRJSource::ServiceProviderASCE(reason) => {
                        writer.write_u8(0x02).context(WriteFieldSnafu { field: "AssociationRJServiceProvider" })?;
                        writer.write_u8(match reason {
                            AssociationRJServiceProviderASCEReason::NoReasonGiven => {
                                0x01
                            }
                            AssociationRJServiceProviderASCEReason::ProtocolVersionNotSupported => {
                                0x02
                            }
                        }).context(WriteFieldSnafu { field: "AssociationRJServiceProvider (2)" })?;
                    }
                    AssociationRJSource::ServiceProviderPresentation(reason) => {
                        writer.write_u8(0x03).context(WriteFieldSnafu { field: "AssociationRJServiceProviderPresentationReason" })?;
                        writer.write_u8(match reason {
                            AssociationRJServiceProviderPresentationReason::TemporaryCongestion => {
                                0x01
                            }
                            AssociationRJServiceProviderPresentationReason::LocalLimitExceeded => {
                                0x02
                            }
                            AssociationRJServiceProviderPresentationReason::Reserved(data) => {
                                *data
                            }
                        }).context(WriteFieldSnafu { field: "AssociationRJServiceProviderPresentationReason (2)" })?;
                    }
                }

                Ok(())
            }).context(WriteChunkSnafu { name: "AssociationRJ" })?;

            Ok(())
        }
        Pdu::PData { data } => {
            // 1 - PDU-type - 04H
            writer
                .write_u8(0x04)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to
            // this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                // 7-xxx - Presentation-data-value Item(s) - This variable data field shall contain
                // one or more Presentation-data-value Items(s). For a complete description of the
                // use of this field see Section 9.3.5.1

                for presentation_data_value in data {
                    write_chunk_u32(writer, |writer| {
                        // 5 - Presentation-context-ID - Presentation-context-ID values shall be odd
                        // integers between 1 and 255, encoded as an unsigned binary number. For a
                        // complete description of the use of this field see Section 7.1.1.13.
                        writer.push(presentation_data_value.presentation_context_id);

                        // 6-xxx - Presentation-data-value - This Presentation-data-value field
                        // shall contain DICOM message information (command and/or data set) with a
                        // message control header. For a complete description of the use of this
                        // field see Annex E.

                        // The Message Control Header shall be made of one byte with the least
                        // significant bit (bit 0) taking one of the following values:
                        // - If bit 0 is set to 1, the following fragment shall contain Message
                        //   Command information.
                        // - If bit 0 is set to 0, the following fragment shall contain Message Data
                        //   Set information.
                        // The next least significant bit (bit 1) shall be defined by the following
                        // rules: If bit 1 is set to 1, the following fragment shall contain the
                        // last fragment of a Message Data Set or of a Message Command.
                        // - If bit 1 is set to 0, the following fragment does not contain the last
                        //   fragment of a Message Data Set or of a Message Command.
                        let mut message_header = 0x00;
                        if let PDataValueType::Command = presentation_data_value.value_type {
                            message_header |= 0x01;
                        }
                        if presentation_data_value.is_last {
                            message_header |= 0x02;
                        }
                        writer.push(message_header);

                        // Message fragment
                        writer.extend(&presentation_data_value.data);

                        Ok(())
                    })
                    .context(WriteChunkSnafu {
                        name: "Presentation-data-value item",
                    })?;
                }

                Ok(())
            })
            .context(WriteChunkSnafu { name: "PData" })
        }
        Pdu::ReleaseRQ => {
            // 1 - PDU-type - 05H
            writer
                .write_u8(0x05)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to
            // this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                writer.extend([0u8; 4]);
                Ok(())
            })
            .context(WriteChunkSnafu { name: "ReleaseRQ" })?;

            Ok(())
        }
        Pdu::ReleaseRP => {
            // 1 - PDU-type - 06H
            writer
                .write_u8(0x06)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to
            // this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                writer.extend([0u8; 4]);
                Ok(())
            })
            .context(WriteChunkSnafu { name: "ReleaseRP" })?;

            Ok(())
        }
        Pdu::AbortRQ { source } => {
            // 1 - PDU-type - 07H
            writer
                .write_u8(0x07)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to
            // this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                // 7 - Reserved - This reserved field shall be sent with a value 00H but not tested
                // to this value when received.
                writer.push(0);
                // 8 - Reserved - This reserved field shall be sent with a value 00H but not tested
                // to this value when received.
                writer.push(0);

                // 9 - Source - This Source field shall contain an integer value encoded as an
                // unsigned binary number. One of the following values shall be used:
                // - 0 - DICOM UL service-user (initiated abort)
                // - 1 - reserved
                // - 2 - DICOM UL service-provider (initiated abort)
                // 10 - Reason/Diag - This field shall contain an integer value encoded as an
                // unsigned binary number. If the Source field has the value (2) "DICOM UL
                // service-provider", it shall take one of the following:
                // - 0 - reason-not-specified1 - unrecognized-PDU
                // - 2 - unexpected-PDU
                // - 3 - reserved
                // - 4 - unrecognized-PDU parameter
                // - 5 - unexpected-PDU parameter
                // - 6 - invalid-PDU-parameter value
                // If the Source field has the value (0) "DICOM UL service-user", this reason field
                // shall not be significant. It shall be sent with a value 00H but not tested to
                // this value when received.
                let source_word = match source {
                    AbortRQSource::ServiceUser => [0x00; 2],
                    AbortRQSource::Reserved => [0x01, 0x00],
                    AbortRQSource::ServiceProvider(reason) => match reason {
                        AbortRQServiceProviderReason::ReasonNotSpecified => [0x02, 0x00],
                        AbortRQServiceProviderReason::UnrecognizedPdu => [0x02, 0x01],
                        AbortRQServiceProviderReason::UnexpectedPdu => [0x02, 0x02],
                        AbortRQServiceProviderReason::Reserved => [0x02, 0x03],
                        AbortRQServiceProviderReason::UnrecognizedPduParameter => [0x02, 0x04],
                        AbortRQServiceProviderReason::UnexpectedPduParameter => [0x02, 0x05],
                        AbortRQServiceProviderReason::InvalidPduParameter => [0x02, 0x06],
                    },
                };
                writer.extend(source_word);

                Ok(())
            })
            .context(WriteChunkSnafu { name: "AbortRQ" })?;

            Ok(())
        }
        Pdu::Unknown { pdu_type, data } => {
            // 1 - PDU-type - XXH
            writer
                .write_u8(*pdu_type)
                .context(WriteFieldSnafu { field: "PDU-type" })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to
            // this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u32(writer, |writer| {
                writer.extend(data);
                Ok(())
            })
            .context(WriteChunkSnafu { name: "Unknown" })?;

            Ok(())
        }
    }
}

fn write_pdu_variable_application_context_name(
    writer: &mut dyn Write,
    application_context_name: &str,
    codec: &dyn TextCodec,
) -> Result<()> {
    // Application Context Item Structure
    // 1 - Item-type - 10H
    writer
        .write_u8(0x10)
        .context(WriteFieldSnafu { field: "Item-type" })?;

    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
    // tested to this value when received.
    writer
        .write_u8(0x00)
        .context(WriteReservedSnafu { bytes: 1_u32 })?;

    write_chunk_u16(writer, |writer| {
        // 5-xxx - Application-context-name -A valid Application-context-name shall
        // be encoded as defined in Annex F. For a description of the use of this
        // field see Section 7.1.1.2. Application-context-names are structured as
        // UIDs as defined in PS3.5 (see Annex A for an overview of this concept).
        // DICOM Application-context-names are registered in PS3.7.
        writer
            .write_all(
                &codec
                    .encode(application_context_name)
                    .context(EncodeFieldSnafu {
                        field: "Application-context-name",
                    })?,
            )
            .context(WriteFieldSnafu {
                field: "Application-context-name",
            })
    })
    .context(WriteChunkSnafu {
        name: "Application Context Item",
    })?;

    Ok(())
}

fn write_pdu_variable_presentation_context_proposed(
    writer: &mut dyn Write,
    presentation_context: &PresentationContextProposed,
    codec: &dyn TextCodec,
) -> Result<()> {
    // Presentation Context Item Structure
    // 1 - tem-type - 20H
    writer
        .write_u8(0x20)
        .context(WriteFieldSnafu { field: "Item-type" })?;

    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
    // tested to this value when received.
    writer
        .write_u8(0x00)
        .context(WriteReservedSnafu { bytes: 1_u32 })?;

    write_chunk_u16(writer, |writer| {
        // 5 - Presentation-context-ID - Presentation-context-ID values shall be
        // odd integers between 1 and 255, encoded as an unsigned binary number.
        // For a complete description of the use of this field see Section
        // 7.1.1.13.
        writer
            .write_u8(presentation_context.id)
            .context(WriteFieldSnafu {
                field: "Presentation-context-ID",
            })?;

        // 6 - Reserved - This reserved field shall be sent with a value 00H but
        // not tested to this value when received.
        writer
            .write_u8(0x00)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        // 7 - Reserved - This reserved field shall be sent with a value 00H but
        // not tested to this value when received
        writer
            .write_u8(0x00)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        // 8 - Reserved - This reserved field shall be sent with a value 00H but
        // not tested to this value when received.
        writer
            .write_u8(0x00)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        // 9-xxx - Abstract/Transfer Syntax Sub-Items - This variable field
        // shall contain the following sub-items: one Abstract Syntax and one or
        // more Transfer Syntax(es). For a complete description of the use and
        // encoding of these sub-items see Section 9.3.2.2.1 and Section
        // 9.3.2.2.2.

        // Abstract Syntax Sub-Item Structure
        // 1 - Item-type 30H
        writer
            .write_u8(0x30)
            .context(WriteFieldSnafu { field: "Item-type" })?;

        // 2 - Reserved - This reserved field shall be sent with a value 00H
        // but not tested to this value when
        // received.
        writer
            .write_u8(0x00)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        write_chunk_u16(writer, |writer| {
            // 5-xxx - Abstract-syntax-name - This variable field shall
            // contain
            // the Abstract-syntax-name related to the proposed presentation
            // context. A valid Abstract-syntax-name shall be encoded as
            // defined in Annex F. For a
            // description of the use of this field see
            // Section 7.1.1.13. Abstract-syntax-names are structured as
            // UIDs as defined in PS3.5
            // (see Annex B for an overview of this concept).
            // DICOM Abstract-syntax-names are registered in PS3.4.
            writer
                .write_all(
                    &codec
                        .encode(&presentation_context.abstract_syntax)
                        .context(EncodeFieldSnafu {
                            field: "Abstract-syntax-name",
                        })?,
                )
                .context(WriteFieldSnafu {
                    field: "Abstract-syntax-name",
                })
        })
        .context(WriteChunkSnafu {
            name: "Abstract Syntax Item",
        })?;

        for transfer_syntax in &presentation_context.transfer_syntaxes {
            // Transfer Syntax Sub-Item Structure
            // 1 - Item-type - 40H
            writer.write_u8(0x40).context(WriteFieldSnafu {
                field: "Presentation-context Item-type",
            })?;

            // 2 - Reserved - This reserved field shall be sent with a value 00H
            // but not tested to this value when received.
            writer
                .write_u8(0x00)
                .context(WriteReservedSnafu { bytes: 1_u32 })?;

            write_chunk_u16(writer, |writer| {
                // 5-xxx - Transfer-syntax-name(s) - This variable field shall
                // contain the Transfer-syntax-name proposed for this
                // presentation context. A valid Transfer-syntax-name shall be
                // encoded as defined in Annex F. For a description of the use
                // of this field see Section 7.1.1.13. Transfer-syntax-names are
                // structured as UIDs as defined in PS3.5 (see Annex B for an
                // overview of this concept). DICOM Transfer-syntax-names are
                // registered in PS3.5.
                writer
                    .write_all(&codec.encode(transfer_syntax).context(EncodeFieldSnafu {
                        field: "Transfer-syntax-name",
                    })?)
                    .context(WriteFieldSnafu {
                        field: "Transfer-syntax-name",
                    })
            })
            .context(WriteChunkSnafu {
                name: "Transfer Syntax Sub-Item",
            })?;
        }

        Ok(())
    })
    .context(WriteChunkSnafu {
        name: "Presentation Context Item",
    })?;

    Ok(())
}

fn write_pdu_variable_presentation_context_result(
    writer: &mut dyn Write,
    presentation_context: &PresentationContextResult,
    codec: &dyn TextCodec,
) -> Result<()> {
    // 1 - Item-type - 21H
    writer
        .write_u8(0x21)
        .context(WriteFieldSnafu { field: "Item-type" })?;

    // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to this
    // value when received.
    writer
        .write_u8(0x00)
        .context(WriteReservedSnafu { bytes: 1_u32 })?;

    write_chunk_u16(writer, |writer| {
        // 5 - Presentation-context-ID - Presentation-context-ID values shall be odd integers
        // between 1 and 255, encoded as an unsigned binary number. For a complete description of
        // the use of this field see Section 7.1.1.13.
        writer
            .write_u8(presentation_context.id)
            .context(WriteFieldSnafu {
                field: "Presentation-context-ID",
            })?;

        // 6 - Reserved - This reserved field shall be sent with a value 00H but not tested to this
        // value when received.
        writer
            .write_u8(0x00)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        // 7 - Result/Reason - This Result/Reason field shall contain an integer value encoded as an
        // unsigned binary number. One of the following values shall be used:
        //   0 - acceptance
        //   1 - user-rejection
        //   2 - no-reason (provider rejection)
        //   3 - abstract-syntax-not-supported (provider rejection)
        //   4 - transfer-syntaxes-not-supported (provider rejection)
        writer
            .write_u8(match &presentation_context.reason {
                PresentationContextResultReason::Acceptance => 0,
                PresentationContextResultReason::UserRejection => 1,
                PresentationContextResultReason::NoReason => 2,
                PresentationContextResultReason::AbstractSyntaxNotSupported => 3,
                PresentationContextResultReason::TransferSyntaxesNotSupported => 4,
            })
            .context(WriteFieldSnafu {
                field: "Presentation Context Result/Reason",
            })?;

        // 8 - Reserved - This reserved field shall be sent with a value 00H but not tested to this
        // value when received.
        writer
            .write_u8(0x00)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        // 9-xxx - Transfer syntax sub-item - This variable field shall contain one Transfer Syntax
        // Sub-Item. When the Result/Reason field has a value other than acceptance (0), this field
        // shall not be significant and its value shall not be tested when received. For a complete
        // description of the use and encoding of this item see Section 9.3.3.2.1.

        // 1 - Item-type - 40H
        writer
            .write_u8(0x40)
            .context(WriteFieldSnafu { field: "Item-type" })?;

        // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to this
        // value when received.
        writer
            .write_u8(0x40)
            .context(WriteReservedSnafu { bytes: 1_u32 })?;

        write_chunk_u16(writer, |writer| {
            // 5-xxx - Transfer-syntax-name - This variable field shall contain the
            // Transfer-syntax-name proposed for this presentation context. A valid
            // Transfer-syntax-name shall be encoded as defined in Annex F. For a description of the
            // use of this field see Section 7.1.1.14. Transfer-syntax-names are structured as UIDs
            // as defined in PS3.5 (see Annex B for an overview of this concept). DICOM
            // Transfer-syntax-names are registered in PS3.5.
            writer
                .write_all(
                    &codec
                        .encode(&presentation_context.transfer_syntax)
                        .context(EncodeFieldSnafu {
                            field: "Transfer-syntax-name",
                        })?,
                )
                .context(WriteFieldSnafu {
                    field: "Transfer-syntax-name",
                })?;

            Ok(())
        })
        .context(WriteChunkSnafu {
            name: "Transfer Syntax sub-item",
        })?;

        Ok(())
    })
    .context(WriteChunkSnafu {
        name: "Presentation-context",
    })
}

fn write_pdu_variable_user_variables(
    writer: &mut dyn Write,
    user_variables: &[UserVariableItem],
    codec: &dyn TextCodec,
) -> Result<()> {
    if user_variables.is_empty() {
        return Ok(());
    }

    // 1 - Item-type - 50H
    writer
        .write_u8(0x50)
        .context(WriteFieldSnafu { field: "Item-type" })?;

    // 2 - Reserved - This reserved field shall be sent with a value 00H but not tested to this
    // value when received.
    writer
        .write_u8(0x00)
        .context(WriteReservedSnafu { bytes: 1_u32 })?;

    write_chunk_u16(writer, |writer| {
        // 5-xxx - User-data - This variable field shall contain User-data sub-items as defined by
        // the DICOM Application Entity. The structure and content of these sub-items is defined in
        // Annex D.
        for user_variable in user_variables {
            match user_variable {
                UserVariableItem::MaxLength(max_length) => {
                    // 1 - Item-type - 51H
                    writer
                        .write_u8(0x51)
                        .context(WriteFieldSnafu { field: "Item-type" })?;

                    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
                    // tested to this value when received.
                    writer
                        .write_u8(0x00)
                        .context(WriteReservedSnafu { bytes: 1_u32 })?;

                    write_chunk_u16(writer, |writer| {
                        // 5-8 - Maximum-length-received - This parameter allows the
                        // association-requestor to restrict the maximum length of the variable
                        // field of the P-DATA-TF PDUs sent by the acceptor on the association once
                        // established. This length value is indicated as a number of bytes encoded
                        // as an unsigned binary number. The value of (0) indicates that no maximum
                        // length is specified. This maximum length value shall never be exceeded by
                        // the PDU length values used in the PDU-length field of the P-DATA-TF PDUs
                        // received by the association-requestor. Otherwise, it shall be a protocol
                        // error.
                        writer
                            .write_u32::<BigEndian>(*max_length)
                            .context(WriteFieldSnafu {
                                field: "Maximum-length-received",
                            })
                    })
                    .context(WriteChunkSnafu {
                        name: "Maximum-length-received",
                    })?;
                }
                UserVariableItem::ImplementationVersionName(implementation_version_name) => {
                    // 1 - Item-type - 55H
                    writer
                        .write_u8(0x55)
                        .context(WriteFieldSnafu { field: "Item-type" })?;

                    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
                    // tested to this value when received.
                    writer
                        .write_u8(0x00)
                        .context(WriteReservedSnafu { bytes: 1_u32 })?;

                    write_chunk_u16(writer, |writer| {
                        // 5 - xxx - Implementation-version-name - This variable field shall contain
                        // the Implementation-version-name of the Association-acceptor as defined in
                        // Section D.3.3.2. It shall be encoded as a string of 1 to 16 ISO 646:1990
                        // (basic G0 set) characters.
                        writer
                            .write_all(&codec.encode(implementation_version_name).context(
                                EncodeFieldSnafu {
                                    field: "Implementation-version-name",
                                },
                            )?)
                            .context(WriteFieldSnafu {
                                field: "Implementation-version-name",
                            })
                    })
                    .context(WriteChunkSnafu {
                        name: "Implementation-version-name",
                    })?;
                }
                UserVariableItem::ImplementationClassUID(implementation_class_uid) => {
                    // 1 - Item-type - 52H
                    writer
                        .write_u8(0x52)
                        .context(WriteFieldSnafu { field: "Item-type" })?;

                    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
                    // tested to this value when received.
                    writer
                        .write_u8(0x00)
                        .context(WriteReservedSnafu { bytes: 1_u32 })?;

                    write_chunk_u16(writer, |writer| {
                        //5 - xxx - Implementation-class-uid - This variable field shall contain
                        // the Implementation-class-uid of the Association-acceptor as defined in
                        // Section D.3.3.2. The Implementation-class-uid field is structured as a
                        // UID as defined in PS3.5.
                        writer
                            .write_all(&codec.encode(implementation_class_uid).context(
                                EncodeFieldSnafu {
                                    field: "Implementation-class-uid",
                                },
                            )?)
                            .context(WriteFieldSnafu {
                                field: "Implementation-class-uid",
                            })
                    })
                    .context(WriteChunkSnafu {
                        name: "Implementation-class-uid",
                    })?;
                }
                UserVariableItem::SopClassExtendedNegotiationSubItem(sop_class_uid, data) => {
                    // 1 - Item-type - 56H
                    writer
                        .write_u8(0x56)
                        .context(WriteFieldSnafu { field: "Item-type" })?;
                    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
                    // tested to this value when received.
                    writer
                        .write_u8(0x00)
                        .context(WriteReservedSnafu { bytes: 1_u32 })?;

                    write_chunk_u16(writer, |writer| {
                        write_chunk_u16(writer, |writer| {
                            //  7-xxx - The SOP Class or Meta SOP Class identifier encoded as a UID
                            //  as defined in Section 9 “Unique Identifiers (UIDs)” in PS3.5.
                            writer
                                .write_all(&codec.encode(sop_class_uid).context(
                                    EncodeFieldSnafu {
                                        field: "SOP-class-uid",
                                    },
                                )?)
                                .context(WriteFieldSnafu {
                                    field: "SOP-class-uid",
                                })
                        })
                        .context(WriteChunkSnafu {
                            name: "SOP-class-uid",
                        })?;

                        // xxx-xxx Service-class-application-information - This field shall contain
                        // the application information specific to the Service Class specification
                        // identified by the SOP-class-uid. The semantics and value of this field is
                        // defined in the identified Service Class specification.
                        writer.write_all(data).context(WriteFieldSnafu {
                            field: "Service-class-application-information",
                        })
                    })
                    .context(WriteChunkSnafu { name: "Sub-item" })?;
                }
                UserVariableItem::UserIdentityItem(user_identity) => {
                    // 1 - Item-type - 58H
                    writer
                        .write_u8(0x58)
                        .context(WriteFieldSnafu { field: "Item-type" })?;

                    // 2 - Reserved - This reserved field shall be sent with a value 00H but not
                    // tested to this value when received.
                    writer
                        .write_u8(0x00)
                        .context(WriteReservedSnafu { bytes: 1_u32 })?;

                    // 3-4 - Item-length
                    write_chunk_u16(writer, |writer| {
                        // 5 - User-Identity-Type
                        writer
                            .write_u8(user_identity.identity_type().to_u8())
                            .context(WriteFieldSnafu {
                                field: "User-Identity-Type",
                            })?;

                        // 6 - Positive-response-requested
                        let positive_response_requested_out: u8 =
                            if user_identity.positive_response_requested() {
                                1
                            } else {
                                0
                            };
                        writer.write_u8(positive_response_requested_out).context(
                            WriteFieldSnafu {
                                field: "Positive-response-requested",
                            },
                        )?;

                        // 7-8 - Primary-field-length
                        write_chunk_u16(writer, |writer| {
                            // 9-n - Primary-field
                            writer
                                .write_all(user_identity.primary_field().as_slice())
                                .context(WriteFieldSnafu {
                                    field: "Primary-field",
                                })
                        })
                        .context(WriteChunkSnafu {
                            name: "Primary-field",
                        })?;

                        // n+1-n+2 - Secondary-field-length
                        write_chunk_u16(writer, |writer| {
                            // n+3-m - Secondary-field
                            writer
                                .write_all(user_identity.secondary_field().as_slice())
                                .context(WriteFieldSnafu {
                                    field: "Secondary-field",
                                })
                        })
                        .context(WriteChunkSnafu {
                            name: "Secondary-field",
                        })
                    })
                    .context(WriteChunkSnafu {
                        name: "Item-length",
                    })?;
                }
                UserVariableItem::Unknown(item_type, data) => {
                    writer
                        .write_u8(*item_type)
                        .context(WriteFieldSnafu { field: "Item-type" })?;

                    writer
                        .write_u8(0x00)
                        .context(WriteReservedSnafu { bytes: 1_u32 })?;

                    write_chunk_u16(writer, |writer| {
                        writer.write_all(data).context(WriteFieldSnafu {
                            field: "Unknown Data",
                        })
                    })
                    .context(WriteChunkSnafu { name: "Unknown" })?;
                }
            }
        }

        Ok(())
    })
    .context(WriteChunkSnafu { name: "User-data" })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn can_write_chunks_with_preceding_u32_length() -> Result<()> {
        let mut bytes = vec![0u8; 0];
        write_chunk_u32(&mut bytes, |writer| {
            writer
                .write_u8(0x02)
                .context(WriteFieldSnafu { field: "Field1" })?;
            write_chunk_u32(writer, |writer| {
                writer
                    .write_u8(0x03)
                    .context(WriteFieldSnafu { field: "Field2" })?;
                Ok(())
            })
            .context(WriteChunkSnafu { name: "Chunk2" })
        })
        .context(WriteChunkSnafu { name: "Chunk1" })?;

        assert_eq!(bytes.len(), 10);
        assert_eq!(bytes, &[0, 0, 0, 6, 2, 0, 0, 0, 1, 3]);

        Ok(())
    }

    #[test]
    fn can_write_chunks_with_preceding_u16_length() -> Result<()> {
        let mut bytes = vec![0u8; 0];
        write_chunk_u16(&mut bytes, |writer| {
            writer
                .write_u8(0x02)
                .context(WriteFieldSnafu { field: "Field1" })?;
            write_chunk_u16(writer, |writer| {
                writer
                    .write_u8(0x03)
                    .context(WriteFieldSnafu { field: "Field2" })?;
                Ok(())
            })
            .context(WriteChunkSnafu { name: "Chunk2" })
        })
        .context(WriteChunkSnafu { name: "Chunk1" })?;

        assert_eq!(bytes.len(), 6);
        assert_eq!(bytes, &[0, 4, 2, 0, 1, 3]);

        Ok(())
    }

    #[test]
    fn write_abort_rq() {
        let mut out = vec![];

        // abort by request of SCU
        let pdu = Pdu::AbortRQ {
            source: AbortRQSource::ServiceUser,
        };
        write_pdu(&mut out, &pdu).unwrap();
        assert_eq!(
            &out,
            &[
                // code 7 + reserved byte
                0x07, 0x00, //
                // PDU length: 4 bytes
                0x00, 0x00, 0x00, 0x04, //
                // reserved 2 bytes + source: service user (0) + reason (0)
                0x00, 0x00, 0x00, 0x00,
            ]
        );
        out.clear();

        // Reserved
        let pdu = Pdu::AbortRQ {
            source: AbortRQSource::Reserved,
        };
        write_pdu(&mut out, &pdu).unwrap();
        assert_eq!(
            &out,
            &[
                // code 7 + reserved byte
                0x07, 0x00, //
                // PDU length: 4 bytes
                0x00, 0x00, 0x00, 0x04, //
                // reserved 2 bytes + source: reserved (1) + reason (0)
                0x00, 0x00, 0x01, 0x00,
            ]
        );
        out.clear();

        // abort by request of SCP
        let pdu = Pdu::AbortRQ {
            source: AbortRQSource::ServiceProvider(
                AbortRQServiceProviderReason::InvalidPduParameter,
            ),
        };
        write_pdu(&mut out, &pdu).unwrap();
        assert_eq!(
            &out,
            &[
                // code 7 + reserved byte
                0x07, 0x00, //
                // PDU length: 4 bytes
                0x00, 0x00, 0x00, 0x04, //
                // reserved 2 bytes
                0x00, 0x00, //
                // source: service provider (2), invalid parameter value (6)
                0x02, 0x06,
            ]
        );
    }

    #[test]
    fn extended_negotiation_bytestream_roundtrip() -> Result<()> {
        let pdu = Pdu::AssociationRQ(AssociationRQ {
            protocol_version: 1,
            calling_ae_title: "SCU".to_string(),
            called_ae_title: "SCP".to_string(),
            application_context_name: "1.2.3".to_string(),
            presentation_contexts: vec![],
            user_variables: vec![UserVariableItem::SopClassExtendedNegotiationSubItem(
                "1.2.3.4".to_string(),
                vec![1, 0, 1, 1],
            )],
        });
        let mut out = Vec::<u8>::new();

        // Serialize and check serialized stream
        write_pdu(&mut out, &pdu)?;

        #[rustfmt::skip]
        assert_eq!(
            out,
            &[1, 0,             // A-ASSOCIATE-RQ PDU type and reserved byte
            0, 0, 0, 98,        // PDU Total length (Big Endian)
                0, 1,           // Protocol version bits (BE)
                0, 0,           // Reserved

                // Called AE Title, space-padded
                b'S', b'C', b'P', b' ', b' ', b' ', b' ', b' ',
                b' ', b' ', b' ', b' ', b' ', b' ', b' ', b' ',

                // Calling AE Title, space-padded
                b'S', b'C', b'U', b' ', b' ', b' ', b' ', b' ',
                b' ', b' ', b' ', b' ', b' ', b' ', b' ', b' ',

                // 32 reserved bytes
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

                0x10, 0,            // Application Context Name container
                    0, 5,           // Length of Application Context Name (BE)
                    b'1', b'.', b'2', b'.', b'3',  // Application Context Name

                0x50, 0,            // User Variables container
                    0, 17,          // Total length of User Variables (BE)
                        0x56, 0,    // Extended Negotiation container
                        0, 13,      // Length of bytes contained in E.N. (BE)
                            0, 7,   // Length of SOP Class UID string (BE)
                                // SOP Class UID string
                                b'1', b'.', b'2', b'.', b'3', b'.', b'4',
                            // Service-class-application-information field
                            1, 0, 1, 1,
            ],
        );

        // Deserialize and check against original A-ASSOCIATE-RQ PDU
        // (checks that it round-trips)
        let mut buf = Cursor::new(&mut out);
        let pdu2 = read_pdu(&mut buf, 16384, false).unwrap().unwrap();
        assert_eq!(pdu, pdu2);

        Ok(())
    }
}