bacnet-encoding 0.13.0

BACnet ASN.1/BER encoding, APDU and NPDU codecs per ASHRAE 135-2020
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
//! APDU encoding and decoding per ASHRAE 135-2020 Clause 20.1.
//!
//! Covers all eight PDU types:
//! - [`ConfirmedRequest`] (Clause 20.1.2)
//! - [`UnconfirmedRequest`] (Clause 20.1.3)
//! - [`SimpleAck`] (Clause 20.1.4)
//! - [`ComplexAck`] (Clause 20.1.5)
//! - [`SegmentAck`] (Clause 20.1.6)
//! - [`ErrorPdu`] (Clause 20.1.7)
//! - [`RejectPdu`] (Clause 20.1.8)
//! - [`AbortPdu`] (Clause 20.1.9)

use bacnet_types::enums::{
    AbortReason, ConfirmedServiceChoice, ErrorClass, ErrorCode, PduType, RejectReason,
    UnconfirmedServiceChoice,
};
use bacnet_types::error::Error;
use bytes::{BufMut, Bytes, BytesMut};

use crate::primitives;
use crate::tags;

mod formal_error;

// ---------------------------------------------------------------------------
// Max-segments encoding
// ---------------------------------------------------------------------------

/// Decoded max-segments values indexed by the 3-bit field (0-7).
/// `None` means unspecified (0).
const MAX_SEGMENTS_DECODE: [Option<u8>; 8] = [
    None,      // 0 = unspecified
    Some(2),   // 1
    Some(4),   // 2
    Some(8),   // 3
    Some(16),  // 4
    Some(32),  // 5
    Some(64),  // 6
    Some(255), // 7 = >64 segments accepted
];

/// Validate a configured maximum segment count for a Confirmed-Request header.
///
/// Clause 20.1.2.4 has no encoding for a finite capacity below two segments.
/// To decline segmented responses, set `segmented-response-accepted = false`
/// and use `None` rather than `Some(1)`.
pub fn validate_max_segments(value: Option<u8>) -> Result<(), Error> {
    match value {
        Some(value @ 0..=1) => Err(Error::Encoding(format!(
            "invalid max-segments-accepted {value}; expected 2..=255 or unspecified"
        ))),
        _ => Ok(()),
    }
}

/// Encode a max-segments value to a 3-bit field.
///
/// Finite counts that fall between the Clause 20.1.2.4 rungs are rounded down
/// so the wire header never promises more receive capacity than configured.
fn encode_max_segments(value: Option<u8>) -> Result<u8, Error> {
    validate_max_segments(value)?;
    Ok(match value {
        None => 0,
        Some(2..=3) => 1,
        Some(4..=7) => 2,
        Some(8..=15) => 3,
        Some(16..=31) => 4,
        Some(32..=63) => 5,
        Some(64) => 6,
        Some(65..=u8::MAX) => 7, // >64
        Some(0..=1) => unreachable!("validated above"),
    })
}

/// Decode a 3-bit max-segments field.
fn decode_max_segments(value: u8) -> Option<u8> {
    MAX_SEGMENTS_DECODE[(value & 0x07) as usize]
}

/// The segment count a configured `max-segments-accepted` actually promises a peer.
///
/// Clause 20.1.2.4 carries this parameter in three bits, and only B'001'
/// through B'110' name a number (2, 4, 8, 16, 32, 64). B'000' leaves capacity
/// unspecified; B'111' advertises capacity above 64 without an upper bound.
/// Neither tells the peer a limit, so both yield `None`.
///
/// This deliberately round-trips through the wire encoding rather than reading
/// `configured` directly: a value such as `Some(100)` encodes as B'111', so the
/// peer was told only that capacity exceeds 64, not that it is 100. Answering
/// from the configured number would claim a promise that was never sent.
/// Invalid finite capacities below two yield `None`; APDU encoding and client
/// startup reject those values through [`validate_max_segments`].
pub fn advertised_max_segments(configured: Option<u8>) -> Option<u8> {
    let encoded = encode_max_segments(configured).ok()?;
    match decode_max_segments(encoded) {
        // B'111' advertises capacity above 64, not a specific upper bound.
        Some(255) => None,
        decoded => decoded,
    }
}

