bacnet-services 0.15.0

BACnet service request/response encode/decode 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
//! Who-Is and I-Am services per ASHRAE 135-2020 Clause 16.10.
//!
//! Both encode to a sink and decode from borrowed octets without an
//! allocator (#1614). The `BytesMut` encoders need `alloc`, and write the
//! same octets through the sink encoders.

use bacnet_encoding::constructed::tagged::{
    decode_app_enumerated, decode_app_object_id, decode_app_unsigned, decode_ctx_unsigned,
    decode_optional_ctx, expect_end,
};
use bacnet_encoding::primitives;
use bacnet_encoding::sink::{EncodeSink, SinkFull};
use bacnet_types::enums::Segmentation;
use bacnet_types::error::{DecodeError, DecodingKind, Error, RangeError};
use bacnet_types::primitives::ObjectIdentifier;
#[cfg(feature = "alloc")]
use bytes::BytesMut;

/// Encode into `staging` with `encode`, then append what it wrote to `sink`
/// in one write; returns the octets appended. `staging` must hold the
/// largest value `encode` writes.
pub(crate) fn staged<S: EncodeSink + ?Sized>(
    sink: &mut S,
    staging: &mut [u8],
    encode: impl FnOnce(&mut &mut [u8]) -> Result<usize, SinkFull>,
) -> Result<usize, SinkFull> {
    let mut tail = &mut *staging;
    let written = encode(&mut tail).expect("the staging buffer holds the largest value");
    sink.write(&staging[..written])?;
    Ok(written)
}

// ---------------------------------------------------------------------------
// DeviceInstanceRange
// ---------------------------------------------------------------------------

/// The devices a Who-Is or Who-Has asks to answer: those whose Device object
/// instance lies from [`low`](Self::low) to [`high`](Self::high), both
/// included (Clauses 16.10.1.1.1-2 and 16.9.1.1.1-2).
///
/// The clauses send both limits or neither, keep the low one at or below
/// the high one, and give each the instance range 0 to
/// [`ObjectIdentifier::MAX_INSTANCE`]. A request holds an
/// `Option<DeviceInstanceRange>`, so it can't carry one limit alone, and
/// [`Self::new`] refuses a low limit above the high one, a range no device
/// lies in, and a limit past the highest instance. The decoders refuse the
/// first two forms on the wire as well (#1447, #1483), but take a limit past
/// the highest instance, since some devices send one to mean every device;
/// [`Self::contains`] reads such a range as written.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeviceInstanceRange {
    low: u32,
    high: u32,
}

impl DeviceInstanceRange {
    /// The instances from `low` to `high`, both included. Fails with
    /// [`Error::Range`] when `low` is above `high`, or `high` is above
    /// [`ObjectIdentifier::MAX_INSTANCE`].
    pub fn new(low: u32, high: u32) -> Result<Self, Error> {
        let range = Self::decoded(low, high)?;
        if high > ObjectIdentifier::MAX_INSTANCE {
            return Err(RangeError::new(
                "device instance range high limit {} is above the highest instance, 4194303",
            )
            .with_value(high.into())
            .into());
        }
        Ok(range)
    }

    /// The range as a decoder reads it: `low` no greater than `high`, with
    /// either past the highest instance taken as written.
    fn decoded(low: u32, high: u32) -> Result<Self, Error> {
        if low > high {
            return Err(RangeError::new(
                "device instance range low limit {} is above its high limit {}, \
                 so it would match no device",
            )
            .with_values(low.into(), high.into())
            .into());
        }
        Ok(Self { low, high })
    }

    /// The one instance `instance`, as when a Who-Is looks for one device;
    /// fails as [`Self::new`] does for an instance past the highest.
    pub fn single(instance: u32) -> Result<Self, Error> {
        Self::new(instance, instance)
    }

    /// The one instance of `device`, which always lies in the instance range.
    pub fn device(device: ObjectIdentifier) -> Self {
        let instance = device.instance_number();
        Self {
            low: instance,
            high: instance,
        }
    }

