bacnet-services 0.14.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
702
703
704
705
706
707
708
709
710
711
//! Incremental WritePropertyMultiple request grammar.

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use bacnet_encoding::constructed::tagged::misplaced_kind;
use bacnet_encoding::constructed::{
    decode_bacnet_property_value_in_list_detailed, PropertyValueDecodeError,
    PropertyValueDecodeFailure, PropertyValueDecodeStage,
};
use bacnet_encoding::tags;
use bacnet_types::constructed::BACnetObjectPropertyReference;
use bacnet_types::enums::RejectReason;
use bacnet_types::error::{DecodeError, Error};
use bacnet_types::primitives::ObjectIdentifier;

use crate::common::MAX_DECODED_ITEMS;

/// Stable request-decoding stage reported by the incremental WPM cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WritePropertyMultipleDecodeStage {
    /// Context `[0]` object identifier.
    ObjectIdentifier,
    /// Opening context `[1]` property list.
    PropertyList,
    /// Required property identifier of a list item.
    PropertyIdentifier,
    /// Optional property array index.
    ArrayIndex,
    /// Constructed property value.
    Value,
    /// Optional write priority.
    Priority,
    /// Closing context `[1]` property list delimiter.
    PropertyListEnd,
    /// Bounded object/property cardinality.
    ItemLimit,
}

impl WritePropertyMultipleDecodeStage {
    /// The stage's name in a refusal's text, such as `"WPM Value"`.
    pub fn name(self) -> &'static str {
        match self {
            Self::ObjectIdentifier => "WPM ObjectIdentifier",
            Self::PropertyList => "WPM PropertyList",
            Self::PropertyIdentifier => "WPM PropertyIdentifier",
            Self::ArrayIndex => "WPM ArrayIndex",
            Self::Value => "WPM Value",
            Self::Priority => "WPM Priority",
            Self::PropertyListEnd => "WPM PropertyListEnd",
            Self::ItemLimit => "WPM ItemLimit",
        }
    }
}

/// Classification retained independently of the number of writes executed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WritePropertyMultipleFailureKind {
    /// Malformed request grammar, with its pre-write Clause 18.9 Reject reason.
    Syntax(RejectReason),
    /// A valid Unsigned priority outside 1..=16 (Clause 15.10 service Error).
    PriorityOutOfRange,
}

/// A classified WPM request failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WritePropertyMultipleCursorError {
    /// Zero-based byte offset where decoding failed.
    pub offset: usize,
    /// Stable request stage that failed.
    pub stage: WritePropertyMultipleDecodeStage,
    /// Syntax or semantic priority failure; service execution selects the response.
    pub kind: WritePropertyMultipleFailureKind,
    /// Complete failed coordinate, present only after every member decoded.
    pub first_failed_write_attempt: Option<BACnetObjectPropertyReference>,
    /// The refusal as a static decoding error, never encoded on the wire:
    /// this failure's offset and the [`DecodingKind`](bacnet_types::error::DecodingKind)
    /// its kind draws, with the stage's [`name`](WritePropertyMultipleDecodeStage::name)
    /// as its context (#1776).
    pub error: DecodeError,
}

/// One complete write attempt in request wire order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WritePropertyAttempt {
    /// Complete object/property coordinate.
    pub reference: BACnetObjectPropertyReference,
    /// Raw, exactly bounded contents of the property's constructed value.
    pub value: Vec<u8>,
    /// Optional command priority.
    pub priority: Option<u8>,
}

/// Events emitted by [`WritePropertyMultipleCursor`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WritePropertyMultipleEvent {
    /// A context `[0]` object and its opening property list decoded.
    ObjectStart(ObjectIdentifier),
    /// One complete property write attempt.
    WriteAttempt(WritePropertyAttempt),
    /// The current object's property list closed.
    ObjectEnd,
}

#[derive(Debug, Clone, Copy)]
enum State {
    Object,
    Properties(ObjectIdentifier),
    Done,
    Failed,
}