// ---------------------------------------------------------------------------
// Max-APDU-length encoding
// ---------------------------------------------------------------------------

/// MinimumMessageSize: the smallest APDU any BACnet device accepts.
///
/// Clause 20.1.2.5 assigns the lowest max-APDU-length-accepted code, `B'0000'`,
/// to the 50-octet MinimumMessageSize capacity. Clause 12.11.18 sets the same
/// floor for `Max_APDU_Length_Accepted`, as does Clause 5.2.1.2 for a remote
/// peer's receive capacity.
pub const MINIMUM_MESSAGE_SIZE: u16 = 50;

/// Decoded max-APDU-length values indexed by the 4-bit field.
const MAX_APDU_DECODE: [u16; 6] = [MINIMUM_MESSAGE_SIZE, 128, 206, 480, 1024, 1476];

/// Floor a raw local receive capacity to a Confirmed-Request header value.
///
/// Device `Max_APDU_Length_Accepted` and I-Am retain the raw unsigned value.
/// Only the Clause 20.1.2.5 header uses this six-code representation; flooring
/// must not change byte budgets or the Device declaration. Values below
/// MinimumMessageSize are invalid, while larger values saturate at 1476.
pub fn max_apdu_header_at_or_below(capacity: u32) -> Result<u16, Error> {
    MAX_APDU_DECODE
        .iter()
        .rev()
        .copied()
        .find(|value| u32::from(*value) <= capacity)
        .ok_or_else(|| Error::Encoding(format!("local APDU capacity {capacity} is below 50")))
}

/// Return true when `value` is one of the BACnet max-APDU-length encodings
/// defined by ASHRAE 135-2020 Clause 20.1.2.5.
pub fn is_valid_max_apdu_length(value: u16) -> bool {
    matches!(value, 50 | 128 | 206 | 480 | 1024 | 1476)
}

/// Validate an exact Confirmed-Request max-APDU-length header value.
pub fn validate_max_apdu_length(value: u16) -> Result<(), Error> {
    if is_valid_max_apdu_length(value) {
        Ok(())
    } else {
        Err(Error::Encoding(format!(
            "invalid max-APDU-length {value}; expected one of 50, 128, 206, 480, 1024, 1476"
        )))
    }
}

/// Encode a max-APDU-length to a 4-bit field.
fn encode_max_apdu(value: u16) -> Result<u8, Error> {
    validate_max_apdu_length(value)?;
    match value {
        50 => Ok(0),
        128 => Ok(1),
        206 => Ok(2),
        480 => Ok(3),
        1024 => Ok(4),
        1476 => Ok(5),
        _ => unreachable!("validated max-APDU-length"),
    }
}

/// Decode a 4-bit max-APDU-length field.
fn decode_max_apdu(value: u8) -> Result<u16, Error> {
    let idx = (value & 0x0F) as usize;
    if idx < MAX_APDU_DECODE.len() {
        Ok(MAX_APDU_DECODE[idx])
    } else {
        Err(Error::decoding(
            1,
            format!("reserved max-APDU-length field value {idx}"),
        ))
    }
}

// ---------------------------------------------------------------------------
// PDU structs
// ---------------------------------------------------------------------------

/// Confirmed-Request PDU (Clause 20.1.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmedRequest {
    /// Set when this PDU is one segment of a segmented request; adds the sequence and window
    /// fields.
    pub segmented: bool,
    /// Set on every segment except the last one of a segmented request.
    pub more_follows: bool,
    /// Whether the requester can receive the reply as a segmented message.
    pub segmented_response_accepted: bool,
    /// Most segments the requester will accept in a reply; `None` leaves the limit unspecified.
    /// Must be `None` or at least 2; the 3-bit wire field rounds down to 2, 4, 8, 16, 32 or 64, and
    /// anything above 64 encodes as "more than 64".
    pub max_segments: Option<u8>,
    /// Largest APDU, in octets, the requester can receive; must be 50, 128, 206, 480, 1024 or 1476.
    pub max_apdu_length: u16,
    /// Identifier the requester uses to match the reply to this request.
    pub invoke_id: u8,
    /// Segment number within a segmented request; `None` for unsegmented PDUs. `None` on a
    /// segmented PDU encodes as 0.
    pub sequence_number: Option<u8>,
    /// Proposed window: how many segments the sender will transmit per SegmentACK (1..=127);
    /// `None` for unsegmented PDUs. `None` on a segmented PDU encodes as 1.
    pub proposed_window_size: Option<u8>,
    /// Which confirmed service is being requested.
    pub service_choice: ConfirmedServiceChoice,
    /// Raw encoded service request parameters (the bytes after the header).
    pub service_request: Bytes,
}