    /// The range two separately held limits give: none for neither, a range
    /// for both, as the Python bindings take them. One limit alone fails with
    /// [`Error::Range`] naming it, rather than becoming a request for every
    /// device, and so does any range [`Self::new`] refuses.
    pub fn from_limits(low: Option<u32>, high: Option<u32>) -> Result<Option<Self>, Error> {
        let alone = |label, limit: u32| Err(RangeError::new(label).with_value(limit.into()).into());
        match (low, high) {
            (None, None) => Ok(None),
            (Some(low), Some(high)) => Self::new(low, high).map(Some),
            (Some(low), None) => alone(
                "a device instance range needs both limits or neither: \
                 low limit {} was given without a high limit",
                low,
            ),
            (None, Some(high)) => alone(
                "a device instance range needs both limits or neither: \
                 high limit {} was given without a low limit",
                high,
            ),
        }
    }

    /// The lowest instance in the range.
    pub const fn low(self) -> u32 {
        self.low
    }

    /// The highest instance in the range.
    pub const fn high(self) -> u32 {
        self.high
    }

    /// Whether `instance` lies in the range.
    pub const fn contains(self, instance: u32) -> bool {
        self.low <= instance && instance <= self.high
    }

    /// Write the range as the `[0]` low and `[1]` high limits: at most ten
    /// octets, in one write.
    pub(crate) fn encode_to_sink<S: EncodeSink + ?Sized>(
        self,
        sink: &mut S,
    ) -> Result<usize, SinkFull> {
        staged(sink, &mut [0; 10], |tail| {
            Ok(
                primitives::encode_ctx_unsigned_to_sink(tail, 0, self.low.into())?
                    + primitives::encode_ctx_unsigned_to_sink(tail, 1, self.high.into())?,
            )
        })
    }

    /// Write the range as the `[0]` low and `[1]` high limits.
    #[cfg(feature = "alloc")]
    pub(crate) fn encode(self, buf: &mut BytesMut) {
        self.encode_to_sink(buf)
            .expect("the BytesMut sink cannot return SinkFull");
    }
}

/// What a Who-Is or Who-Has calls its limits in errors, and how it words a
/// limit missing its partner or a low limit above the high one. The labels
/// are written out whole, so a request that decodes builds none (#1645), and
/// a refusal builds its text only when displayed (#1646).
pub(crate) struct LimitLabels {
    /// The `[0]` low limit.
    low: &'static str,
    /// The `[1]` high limit.
    high: &'static str,
    /// A low limit above the high one.
    inverted: &'static str,
    /// A low limit without the high one.
    low_alone: &'static str,
    /// A high limit without the low one.
    high_alone: &'static str,
}

/// [`LimitLabels`] for `$service`.
macro_rules! limit_labels {
    ($service:literal) => {
        LimitLabels {
            low: concat!($service, " low limit"),
            high: concat!($service, " high limit"),
            inverted: concat!($service, " low limit exceeds high limit"),
            low_alone: concat!($service, " low limit needs the high limit [1] with it"),
            high_alone: concat!($service, " high limit needs the low limit [0] before it"),
        }
    };
}

impl LimitLabels {
    /// A Who-Is's.
    pub(crate) const WHO_IS: Self = limit_labels!("WhoIs");
    /// A Who-Has's.
    #[cfg(feature = "alloc")]
    pub(crate) const WHO_HAS: Self = limit_labels!("WhoHas");
}

/// A Who-Is or Who-Has request's optional `[0]` low and `[1]` high limits,
/// as read from the start of its service-request octets. The decoders read
/// the rest of the request before [`Self::range`] checks the pairing.
pub(crate) struct WireLimits {
    low: Option<u32>,
    high: Option<u32>,
    /// Where a `[1]` high limit after a lone low limit was due.
    after_low: usize,
    /// The offset after the limits.
    pub(crate) end: usize,
    /// What errors call the service and its limits.
    labels: &'static LimitLabels,
}