/// Bounded, allocation-light cursor over a WPM request body.
pub struct WritePropertyMultipleCursor<'a> {
    data: &'a [u8],
    offset: usize,
    state: State,
    object_count: usize,
    property_count: usize,
    total_attempts: usize,
}

impl<'a> WritePropertyMultipleCursor<'a> {
    /// Create a cursor over one WPM service request body.
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            offset: 0,
            state: State::Object,
            object_count: 0,
            property_count: 0,
            total_attempts: 0,
        }
    }

    /// Return the next unread byte offset.
    pub fn offset(&self) -> usize {
        self.offset
    }

    /// Decode the next object/list/write event without reading later attempts.
    pub fn next_event(
        &mut self,
    ) -> Result<Option<WritePropertyMultipleEvent>, WritePropertyMultipleCursorError> {
        match self.state {
            State::Done => Ok(None),
            State::Failed => Ok(None),
            State::Object => {
                if self.offset == self.data.len() {
                    self.state = State::Done;
                    return Ok(None);
                }
                if self.object_count >= MAX_DECODED_ITEMS {
                    return self.fail(self.limit_error("WPM object count exceeds limit"));
                }
                let oid = match self.decode_object_identifier() {
                    Ok(oid) => oid,
                    Err(error) => return self.fail(error),
                };
                if let Err(error) = self.decode_property_list_opening() {
                    return self.fail(error);
                }
                self.object_count += 1;
                self.property_count = 0;
                self.state = State::Properties(oid);
                Ok(Some(WritePropertyMultipleEvent::ObjectStart(oid)))
            }
            State::Properties(oid) => {
                if self.offset >= self.data.len() {
                    return self.fail(self.syntax_error(
                        self.offset,
                        WritePropertyMultipleDecodeStage::PropertyListEnd,
                        RejectReason::MISSING_REQUIRED_PARAMETER,
                        None,
                        "WPM property list is missing closing tag 1",
                    ));
                }
                let (tag, tag_end) = match tags::decode_tag(self.data, self.offset) {
                    Ok(decoded) => decoded,
                    Err(error) => {
                        return self.fail(self.syntax_error(
                            self.offset,
                            WritePropertyMultipleDecodeStage::PropertyIdentifier,
                            tag_reason(&error),
                            None,
                            described(&error),
                        ));
                    }
                };
                if tag.is_closing_tag(1) {
                    self.offset = tag_end;
                    self.state = State::Object;
                    return Ok(Some(WritePropertyMultipleEvent::ObjectEnd));
                }
                if tag.is_closing {
                    return self.fail(self.syntax_error(
                        self.offset,
                        WritePropertyMultipleDecodeStage::PropertyListEnd,
                        RejectReason::INVALID_TAG,
                        None,
                        "WPM property list has an unmatched closing tag",
                    ));
                }
                if self.property_count >= MAX_DECODED_ITEMS
                    || self.total_attempts >= MAX_DECODED_ITEMS
                {
                    return self.fail(self.limit_error("WPM property count exceeds limit"));
                }
                let (property, end) = match decode_bacnet_property_value_in_list_detailed(
                    self.data,
                    self.offset,
                    1,
                ) {
                    Ok(decoded) => decoded,
                    Err(error) => return self.fail(self.property_error(oid, error)),
                };
                self.offset = end;
                self.property_count += 1;
                self.total_attempts += 1;
                Ok(Some(WritePropertyMultipleEvent::WriteAttempt(
                    WritePropertyAttempt {
                        reference: BACnetObjectPropertyReference {
                            object_identifier: oid,
                            property_identifier: property.property_identifier.to_raw(),
                            property_array_index: property.property_array_index,
                        },
                        value: property.value,
                        priority: property.priority,
                    },
                )))
            }
        }
    }

    fn decode_object_identifier(
        &mut self,
    ) -> Result<ObjectIdentifier, WritePropertyMultipleCursorError> {
        let start = self.offset;
        let (tag, content_start) = tags::decode_tag(self.data, start).map_err(|error| {
            self.syntax_error(
                start,
                WritePropertyMultipleDecodeStage::ObjectIdentifier,
                tag_reason(&error),
                None,
                described(&error),
            )
        })?;
        if !tag.is_context(0) {
            return Err(self.syntax_error(
                start,
                WritePropertyMultipleDecodeStage::ObjectIdentifier,
                misplaced_kind(self.data, start, &tag, Some(0)).reject_reason(),
                None,
                "WPM object identifier must use primitive context tag 0",
            ));
        }
        let end = content_start
            .checked_add(tag.length as usize)
            .filter(|end| *end <= self.data.len())
            .ok_or_else(|| {
                self.syntax_error(
                    content_start,
                    WritePropertyMultipleDecodeStage::ObjectIdentifier,
                    RejectReason::MISSING_REQUIRED_PARAMETER,
                    None,
                    "WPM object identifier payload is truncated",
                )
            })?;
        if tag.length != 4 {
            return Err(self.syntax_error(
                content_start,
                WritePropertyMultipleDecodeStage::ObjectIdentifier,
                RejectReason::INVALID_DATA_ENCODING,
                None,
                "WPM object identifier must contain exactly four octets",
            ));
        }
        let oid = ObjectIdentifier::decode(&self.data[content_start..end]).map_err(|error| {
            self.syntax_error(
                content_start,
                WritePropertyMultipleDecodeStage::ObjectIdentifier,
                RejectReason::INVALID_DATA_ENCODING,
                None,
                described(&error),
            )
        })?;
        self.offset = end;
        Ok(oid)
    }

    fn decode_property_list_opening(&mut self) -> Result<(), WritePropertyMultipleCursorError> {
        if self.offset >= self.data.len() {
            return Err(self.syntax_error(
                self.offset,
                WritePropertyMultipleDecodeStage::PropertyList,
                RejectReason::MISSING_REQUIRED_PARAMETER,
                None,
                "WPM object is missing its property list",
            ));
        }
        let start = self.offset;
        let (tag, end) = tags::decode_tag(self.data, start).map_err(|error| {
            self.syntax_error(
                start,
                WritePropertyMultipleDecodeStage::PropertyList,
                tag_reason(&error),
                None,
                described(&error),
            )
        })?;
        if !tag.is_opening_tag(1) {
            return Err(self.syntax_error(
                start,
                WritePropertyMultipleDecodeStage::PropertyList,
                misplaced_kind(self.data, start, &tag, Some(1)).reject_reason(),
                None,
                "WPM expected opening tag 1 for the property list",
            ));
        }
        self.offset = end;
        Ok(())
    }

    fn property_error(
        &self,
        oid: ObjectIdentifier,
        error: PropertyValueDecodeError,
    ) -> WritePropertyMultipleCursorError {
        let stage = match error.stage {
            PropertyValueDecodeStage::PropertyIdentifier => {
                WritePropertyMultipleDecodeStage::PropertyIdentifier
            }
            PropertyValueDecodeStage::ArrayIndex => WritePropertyMultipleDecodeStage::ArrayIndex,
            PropertyValueDecodeStage::Value => WritePropertyMultipleDecodeStage::Value,
            PropertyValueDecodeStage::Priority => WritePropertyMultipleDecodeStage::Priority,
        };
        let reference = error
            .reference_complete
            .then(|| BACnetObjectPropertyReference {
                object_identifier: oid,
                property_identifier: error
                    .property_identifier
                    .expect("complete reference has a property")
                    .to_raw(),
                property_array_index: error.property_array_index,
            });
        let kind = match error.kind {
            PropertyValueDecodeFailure::Syntax(reason) => {
                WritePropertyMultipleFailureKind::Syntax(reason)
            }
            PropertyValueDecodeFailure::PriorityOutOfRange => {
                WritePropertyMultipleFailureKind::PriorityOutOfRange
            }
        };
        cursor_error(
            error.offset,
            stage,
            kind,
            reference,
            described(&error.error),
        )
    }

    fn limit_error(&self, label: &'static str) -> WritePropertyMultipleCursorError {
        // An item limit is a buffer capacity, as for every decoder (#1446).
        self.syntax_error(
            self.offset,
            WritePropertyMultipleDecodeStage::ItemLimit,
            RejectReason::BUFFER_OVERFLOW,
            None,
            label,
        )
    }

    fn syntax_error(
        &self,
        offset: usize,
        stage: WritePropertyMultipleDecodeStage,
        reject_reason: RejectReason,
        first_failed_write_attempt: Option<BACnetObjectPropertyReference>,
        described: impl Into<Described>,
    ) -> WritePropertyMultipleCursorError {
        cursor_error(
            offset,
            stage,
            WritePropertyMultipleFailureKind::Syntax(reject_reason),
            first_failed_write_attempt,
            described.into(),
        )
    }

    fn fail<T>(
        &mut self,
        error: WritePropertyMultipleCursorError,
    ) -> Result<T, WritePropertyMultipleCursorError> {
        self.state = State::Failed;
        Err(error)
    }
}