/// Unconfirmed-Request PDU (Clause 20.1.3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnconfirmedRequest {
    /// Which unconfirmed service this PDU carries.
    pub service_choice: UnconfirmedServiceChoice,
    /// Raw encoded service request parameters.
    pub service_request: Bytes,
}

/// SimpleACK PDU (Clause 20.1.4).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimpleAck {
    /// Invoke ID of the confirmed request being acknowledged.
    pub invoke_id: u8,
    /// Confirmed service being acknowledged.
    pub service_choice: ConfirmedServiceChoice,
}

/// ComplexACK PDU (Clause 20.1.5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComplexAck {
    /// Set when this PDU is one segment of a segmented reply; adds the sequence and window fields.
    pub segmented: bool,
    /// Set on every segment except the last one of a segmented reply.
    pub more_follows: bool,
    /// Invoke ID of the confirmed request this reply answers.
    pub invoke_id: u8,
    /// Segment number within a segmented reply; `None` for unsegmented PDUs. `None` on a
    /// segmented PDU encodes as 0.
    pub sequence_number: Option<u8>,
    /// Proposed window: how many segments the sender will transmit per SegmentACK (1..=127);
    /// `None` for unsegmented PDUs. `None` on a segmented PDU encodes as 1.
    pub proposed_window_size: Option<u8>,
    /// Confirmed service this reply belongs to.
    pub service_choice: ConfirmedServiceChoice,
    /// Raw encoded service acknowledgment parameters.
    pub service_ack: Bytes,
}

/// SegmentACK PDU (Clause 20.1.6).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SegmentAck {
    /// Set when a segment arrived out of order; the peer resends starting with the segment after
    /// `sequence_number`.
    pub negative_ack: bool,
    /// Set when the SegmentACK comes from the server side (the device answering a request), clear
    /// when sent by the requester.
    pub sent_by_server: bool,
    /// Invoke ID of the segmented transaction being acknowledged.
    pub invoke_id: u8,
    /// Last segment received in order. It and every earlier segment are acknowledged; the peer
    /// continues (or, on a negative ack, resends) from the next one, modulo 256.
    pub sequence_number: u8,
    /// Window size, in segments (1..=127), the receiver will accept from now on.
    pub actual_window_size: u8,
}

/// Error PDU (Clause 20.1.7).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorPdu {
    /// Invoke ID of the confirmed request that failed.
    pub invoke_id: u8,
    /// Confirmed service that produced the error.
    pub service_choice: ConfirmedServiceChoice,
    /// Error class from the standard Error production.
    pub error_class: ErrorClass,
    /// Error code from the standard Error production.
    pub error_code: ErrorCode,
    /// Service-specific bytes following the error class and code; empty for a plain class/code
    /// error. For a service whose Clause 21 production replaces the plain pair
    /// (WritePropertyMultiple-Error, ChangeList-Error, CreateObject-Error,
    /// SubscribeCOVPropertyMultiple-Error, ConfirmedPrivateTransfer-Error, VTClose-Error) it
    /// holds the whole error body when that decodes in the formal form; a legacy class/code
    /// error from those services keeps only the bytes after the code.
    pub error_data: Bytes,
}

/// Reject PDU (Clause 20.1.8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RejectPdu {
    /// Invoke ID of the rejected request.
    pub invoke_id: u8,
    /// Why the request was rejected as malformed or unsupported.
    pub reject_reason: RejectReason,
}

/// Abort PDU (Clause 20.1.9).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbortPdu {
    /// Set when the abort comes from the server side of the transaction, clear when sent by the
    /// requester.
    pub sent_by_server: bool,
    /// Invoke ID of the transaction this PDU ends.
    pub invoke_id: u8,
    /// Why the transaction was aborted.
    pub abort_reason: AbortReason,
}