impl WireLimits {
    /// Read the limits, which `labels` names in errors.
    pub(crate) fn decode(data: &[u8], labels: &'static LimitLabels) -> Result<Self, Error> {
        let (low, after_low) =
            decode_optional_ctx(data, 0, 0, labels.low, decode_ctx_unsigned::<u32>)?;
        let (high, end) =
            decode_optional_ctx(data, after_low, 1, labels.high, decode_ctx_unsigned::<u32>)?;
        Ok(Self {
            low,
            high,
            after_low,
            end,
            labels,
        })
    }

    /// The range the limits give. One limit without the other is malformed
    /// (#1447, #1483): a receiver drops it rather than reading it as a
    /// request for every device, which would make every device answer one
    /// that probably meant a range. So is a low limit above the high one.
    pub(crate) fn range(&self) -> Result<Option<DeviceInstanceRange>, Error> {
        let labels = self.labels;
        match (self.low, self.high) {
            (None, None) => Ok(None),
            (Some(low), Some(high)) => DeviceInstanceRange::decoded(low, high)
                .map(Some)
                .map_err(|_| DecodeError::new(DecodingKind::OutOfRange, 0, labels.inverted).into()),
            (Some(_), None) => {
                Err(
                    DecodeError::new(DecodingKind::Missing, self.after_low, labels.low_alone)
                        .into(),
                )
            }
            (None, Some(_)) => {
                Err(DecodeError::new(DecodingKind::Missing, 0, labels.high_alone).into())
            }
        }
    }
}

// ---------------------------------------------------------------------------
// WhoIsRequest
// ---------------------------------------------------------------------------

/// Who-Is-Request service parameters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WhoIsRequest {
    /// The devices that should answer; `None` asks every device.
    pub range: Option<DeviceInstanceRange>,
}

impl WhoIsRequest {
    /// Create an unbounded WhoIs (all devices).
    pub fn all() -> Self {
        Self { range: None }
    }

    /// Append the request to `sink`: both limits for a range, nothing for an
    /// unbounded request. Returns the octets appended, at most ten, in one
    /// write.
    pub fn encode_to_sink<S: EncodeSink + ?Sized>(&self, sink: &mut S) -> Result<usize, SinkFull> {
        match self.range {
            Some(range) => range.encode_to_sink(sink),
            None => Ok(0),
        }
    }

    /// Encode the request into `buf`: both limits for a range, nothing for an
    /// unbounded request. Only with `alloc`.
    #[cfg(feature = "alloc")]
    pub fn encode(&self, buf: &mut BytesMut) {
        self.encode_to_sink(buf)
            .expect("the BytesMut sink cannot return SinkFull");
    }

    /// Decode the request from service-request octets; fails on malformed or truncated input,
    /// on any octet that isn't a `[0]` or `[1]` limit in its place, so a limit under another
    /// tag or anything after the limits refuses the request rather than reading as no limits,
    /// on one limit without the other (#1447), and on a low limit above the high one.
    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        let limits = WireLimits::decode(data, &LimitLabels::WHO_IS)?;
        expect_end(data, limits.end, limits.end, "WhoIs")?;
        Ok(Self {
            range: limits.range()?,
        })
    }
}

// ---------------------------------------------------------------------------
// IAmRequest
// ---------------------------------------------------------------------------

/// I-Am-Request service parameters.
///
/// All fields use APPLICATION tags (not context-specific).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IAmRequest {
    /// Device object of the announcing device.
    pub object_identifier: ObjectIdentifier,
    /// Largest APDU, in octets, the device can accept.
    pub max_apdu_length: u32,
    /// Segmentation abilities the device supports.
    pub segmentation_supported: Segmentation,
    /// Vendor identifier (Unsigned16) of the device manufacturer.
    pub vendor_id: u16,
}

impl IAmRequest {
    /// Append the request parameters to `sink`. Returns the octets appended,
    /// at most fifteen, in one write.
    pub fn encode_to_sink<S: EncodeSink + ?Sized>(&self, sink: &mut S) -> Result<usize, SinkFull> {
        staged(sink, &mut [0; 15], |tail| {
            Ok(
                primitives::encode_app_object_id_to_sink(tail, &self.object_identifier)?
                    + primitives::encode_app_unsigned_to_sink(tail, self.max_apdu_length.into())?
                    + primitives::encode_app_enumerated_to_sink(
                        tail,
                        self.segmentation_supported.to_raw().into(),
                    )?
                    + primitives::encode_app_unsigned_to_sink(tail, self.vendor_id.into())?,
            )
        })
    }