/// A refusal's static label and the numbers its placeholders stand for.
struct Described(&'static str, [u64; 2]);

impl From<&'static str> for Described {
    fn from(label: &'static str) -> Self {
        Self(label, [0; 2])
    }
}

/// How a decoder's `error` reads, without formatting it: the label and
/// numbers [`Error::to_decode_error`] gives it.
fn described(error: &Error) -> Described {
    let refused = error.to_decode_error(0);
    Described(refused.label, refused.values)
}

/// The cursor's refusal at `offset`, its static error built from `described`.
fn cursor_error(
    offset: usize,
    stage: WritePropertyMultipleDecodeStage,
    kind: WritePropertyMultipleFailureKind,
    first_failed_write_attempt: Option<BACnetObjectPropertyReference>,
    Described(label, values): Described,
) -> WritePropertyMultipleCursorError {
    let mut error = DecodeError::new(super::failure_kind(kind), offset, label).within(stage.name());
    error.values = values;
    WritePropertyMultipleCursorError {
        offset,
        stage,
        kind,
        first_failed_write_attempt,
        error,
    }
}

/// The Reject reason for a tag header that didn't decode: the data ended
/// (MISSING_REQUIRED_PARAMETER) or the header is malformed (INVALID_TAG), the
/// reasons every confirmed request gets (#1446).
fn tag_reason(error: &Error) -> RejectReason {
    error.reject_reason().unwrap_or(RejectReason::INVALID_TAG)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::BACnetPropertyValue;
    use crate::wpm::{WriteAccessSpecification, WritePropertyMultipleRequest};
    use bacnet_encoding::constructed::encode_bacnet_property_value;
    use bacnet_encoding::{primitives, tags};
    use bacnet_types::enums::{ObjectType, PropertyIdentifier};
    use bytes::BytesMut;

    fn oid(object_type: ObjectType, instance: u32) -> ObjectIdentifier {
        ObjectIdentifier::new(object_type, instance).unwrap()
    }

    fn property(property_identifier: PropertyIdentifier) -> BACnetPropertyValue {
        let mut value = BytesMut::new();
        primitives::encode_app_null(&mut value);
        BACnetPropertyValue {
            property_identifier,
            property_array_index: None,
            value: value.to_vec(),
            priority: None,
        }
    }

    // Inbound fixtures intentionally include requests rejected by the outbound
    // typed contract. Construct their wire grammar directly.
    fn encode(specs: Vec<WriteAccessSpecification>) -> BytesMut {
        let mut data = BytesMut::new();
        for spec in specs {
            primitives::encode_ctx_object_id(&mut data, 0, &spec.object_identifier);
            tags::encode_opening_tag(&mut data, 1);
            for property in spec.list_of_properties {
                encode_bacnet_property_value(&property, &mut data);
            }
            tags::encode_closing_tag(&mut data, 1);
        }
        data
    }

    fn attempts(data: &[u8]) -> Vec<WritePropertyAttempt> {
        let mut cursor = WritePropertyMultipleCursor::new(data);
        let mut attempts = Vec::new();
        while let Some(event) = cursor.next_event().unwrap() {
            if let WritePropertyMultipleEvent::WriteAttempt(attempt) = event {
                attempts.push(attempt);
            }
        }
        attempts
    }

    #[test]
    fn yields_multi_object_and_property_attempts_in_wire_order() {
        let first = oid(ObjectType::ANALOG_OUTPUT, 1);
        let second = oid(ObjectType::BINARY_OUTPUT, 2);
        let data = encode(vec![
            WriteAccessSpecification {
                object_identifier: first,
                list_of_properties: vec![
                    property(PropertyIdentifier::DESCRIPTION),
                    property(PropertyIdentifier::PRESENT_VALUE),
                ],
            },
            WriteAccessSpecification {
                object_identifier: second,
                list_of_properties: vec![property(PropertyIdentifier::OUT_OF_SERVICE)],
            },
        ]);

        let coordinates: Vec<_> = attempts(&data)
            .into_iter()
            .map(|attempt| {
                (
                    attempt.reference.object_identifier,
                    attempt.reference.property_identifier,
                )
            })
            .collect();
        assert_eq!(
            coordinates,
            vec![
                (first, PropertyIdentifier::DESCRIPTION.to_raw()),
                (first, PropertyIdentifier::PRESENT_VALUE.to_raw()),
                (second, PropertyIdentifier::OUT_OF_SERVICE.to_raw()),
            ]
        );
    }

    #[test]
    fn empty_request_and_empty_property_lists_are_noops() {
        assert!(attempts(&[]).is_empty());
        let object = oid(ObjectType::BINARY_VALUE, 1);
        let data = encode(vec![WriteAccessSpecification {
            object_identifier: object,
            list_of_properties: vec![],
        }]);
        let mut cursor = WritePropertyMultipleCursor::new(&data);
        assert_eq!(
            cursor.next_event().unwrap(),
            Some(WritePropertyMultipleEvent::ObjectStart(object))
        );
        assert_eq!(
            cursor.next_event().unwrap(),
            Some(WritePropertyMultipleEvent::ObjectEnd)
        );
        assert_eq!(cursor.next_event().unwrap(), None);
        assert_eq!(
            WritePropertyMultipleRequest::decode(&data)
                .unwrap()
                .list_of_write_access_specs[0]
                .list_of_properties,
            vec![]
        );
    }

    fn first_error(data: &[u8]) -> WritePropertyMultipleCursorError {
        let mut cursor = WritePropertyMultipleCursor::new(data);
        loop {
            match cursor.next_event() {
                Ok(Some(_)) => {}
                Ok(None) => panic!("expected malformed request"),
                Err(error) => return error,
            }
        }
    }

    #[test]
    fn pre_write_failures_use_narrow_reject_classifications() {
        let object = oid(ObjectType::BINARY_VALUE, 1);
        let mut object_bytes = BytesMut::new();
        primitives::encode_ctx_object_id(&mut object_bytes, 0, &object);

        // A later member where the [0] object identifier is due: it is
        // missing (#1446).
        let mut wrong_context = object_bytes.clone();
        wrong_context[0] = 0x1c;
        assert_eq!(
            first_error(&wrong_context).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::MISSING_REQUIRED_PARAMETER)
        );

        assert_eq!(
            first_error(&object_bytes).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::MISSING_REQUIRED_PARAMETER)
        );

        // An application tag there doesn't fit, and an identifier cut short
        // is missing octets, as for every confirmed request (#1446).
        let mut wrong_type = BytesMut::new();
        primitives::encode_app_object_id(&mut wrong_type, &object);
        assert_eq!(
            first_error(&wrong_type).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::INVALID_TAG)
        );

        assert_eq!(
            first_error(&[0x0c, 0, 0, 0]).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::MISSING_REQUIRED_PARAMETER)
        );

        let invalid_priority = encode(vec![WriteAccessSpecification {
            object_identifier: object,
            list_of_properties: vec![BACnetPropertyValue {
                priority: Some(17),
                ..property(PropertyIdentifier::PRESENT_VALUE)
            }],
        }]);
        let error = first_error(&invalid_priority);
        assert_eq!(
            error.kind,
            WritePropertyMultipleFailureKind::PriorityOutOfRange
        );
        assert_eq!(error.stage, WritePropertyMultipleDecodeStage::Priority);
        assert!(error.first_failed_write_attempt.is_some());

        let mut unexpected = encode(vec![WriteAccessSpecification {
            object_identifier: object,
            list_of_properties: vec![property(PropertyIdentifier::DESCRIPTION)],
        }]);
        unexpected.truncate(unexpected.len() - 1);
        unexpected.extend_from_slice(&[0x49, 0x00, 0x1f]);
        let error = first_error(&unexpected);
        assert_eq!(
            error.kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::INVALID_TAG)
        );
        assert!(error.first_failed_write_attempt.is_some());

        let mut malformed_value = object_bytes.clone();
        tags::encode_opening_tag(&mut malformed_value, 1);
        primitives::encode_ctx_unsigned(
            &mut malformed_value,
            0,
            PropertyIdentifier::DESCRIPTION.to_raw() as u64,
        );
        tags::encode_opening_tag(&mut malformed_value, 2);
        let mut cut_value = malformed_value.clone();
        cut_value.extend_from_slice(&[0x75, 10, b'x', 0x2f, 0x1f]);
        assert_eq!(
            first_error(&cut_value).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::MISSING_REQUIRED_PARAMETER)
        );
        // A value nested deeper than the decoder walks holds an opening tag
        // it can't take.
        malformed_value.extend_from_slice(&[0x3E; 40]);
        assert_eq!(
            first_error(&malformed_value).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::INVALID_TAG)
        );
    }

    #[test]
    fn value_opening_failures_keep_the_completed_property_reference() {
        let object = oid(ObjectType::BINARY_VALUE, 1);
        let property = PropertyIdentifier::OBJECT_TYPE;

        for (array_index, terminate_with_wrong_tag) in [(Some(4), false), (None, true)] {
            let mut data = BytesMut::new();
            primitives::encode_ctx_object_id(&mut data, 0, &object);
            tags::encode_opening_tag(&mut data, 1);
            primitives::encode_ctx_unsigned(&mut data, 0, property.to_raw() as u64);
            if let Some(index) = array_index {
                primitives::encode_ctx_unsigned(&mut data, 1, index as u64);
            }
            if terminate_with_wrong_tag {
                tags::encode_closing_tag(&mut data, 1);
            }

            let error = first_error(&data);
            assert_eq!(error.stage, WritePropertyMultipleDecodeStage::Value);
            let reference = error
                .first_failed_write_attempt
                .expect("the property coordinate is complete before value framing");
            assert_eq!(reference.object_identifier, object);
            assert_eq!(reference.property_identifier, property.to_raw());
            assert_eq!(reference.property_array_index, array_index);
        }
    }

    #[test]
    fn total_attempt_bound_prevents_unbounded_collection() {
        let object = oid(ObjectType::BINARY_VALUE, 1);
        let data = encode(vec![WriteAccessSpecification {
            object_identifier: object,
            list_of_properties: (0..=MAX_DECODED_ITEMS)
                .map(|_| property(PropertyIdentifier::DESCRIPTION))
                .collect(),
        }]);
        let error = first_error(&data);
        assert_eq!(
            error.kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::BUFFER_OVERFLOW)
        );
        assert_eq!(error.stage, WritePropertyMultipleDecodeStage::ItemLimit);
    }

    #[test]
    fn unmatched_closing_tag_is_invalid_tag() {
        let object = oid(ObjectType::BINARY_VALUE, 1);
        let mut data = BytesMut::new();
        primitives::encode_ctx_object_id(&mut data, 0, &object);
        tags::encode_opening_tag(&mut data, 1);
        tags::encode_closing_tag(&mut data, 2);
        assert_eq!(
            first_error(&data).kind,
            WritePropertyMultipleFailureKind::Syntax(RejectReason::INVALID_TAG)
        );
    }
}