/// Sum type for all APDU PDU types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Apdu {
    /// Confirmed service request.
    ConfirmedRequest(ConfirmedRequest),
    /// Unconfirmed service request.
    UnconfirmedRequest(UnconfirmedRequest),
    /// Acknowledgment carrying no result data.
    SimpleAck(SimpleAck),
    /// Acknowledgment carrying result data, possibly segmented.
    ComplexAck(ComplexAck),
    /// Flow-control acknowledgment of received segments.
    SegmentAck(SegmentAck),
    /// Service failure reported with an error class and code.
    Error(ErrorPdu),
    /// Request refused before execution.
    Reject(RejectPdu),
    /// Transaction terminated early.
    Abort(AbortPdu),
}

// ---------------------------------------------------------------------------
// Encoding
// ---------------------------------------------------------------------------

/// Encode an APDU to wire format.
pub fn encode_apdu(buf: &mut BytesMut, apdu: &Apdu) -> Result<(), Error> {
    match apdu {
        Apdu::ConfirmedRequest(pdu) => encode_confirmed_request(buf, pdu),
        Apdu::UnconfirmedRequest(pdu) => {
            encode_unconfirmed_request(buf, pdu);
            Ok(())
        }
        Apdu::SimpleAck(pdu) => {
            encode_simple_ack(buf, pdu);
            Ok(())
        }
        Apdu::ComplexAck(pdu) => encode_complex_ack(buf, pdu),
        Apdu::SegmentAck(pdu) => encode_segment_ack(buf, pdu),
        Apdu::Error(pdu) => encode_error(buf, pdu),
        Apdu::Reject(pdu) => {
            encode_reject(buf, pdu);
            Ok(())
        }
        Apdu::Abort(pdu) => {
            encode_abort(buf, pdu);
            Ok(())
        }
    }
}

fn encode_confirmed_request(buf: &mut BytesMut, pdu: &ConfirmedRequest) -> Result<(), Error> {
    let max_segments = encode_max_segments(pdu.max_segments)?;
    let max_apdu = encode_max_apdu(pdu.max_apdu_length)?;

    let mut byte0 = PduType::CONFIRMED_REQUEST.to_raw() << 4;
    if pdu.segmented {
        byte0 |= 0x08;
    }
    if pdu.more_follows {
        byte0 |= 0x04;
    }
    if pdu.segmented_response_accepted {
        byte0 |= 0x02;
    }
    buf.put_u8(byte0);

    let byte1 = (max_segments << 4) | max_apdu;
    buf.put_u8(byte1);

    buf.put_u8(pdu.invoke_id);

    if pdu.segmented {
        buf.put_u8(pdu.sequence_number.unwrap_or(0));
        buf.put_u8(valid_window_size(
            "ConfirmedRequest proposed-window-size",
            pdu.proposed_window_size.unwrap_or(1),
        )?);
    }

    buf.put_u8(pdu.service_choice.to_raw());
    buf.put_slice(&pdu.service_request);
    Ok(())
}

fn encode_unconfirmed_request(buf: &mut BytesMut, pdu: &UnconfirmedRequest) {
    buf.put_u8(PduType::UNCONFIRMED_REQUEST.to_raw() << 4);
    buf.put_u8(pdu.service_choice.to_raw());
    buf.put_slice(&pdu.service_request);
}

fn encode_simple_ack(buf: &mut BytesMut, pdu: &SimpleAck) {
    buf.put_u8(PduType::SIMPLE_ACK.to_raw() << 4);
    buf.put_u8(pdu.invoke_id);
    buf.put_u8(pdu.service_choice.to_raw());
}

fn encode_complex_ack(buf: &mut BytesMut, pdu: &ComplexAck) -> Result<(), Error> {
    let mut byte0 = PduType::COMPLEX_ACK.to_raw() << 4;
    if pdu.segmented {
        byte0 |= 0x08;
    }
    if pdu.more_follows {
        byte0 |= 0x04;
    }
    buf.put_u8(byte0);

    buf.put_u8(pdu.invoke_id);

    if pdu.segmented {
        buf.put_u8(pdu.sequence_number.unwrap_or(0));
        buf.put_u8(valid_window_size(
            "ComplexAck proposed-window-size",
            pdu.proposed_window_size.unwrap_or(1),
        )?);
    }

    buf.put_u8(pdu.service_choice.to_raw());
    buf.put_slice(&pdu.service_ack);
    Ok(())
}