    /// Encode the request parameters into `buf`. Only with `alloc`.
    #[cfg(feature = "alloc")]
    pub fn encode(&self, buf: &mut BytesMut) {
        self.encode_to_sink(buf)
            .expect("the BytesMut sink cannot return SinkFull");
    }

    /// Decode the request from service-request octets; fails on malformed or truncated input
    /// and on octets after the vendor identifier.
    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        let (object_identifier, offset) = decode_app_object_id(data, 0, "IAm object identifier")?;
        let (max_apdu_length, offset) =
            decode_app_unsigned::<u32>(data, offset, "IAm max APDU length")?;
        let (segmentation, offset) = decode_app_enumerated::<u8>(data, offset, "IAm segmentation")?;
        let segmentation_supported = Segmentation::from_raw(segmentation);
        let (vendor_id, end) = decode_app_unsigned::<u16>(data, offset, "IAm vendor ID")?;
        expect_end(data, end, end, "IAm")?;

        Ok(Self {
            object_identifier,
            max_apdu_length,
            segmentation_supported,
            vendor_id,
        })
    }
}

#[cfg(test)]
#[path = "who_is_sink_tests.rs"]
mod sink_tests;

// The tests build requests with the BytesMut encoders, which need alloc.
#[cfg(all(test, feature = "alloc"))]
mod tests {
    use super::*;
    use bacnet_encoding::tags;
    use bacnet_types::enums::ObjectType;

    #[test]
    fn who_is_all_round_trip() {
        let req = WhoIsRequest::all();
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert!(buf.is_empty());
        let decoded = WhoIsRequest::decode(&buf).unwrap();
        assert_eq!(req, decoded);
    }