fn encode_segment_ack(buf: &mut BytesMut, pdu: &SegmentAck) -> Result<(), Error> {
    let mut byte0 = PduType::SEGMENT_ACK.to_raw() << 4;
    if pdu.negative_ack {
        byte0 |= 0x02;
    }
    if pdu.sent_by_server {
        byte0 |= 0x01;
    }
    buf.put_u8(byte0);
    buf.put_u8(pdu.invoke_id);
    buf.put_u8(pdu.sequence_number);
    buf.put_u8(valid_window_size(
        "SegmentACK actual-window-size",
        pdu.actual_window_size,
    )?);
    Ok(())
}

fn valid_window_size(field: &str, value: u8) -> Result<u8, Error> {
    if (1..=127).contains(&value) {
        Ok(value)
    } else {
        Err(Error::Encoding(format!(
            "{field} {value} outside BACnet range 1..=127"
        )))
    }
}

fn encode_error(buf: &mut BytesMut, pdu: &ErrorPdu) -> Result<(), Error> {
    // A legacy generic error may carry arbitrary service data beginning with
    // an opening tag. Only suppress the generic pair for a complete,
    // structurally valid formal body of a service that defines one.
    let formal =
        formal_error::decode_formal_body(pdu.service_choice, &pdu.error_data).unwrap_or(None);
    if let Some((error_class, error_code)) = formal {
        if error_class != pdu.error_class || error_code != pdu.error_code {
            return Err(Error::Encoding(
                "formal Error body disagrees with ErrorPdu class/code".into(),
            ));
        }
    }

    buf.put_u8(PduType::ERROR.to_raw() << 4);
    buf.put_u8(pdu.invoke_id);
    buf.put_u8(pdu.service_choice.to_raw());
    if formal.is_some() {
        buf.put_slice(&pdu.error_data);
    } else {
        primitives::encode_app_enumerated(buf, pdu.error_class.to_raw() as u32);
        primitives::encode_app_enumerated(buf, pdu.error_code.to_raw() as u32);
        if !pdu.error_data.is_empty() {
            buf.put_slice(&pdu.error_data);
        }
    }
    Ok(())
}

fn encode_reject(buf: &mut BytesMut, pdu: &RejectPdu) {
    buf.put_u8(PduType::REJECT.to_raw() << 4);
    buf.put_u8(pdu.invoke_id);
    buf.put_u8(pdu.reject_reason.to_raw());
}

fn encode_abort(buf: &mut BytesMut, pdu: &AbortPdu) {
    let mut byte0 = PduType::ABORT.to_raw() << 4;
    if pdu.sent_by_server {
        byte0 |= 0x01;
    }
    buf.put_u8(byte0);
    buf.put_u8(pdu.invoke_id);
    buf.put_u8(pdu.abort_reason.to_raw());
}

// ---------------------------------------------------------------------------
// Decoding
// ---------------------------------------------------------------------------

/// Decode an APDU from raw bytes.
pub fn decode_apdu(data: Bytes) -> Result<Apdu, Error> {
    if data.is_empty() {
        return Err(Error::decoding(0, "APDU data is empty"));
    }

    let pdu_type_raw = (data[0] >> 4) & 0x0F;
    let pdu_type = PduType::from_raw(pdu_type_raw);

    if pdu_type == PduType::CONFIRMED_REQUEST {
        decode_confirmed_request(data).map(Apdu::ConfirmedRequest)
    } else if pdu_type == PduType::UNCONFIRMED_REQUEST {
        decode_unconfirmed_request(data).map(Apdu::UnconfirmedRequest)
    } else if pdu_type == PduType::SIMPLE_ACK {
        decode_simple_ack(data).map(Apdu::SimpleAck)
    } else if pdu_type == PduType::COMPLEX_ACK {
        decode_complex_ack(data).map(Apdu::ComplexAck)
    } else if pdu_type == PduType::SEGMENT_ACK {
        decode_segment_ack(data).map(Apdu::SegmentAck)
    } else if pdu_type == PduType::ERROR {
        decode_error(data).map(Apdu::Error)
    } else if pdu_type == PduType::REJECT {
        decode_reject(data).map(Apdu::Reject)
    } else if pdu_type == PduType::ABORT {
        decode_abort(data).map(Apdu::Abort)
    } else {
        Err(Error::decoding(
            0,
            format!("unknown PDU type nibble: {:#x}", pdu_type_raw),
        ))
    }
}