    #[test]
    fn who_is_range_round_trip() {
        let req = WhoIsRequest {
            range: Some(DeviceInstanceRange::new(1000, 2000).unwrap()),
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert!(!buf.is_empty());
        let decoded = WhoIsRequest::decode(&buf).unwrap();
        assert_eq!(req, decoded);
    }

    #[test]
    fn i_am_round_trip() {
        let req = IAmRequest {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap(),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            vendor_id: 999,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        let decoded = IAmRequest::decode(&buf).unwrap();
        assert_eq!(req, decoded);
    }

    #[test]
    fn i_am_wire_format() {
        let req = IAmRequest {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap(),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            vendor_id: 42,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);

        // First byte should be app tag 12, length 4 = 0xC4
        assert_eq!(buf[0], 0xC4);
    }

    // -----------------------------------------------------------------------
    // Malformed-input decode error tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_decode_who_is_truncated() {
        // A range cut anywhere fails: inside the low limit, or after it,
        // which leaves one limit alone.
        let req = WhoIsRequest {
            range: Some(DeviceInstanceRange::new(1000, 2000).unwrap()),
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        for cut in 1..buf.len() {
            assert!(WhoIsRequest::decode(&buf[..cut]).is_err(), "cut at {cut}");
        }
    }

    #[test]
    fn who_is_with_one_limit_is_refused() {
        // [0] low limit 1 alone, then [1] high limit 10 alone (#1447).
        for data in [&[0x09, 0x01][..], &[0x19, 0x0A]] {
            let error = WhoIsRequest::decode(data).unwrap_err();
            assert!(matches!(error, Error::Decoding(_)), "{error:?}");
        }
    }

    #[test]
    fn test_decode_who_is_invalid_tag() {
        // A tag that is neither limit is left over, not read as no limits.
        let error = WhoIsRequest::decode(&[0x29, 0]).unwrap_err();
        assert!(matches!(error, Error::Decoding(_)), "{error:?}");
    }

    #[test]
    fn who_is_low_exceeds_high_is_error() {
        // Low limit 2000, high limit 1000: no range can be built this way,
        // so the octets are written out.
        let data = [0x0A, 0x07, 0xD0, 0x1A, 0x03, 0xE8];
        let err = WhoIsRequest::decode(&data).unwrap_err();
        assert!(
            err.to_string()
                .contains("WhoIs low limit exceeds high limit"),
            "expected a low limit above the high limit to fail, got: {err:?}"
        );
    }

    #[test]
    fn who_is_equal_limits_is_valid() {
        let req = WhoIsRequest {
            range: Some(DeviceInstanceRange::single(1500).unwrap()),
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert_eq!(buf[..], [0x0A, 0x05, 0xDC, 0x1A, 0x05, 0xDC]);
        let decoded = WhoIsRequest::decode(&buf).unwrap();
        assert_eq!(decoded, req);
    }

    #[test]
    fn who_is_limits_must_fit_u32() {
        let encode_range = |low, high| {
            let mut buf = BytesMut::new();
            primitives::encode_ctx_unsigned(&mut buf, 0, low);
            primitives::encode_ctx_unsigned(&mut buf, 1, high);
            buf
        };

        // The shared readers' wording names the member, its tag and the value.
        for (low, high, field, value) in [
            (
                4_294_967_297,
                4_294_967_297,
                "low limit: [0]",
                4_294_967_297_u64,
            ),
            (1, 4_294_967_297, "high limit: [1]", 4_294_967_297),
        ] {
            let encoded = encode_range(low, high);
            let error = WhoIsRequest::decode(&encoded).unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains(&format!("WhoIs {field} value {value} exceeds u32")),
                "unexpected error for {field} {value}: {error}"
            );
        }

        let mut leading_zero = BytesMut::new();
        for tag_number in [0, 1] {
            tags::encode_tag(&mut leading_zero, tag_number, tags::TagClass::Context, 5);
            leading_zero.extend_from_slice(&[0, 0xff, 0xff, 0xff, 0xff]);
        }
        let decoded = WhoIsRequest::decode(&leading_zero).unwrap();
        // Past the highest instance, but taken as written.
        let range = decoded.range.unwrap();
        assert_eq!((range.low(), range.high()), (u32::MAX, u32::MAX));
    }

    #[test]
    fn i_am_values_must_fit_field_widths() {
        let object_identifier = ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap();
        let encode_request = |max_apdu_length, segmentation, vendor_id| {
            let mut buf = BytesMut::new();
            primitives::encode_app_object_id(&mut buf, &object_identifier);
            primitives::encode_app_unsigned(&mut buf, max_apdu_length);
            primitives::encode_app_enumerated(&mut buf, segmentation);
            primitives::encode_app_unsigned(&mut buf, vendor_id);
            buf
        };

        // The shared application readers name the member, its type and the
        // width it must fit.
        for (max_apdu_length, segmentation, vendor_id, refusal) in [
            (4_294_967_296, 0, 0, "max APDU length: Unsigned exceeds u32"),
            (1, 256, 0, "segmentation: ENUMERATED exceeds u8"),
            (1, 0, 65_536, "vendor ID: Unsigned exceeds u16"),
        ] {
            let encoded = encode_request(max_apdu_length, segmentation, vendor_id);
            let error = IAmRequest::decode(&encoded).unwrap_err();
            assert!(
                error.to_string().contains(&format!("IAm {refusal}")),
                "unexpected error for {refusal}: {error}"
            );
        }

        let mut leading_zero = BytesMut::new();
        primitives::encode_app_object_id(&mut leading_zero, &object_identifier);
        for (tag_number, content) in [
            (tags::app_tag::UNSIGNED, &[0, 0xff, 0xff, 0xff, 0xff][..]),
            (tags::app_tag::ENUMERATED, &[0, 0xff][..]),
            (tags::app_tag::UNSIGNED, &[0, 0xff, 0xff][..]),
        ] {
            tags::encode_tag(
                &mut leading_zero,
                tag_number,
                tags::TagClass::Application,
                content.len() as u32,
            );
            leading_zero.extend_from_slice(content);
        }
        let decoded = IAmRequest::decode(&leading_zero).unwrap();
        assert_eq!(decoded.max_apdu_length, u32::MAX);
        assert_eq!(decoded.segmentation_supported.to_raw(), u8::MAX);
        assert_eq!(decoded.vendor_id, u16::MAX);

        let encode_with_tags = |object_tag, max_apdu_tag, segmentation_tag, vendor_tag| {
            let mut buf = BytesMut::new();
            for (tag_number, content) in [
                (object_tag, &object_identifier.encode()[..]),
                (max_apdu_tag, &1476_u16.to_be_bytes()[..]),
                (segmentation_tag, &[0][..]),
                (vendor_tag, &999_u16.to_be_bytes()[..]),
            ] {
                tags::encode_tag(
                    &mut buf,
                    tag_number,
                    tags::TagClass::Application,
                    content.len() as u32,
                );
                buf.extend_from_slice(content);
            }
            buf
        };
        for (object_tag, max_apdu_tag, segmentation_tag, vendor_tag, field) in [
            (
                tags::app_tag::UNSIGNED,
                tags::app_tag::UNSIGNED,
                tags::app_tag::ENUMERATED,
                tags::app_tag::UNSIGNED,
                "object identifier",
            ),
            (
                tags::app_tag::OBJECT_IDENTIFIER,
                tags::app_tag::ENUMERATED,
                tags::app_tag::ENUMERATED,
                tags::app_tag::UNSIGNED,
                "max APDU length",
            ),
            (
                tags::app_tag::OBJECT_IDENTIFIER,
                tags::app_tag::UNSIGNED,
                tags::app_tag::UNSIGNED,
                tags::app_tag::UNSIGNED,
                "segmentation",
            ),
            (
                tags::app_tag::OBJECT_IDENTIFIER,
                tags::app_tag::UNSIGNED,
                tags::app_tag::ENUMERATED,
                tags::app_tag::SIGNED,
                "vendor ID",
            ),
        ] {
            let encoded = encode_with_tags(object_tag, max_apdu_tag, segmentation_tag, vendor_tag);
            let error = IAmRequest::decode(&encoded).unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains(&format!("IAm {field}: expected application-tagged")),
                "unexpected error for {field} tag: {error}"
            );
        }

        let valid = encode_request(1476, 0, 999);
        let mut reserved_lvt = BytesMut::from(&[0xc6, 4][..]);
        reserved_lvt.extend_from_slice(&valid[1..]);
        assert!(IAmRequest::decode(&reserved_lvt).is_err());
    }

    #[test]
    fn test_decode_i_am_empty_input() {
        assert!(IAmRequest::decode(&[]).is_err());
    }

    #[test]
    fn test_decode_i_am_truncated_1_byte() {
        let req = IAmRequest {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap(),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            vendor_id: 999,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert!(IAmRequest::decode(&buf[..1]).is_err());
    }

    #[test]
    fn test_decode_i_am_truncated_2_bytes() {
        let req = IAmRequest {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap(),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            vendor_id: 999,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert!(IAmRequest::decode(&buf[..2]).is_err());
    }

    #[test]
    fn test_decode_i_am_truncated_3_bytes() {
        let req = IAmRequest {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap(),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            vendor_id: 999,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        assert!(IAmRequest::decode(&buf[..3]).is_err());
    }

    #[test]
    fn test_decode_i_am_truncated_half() {
        let req = IAmRequest {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap(),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            vendor_id: 999,
        };
        let mut buf = BytesMut::new();
        req.encode(&mut buf);
        let half = buf.len() / 2;
        assert!(IAmRequest::decode(&buf[..half]).is_err());
    }

    #[test]
    fn test_decode_i_am_invalid_tag() {
        assert!(IAmRequest::decode(&[0xFF, 0xFF, 0xFF]).is_err());
    }
}

#[cfg(all(test, feature = "alloc"))]
#[path = "device_range_tests.rs"]
mod device_range_tests;