fn decode_confirmed_request(data: Bytes) -> Result<ConfirmedRequest, Error> {
    if data.len() < 4 {
        return Err(Error::buffer_too_short(4, data.len()));
    }

    let byte0 = data[0];
    let segmented = byte0 & 0x08 != 0;
    let more_follows = byte0 & 0x04 != 0;
    let segmented_response_accepted = byte0 & 0x02 != 0;

    let byte1 = data[1];
    let max_segments = decode_max_segments((byte1 >> 4) & 0x07);
    let max_apdu_length = decode_max_apdu(byte1 & 0x0F)?;

    let invoke_id = data[2];
    let mut offset = 3;

    let (sequence_number, proposed_window_size) = if segmented {
        if data.len() < 6 {
            return Err(Error::decoding(
                offset,
                "segmented ConfirmedRequest too short for sequence/window fields",
            ));
        }
        let seq = data[offset];
        let win = data[offset + 1];
        offset += 2;
        (Some(seq), Some(win))
    } else {
        (None, None)
    };

    if offset >= data.len() {
        return Err(Error::decoding(
            offset,
            "ConfirmedRequest missing service choice",
        ));
    }
    let service_choice = ConfirmedServiceChoice::from_raw(data[offset]);
    offset += 1;

    let service_request = data.slice(offset..);

    Ok(ConfirmedRequest {
        segmented,
        more_follows,
        segmented_response_accepted,
        max_segments,
        max_apdu_length,
        invoke_id,
        sequence_number,
        proposed_window_size,
        service_choice,
        service_request,
    })
}

fn decode_unconfirmed_request(data: Bytes) -> Result<UnconfirmedRequest, Error> {
    if data.len() < 2 {
        return Err(Error::buffer_too_short(2, data.len()));
    }

    let service_choice = UnconfirmedServiceChoice::from_raw(data[1]);
    let service_request = data.slice(2..);

    Ok(UnconfirmedRequest {
        service_choice,
        service_request,
    })
}

fn decode_simple_ack(data: Bytes) -> Result<SimpleAck, Error> {
    if data.len() < 3 {
        return Err(Error::buffer_too_short(3, data.len()));
    }

    Ok(SimpleAck {
        invoke_id: data[1],
        service_choice: ConfirmedServiceChoice::from_raw(data[2]),
    })
}

fn decode_complex_ack(data: Bytes) -> Result<ComplexAck, Error> {
    if data.len() < 3 {
        return Err(Error::buffer_too_short(3, data.len()));
    }

    let byte0 = data[0];
    let segmented = byte0 & 0x08 != 0;
    let more_follows = byte0 & 0x04 != 0;

    let invoke_id = data[1];
    let mut offset = 2;

    let (sequence_number, proposed_window_size) = if segmented {
        if data.len() < 5 {
            return Err(Error::decoding(
                offset,
                "segmented ComplexAck too short for sequence/window fields",
            ));
        }
        let seq = data[offset];
        let win = data[offset + 1];
        offset += 2;
        (Some(seq), Some(win))
    } else {
        (None, None)
    };

    if offset >= data.len() {
        return Err(Error::decoding(offset, "ComplexAck missing service choice"));
    }
    let service_choice = ConfirmedServiceChoice::from_raw(data[offset]);
    offset += 1;

    let service_ack = data.slice(offset..);

    Ok(ComplexAck {
        segmented,
        more_follows,
        invoke_id,
        sequence_number,
        proposed_window_size,
        service_choice,
        service_ack,
    })
}

fn decode_segment_ack(data: Bytes) -> Result<SegmentAck, Error> {
    if data.len() < 4 {
        return Err(Error::buffer_too_short(4, data.len()));
    }

    let byte0 = data[0];
    let raw_window = data[3];
    if raw_window == 0 || raw_window > 127 {
        return Err(Error::decoding(
            3,
            format!("SegmentACK actual-window-size {raw_window} outside range 1..=127"),
        ));
    }
    Ok(SegmentAck {
        negative_ack: byte0 & 0x02 != 0,
        sent_by_server: byte0 & 0x01 != 0,
        invoke_id: data[1],
        sequence_number: data[2],
        actual_window_size: raw_window,
    })
}

fn decode_error(data: Bytes) -> Result<ErrorPdu, Error> {
    if data.len() < 5 {
        return Err(Error::buffer_too_short(5, data.len()));
    }

    let invoke_id = data[1];
    let service_choice = ConfirmedServiceChoice::from_raw(data[2]);

    if let Some((error_class, error_code)) =
        formal_error::decode_formal_body(service_choice, &data[3..])?
    {
        return Ok(ErrorPdu {
            invoke_id,
            service_choice,
            error_class,
            error_code,
            error_data: data.slice(3..),
        });
    }

    let mut offset = 3;
    let (tag, tag_end) = tags::decode_tag(&data, offset)?;
    if tag.class != tags::TagClass::Application || tag.number != tags::app_tag::ENUMERATED {
        return Err(Error::decoding(
            offset,
            "ErrorPDU error class: expected application-tagged enumerated",
        ));
    }
    let class_end = tag_end
        .checked_add(tag.length as usize)
        .ok_or_else(|| Error::decoding(tag_end, "ErrorPDU error class length overflow"))?;
    if class_end > data.len() {
        return Err(Error::buffer_too_short(class_end, data.len()));
    }
    let error_class_raw = primitives::decode_unsigned(&data[tag_end..class_end])?;
    let error_class_raw = u16::try_from(error_class_raw).map_err(|_| {
        Error::out_of_range(
            tag_end,
            format!("ErrorPDU error class {error_class_raw} exceeds u16"),
        )
    })?;
    offset = class_end;

    let (tag, tag_end) = tags::decode_tag(&data, offset)?;
    if tag.class != tags::TagClass::Application || tag.number != tags::app_tag::ENUMERATED {
        return Err(Error::decoding(
            offset,
            "ErrorPDU error code: expected application-tagged enumerated",
        ));
    }
    let code_end = tag_end
        .checked_add(tag.length as usize)
        .ok_or_else(|| Error::decoding(tag_end, "ErrorPDU error code length overflow"))?;
    if code_end > data.len() {
        return Err(Error::buffer_too_short(code_end, data.len()));
    }
    let error_code_raw = primitives::decode_unsigned(&data[tag_end..code_end])?;
    let error_code_raw = u16::try_from(error_code_raw).map_err(|_| {
        Error::out_of_range(
            tag_end,
            format!("ErrorPDU error code {error_code_raw} exceeds u16"),
        )
    })?;
    offset = code_end;

    let error_data = if offset < data.len() {
        data.slice(offset..)
    } else {
        Bytes::new()
    };

    Ok(ErrorPdu {
        invoke_id,
        service_choice,
        error_class: ErrorClass::from_raw(error_class_raw),
        error_code: ErrorCode::from_raw(error_code_raw),
        error_data,
    })
}

fn decode_reject(data: Bytes) -> Result<RejectPdu, Error> {
    if data.len() < 3 {
        return Err(Error::buffer_too_short(3, data.len()));
    }

    Ok(RejectPdu {
        invoke_id: data[1],
        reject_reason: RejectReason::from_raw(data[2]),
    })
}

fn decode_abort(data: Bytes) -> Result<AbortPdu, Error> {
    if data.len() < 3 {
        return Err(Error::buffer_too_short(3, data.len()));
    }

    let byte0 = data[0];
    Ok(AbortPdu {
        sent_by_server: byte0 & 0x01 != 0,
        invoke_id: data[1],
        abort_reason: AbortReason::from_raw(data[2]),
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod change_list_error_tests;
#[cfg(test)]
mod structured_error_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod wpm_error_tests;