Skip to main content

opcua_kit/ua/
value.rs

1//! Built-in values, field masks and structured extension payloads from OPC UA Part 6.
2use super::*;
3use std::{
4    any::Any,
5    fmt,
6    io::{Read, Write},
7    sync::Arc,
8};
9
10/// A Rust type with one built-in scalar representation on the wire.
11pub trait VariantType {
12    /// Built-in type identifier used when declaring a variable or array element.
13    fn variant_type_id() -> VariantScalarTypeId;
14}
15
16/// A homogeneous array in row-major order. Products of matrix dimensions must match the value count.
17#[derive(Clone, Debug, PartialEq)]
18pub struct Array {
19    /// Built-in type carried by every element. Use Variant for heterogeneous arrays.
20    pub value_type: VariantScalarTypeId,
21    pub values: Vec<Variant>,
22    /// Present for matrices with at least two nonzero dimensions.
23    pub dimensions: Option<Vec<u32>>,
24}
25
26// The wire IDs and payload types are defined together so scalar and array codecs agree.
27macro_rules! builtins {
28    ($( $id:literal $kind:ident $ty:ty => $payload:ty ),+ $(,)?) => {
29        /// Part 6 built-in IDs used in the Variant encoding mask.
30        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
31        #[repr(u8)]
32        pub enum VariantScalarTypeId {
33            $( $kind = $id, )+
34            XmlElement = 16, Variant = 24,
35            Reserved26 = 26, Reserved27 = 27, Reserved28 = 28, Reserved29 = 29, Reserved30 = 30, Reserved31 = 31,
36        }
37
38        /// A tagged OPC UA value. Arrays carry their element type even when empty.
39        #[derive(Clone, Debug, PartialEq, Default)]
40        pub enum Variant {
41            #[default]
42            Empty,
43            $( $kind($payload), )+
44            XmlElement(UAString),
45            Array(Box<Array>),
46            /// A typed array with a wire length of −1.
47            NullArray(VariantScalarTypeId),
48            /// A future built-in type in the reserved range 26–31, received as a ByteString.
49            Reserved(VariantScalarTypeId, ByteString),
50        }
51
52        impl TryFrom<u8> for VariantScalarTypeId {
53            type Error = StatusCode;
54            fn try_from(id: u8) -> Result<Self, Self::Error> {
55                match id {
56                    $( $id => Ok(Self::$kind), )+
57                    16 => Ok(Self::XmlElement),
58                    24 => Ok(Self::Variant),
59                    26 => Ok(Self::Reserved26),
60                    27 => Ok(Self::Reserved27),
61                    28 => Ok(Self::Reserved28),
62                    29 => Ok(Self::Reserved29),
63                    30 => Ok(Self::Reserved30),
64                    31 => Ok(Self::Reserved31),
65                    _ => Err(StatusCode::BadDecodingError),
66                }
67            }
68        }
69
70        impl Variant {
71            /// Built-in ID for a non-null scalar. Arrays carry the element ID in their array value.
72            pub fn scalar_type_id(&self) -> Option<VariantScalarTypeId> {
73                match self {
74                    $( Self::$kind(_) => Some(VariantScalarTypeId::$kind), )+
75                    Self::XmlElement(_) => Some(VariantScalarTypeId::XmlElement),
76                    Self::Reserved(kind, _) => Some(*kind),
77                    Self::Empty | Self::Array(_) | Self::NullArray(_) => None,
78                }
79            }
80
81            fn decode_element<R: Read+?Sized>(t: VariantScalarTypeId, r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
82                match t {
83                    $( VariantScalarTypeId::$kind => Ok(Self::$kind(<$payload>::decode(r, c)?)), )+
84                    VariantScalarTypeId::XmlElement => Ok(Self::XmlElement(UAString::decode(r, c)?)),
85                    VariantScalarTypeId::Variant => Self::decode(r, c),
86                    _ => Ok(Self::Reserved(t, ByteString::decode(r, c)?)),
87                }
88            }
89
90            fn encode_element<W: Write+?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
91                match self {
92                    $( Self::$kind(v) => v.encode(w, c), )+
93                    Self::XmlElement(v) => v.encode(w, c),
94                    _ => Err(StatusCode::BadEncodingError),
95                }
96            }
97        }
98        $(
99            impl From<$ty> for Variant {
100                fn from(v: $ty) -> Self { Self::$kind(v.into()) }
101            }
102            impl VariantType for $ty {
103                fn variant_type_id() -> VariantScalarTypeId { VariantScalarTypeId::$kind }
104            }
105        )+
106    }
107}
108
109builtins! {
110    1 Boolean bool => bool, 2 SByte i8 => i8, 3 Byte u8 => u8, 4 Int16 i16 => i16,
111    5 UInt16 u16 => u16, 6 Int32 i32 => i32, 7 UInt32 u32 => u32, 8 Int64 i64 => i64,
112    9 UInt64 u64 => u64, 10 Float f32 => f32, 11 Double f64 => f64, 12 String UAString => UAString,
113    13 DateTime DateTime => Box<DateTime>, 14 Guid Guid => Box<Guid>, 15 ByteString ByteString => ByteString,
114    17 NodeId NodeId => Box<NodeId>, 18 ExpandedNodeId ExpandedNodeId => Box<ExpandedNodeId>,
115    19 StatusCode StatusCode => StatusCode, 20 QualifiedName QualifiedName => Box<QualifiedName>,
116    21 LocalizedText LocalizedText => Box<LocalizedText>, 22 ExtensionObject ExtensionObject => ExtensionObject,
117    23 DataValue DataValue => Box<DataValue>, 25 DiagnosticInfo DiagnosticInfo => Box<DiagnosticInfo>,
118}
119
120impl From<String> for Variant {
121    fn from(v: String) -> Self {
122        Self::String(v.into())
123    }
124}
125impl From<&str> for Variant {
126    fn from(v: &str) -> Self {
127        Self::String(v.into())
128    }
129}
130impl VariantType for String {
131    fn variant_type_id() -> VariantScalarTypeId {
132        VariantScalarTypeId::String
133    }
134}
135impl VariantType for &str {
136    fn variant_type_id() -> VariantScalarTypeId {
137        VariantScalarTypeId::String
138    }
139}
140impl VariantType for Variant {
141    fn variant_type_id() -> VariantScalarTypeId {
142        VariantScalarTypeId::Variant
143    }
144}
145impl<T: Into<Variant> + VariantType> From<Vec<T>> for Variant {
146    fn from(items: Vec<T>) -> Self {
147        Self::Array(Box::new(Array {
148            value_type: T::variant_type_id(),
149            values: items.into_iter().map(Into::into).collect(),
150            dimensions: None,
151        }))
152    }
153}
154
155fn dimensions_match(dims: &[u32], count: usize) -> bool {
156    dims.len() >= 2
157        && dims.iter().all(|&d| d > 0 && d <= i32::MAX as u32)
158        && dims
159            .iter()
160            .try_fold(1usize, |n, &d| n.checked_mul(d as usize))
161            == Some(count)
162}
163
164impl BinaryEncodable for Variant {
165    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
166        let c = &c.nested()?;
167        match self {
168            Self::Empty => 0u8.encode(w, c),
169            Self::Reserved(_, _) => Err(StatusCode::BadEncodingError),
170            Self::NullArray(kind) => {
171                if *kind as u8 > 25 {
172                    return Err(StatusCode::BadEncodingError);
173                }
174                (0x80 | *kind as u8).encode(w, c)?;
175                (-1i32).encode(w, c)
176            }
177            Self::Array(a) => {
178                if a.value_type as u8 > 25
179                    || a.dimensions
180                        .as_ref()
181                        .is_some_and(|d| !dimensions_match(d, a.values.len()))
182                {
183                    return Err(StatusCode::BadEncodingError);
184                }
185                if a.values.len() > c.max_array_length {
186                    return Err(StatusCode::BadEncodingLimitsExceeded);
187                }
188                let len = i32::try_from(a.values.len())
189                    .map_err(|_| StatusCode::BadEncodingLimitsExceeded)?;
190                let mask = if a.dimensions.is_some() { 0xc0 } else { 0x80 };
191                (mask | a.value_type as u8).encode(w, c)?;
192                len.encode(w, c)?;
193                for value in &a.values {
194                    if a.value_type == VariantScalarTypeId::Variant {
195                        value.encode(w, c)?;
196                    } else if value.scalar_type_id() == Some(a.value_type) {
197                        value.encode_element(w, c)?;
198                    } else {
199                        return Err(StatusCode::BadEncodingError);
200                    }
201                }
202                if a.dimensions.is_some() {
203                    a.dimensions.encode(w, c)?;
204                }
205                Ok(())
206            }
207            value => {
208                let kind = value.scalar_type_id().ok_or(StatusCode::BadEncodingError)?;
209                (kind as u8).encode(w, c)?;
210                value.encode_element(w, c)
211            }
212        }
213    }
214}
215
216impl BinaryDecodable for Variant {
217    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
218        let c = &c.nested()?;
219        let mask = u8::decode(r, c)?;
220        if mask == 0 {
221            return Ok(Self::Empty);
222        }
223        let kind = VariantScalarTypeId::try_from(mask & 0x3f)?;
224        if mask & 0x80 == 0 {
225            if mask & 0x40 != 0 || kind == VariantScalarTypeId::Variant {
226                return Err(StatusCode::BadDecodingError);
227            }
228            return Self::decode_element(kind, r, c);
229        }
230        let count = i32::decode(r, c)?;
231        if count == -1 && mask & 0x40 == 0 {
232            return Ok(Self::NullArray(kind));
233        }
234        let count = usize::try_from(count).map_err(|_| StatusCode::BadDecodingError)?;
235        if count > c.max_array_length {
236            return Err(StatusCode::BadEncodingLimitsExceeded);
237        }
238        c.charge::<Array>(1)?;
239        let values = super::binary::decode_array(count, c, || Self::decode_element(kind, r, c))?;
240        let dimensions = if mask & 0x40 != 0 {
241            let dims = Option::<Vec<u32>>::decode(r, c)?.ok_or(StatusCode::BadDecodingError)?;
242            if !dimensions_match(&dims, count) {
243                return Err(StatusCode::BadDecodingError);
244            }
245            Some(dims)
246        } else {
247            None
248        };
249        Ok(Self::Array(Box::new(Array {
250            value_type: kind,
251            values,
252            dimensions,
253        })))
254    }
255}
256
257#[derive(Clone, Default, Debug, PartialEq)]
258/// A value with independent source and server clocks, quality, and 10-picosecond increments.
259pub struct DataValue {
260    pub value: Option<Variant>,
261    pub status: Option<StatusCode>,
262    pub source_timestamp: Option<DateTime>,
263    pub source_picoseconds: Option<u16>,
264    pub server_timestamp: Option<DateTime>,
265    pub server_picoseconds: Option<u16>,
266}
267
268impl DataValue {
269    /// The effective status. An absent status field carries Good severity.
270    pub fn status(&self) -> StatusCode {
271        self.status.unwrap_or_default()
272    }
273
274    pub fn set_timestamps(
275        &mut self,
276        selection: TimestampsToReturn,
277        source: DateTime,
278        server: DateTime,
279    ) {
280        let has_source = matches!(
281            selection,
282            TimestampsToReturn::Source | TimestampsToReturn::Both
283        );
284        let has_server = matches!(
285            selection,
286            TimestampsToReturn::Server | TimestampsToReturn::Both
287        );
288        if !has_source || self.source_timestamp != Some(source) {
289            self.source_picoseconds = None;
290        }
291        if !has_server || self.server_timestamp != Some(server) {
292            self.server_picoseconds = None;
293        }
294        self.source_timestamp = has_source.then_some(source);
295        self.server_timestamp = has_server.then_some(server);
296    }
297    pub fn null() -> Self {
298        Self::default()
299    }
300    pub fn value_only<V: Into<Variant>>(value: V) -> Self {
301        Self {
302            value: Some(value.into()),
303            ..Self::default()
304        }
305    }
306    pub fn new_now<V: Into<Variant>>(value: V) -> Self {
307        let now = DateTime::now();
308        Self {
309            source_timestamp: Some(now),
310            server_timestamp: Some(now),
311            ..Self::value_only(value)
312        }
313    }
314}
315macro_rules! data_from {
316    ($($ty:ty),+) => {$(impl From<$ty> for DataValue {
317        fn from(v:$ty)->Self {Self::value_only(v)}
318    })+};
319}
320data_from!(
321    Variant, bool, i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, String, UAString, ByteString
322);
323
324macro_rules! masked_structure {
325    ($name:ident,$allowed:literal, $( $bit:literal $field:ident : $ty:ty ),+ $(,)?)=>{
326        impl BinaryEncodable for $name {
327            fn encode<W:Write+?Sized>(&self,w:&mut W,c:&Context<'_>)->Result<(),StatusCode>{
328                let c=&c.nested()?;
329                let mask=0u8 $(| if self.$field.is_some() {$bit} else {0})+;
330                mask.encode(w,c)?;
331                $(if let Some(value)=&self.$field {value.encode(w,c)?;})+
332                Ok(())
333            }
334        }
335        impl BinaryDecodable for $name {
336            fn decode<R:Read+?Sized>(r:&mut R,c:&Context<'_>)->Result<Self,StatusCode>{
337                let c=&c.nested()?;
338                let mask=u8::decode(r,c)?;
339                if mask & !$allowed !=0{return Err(StatusCode::BadDecodingError);}
340                Ok(Self{$($field: if mask & $bit !=0 {Some(<$ty>::decode(r,c)?)}else{None}),+})
341            }
342        }
343    }
344}
345masked_structure!(DataValue,0x3f,1 value:Variant,2 status:StatusCode,4 source_timestamp:DateTime,
346    16 source_picoseconds:u16,8 server_timestamp:DateTime,32 server_picoseconds:u16);
347
348/// Indexes refer to the string table carried in the ResponseHeader.
349#[derive(Clone, Default, Debug, PartialEq)]
350pub struct DiagnosticInfo {
351    pub symbolic_id: Option<i32>,
352    pub namespace_uri: Option<i32>,
353    pub locale: Option<i32>,
354    pub localized_text: Option<i32>,
355    pub additional_info: Option<UAString>,
356    pub inner_status_code: Option<StatusCode>,
357    pub inner_diagnostic_info: Option<Box<DiagnosticInfo>>,
358}
359masked_structure!(DiagnosticInfo,0x7f,1 symbolic_id:i32,2 namespace_uri:i32,8 locale:i32,
360    4 localized_text:i32,16 additional_info:UAString,32 inner_status_code:StatusCode,
361    64 inner_diagnostic_info:Box<DiagnosticInfo>);
362
363trait ExtensionValue: fmt::Debug + Send + Sync {
364    fn as_any(&self) -> &dyn Any;
365    fn equivalent(&self, other: &dyn ExtensionValue) -> bool;
366    fn encode_body(&self, w: &mut dyn Write, c: &Context<'_>) -> Result<(), StatusCode>;
367}
368impl<T> ExtensionValue for T
369where
370    T: BinaryEncodable + fmt::Debug + PartialEq + Send + Sync + 'static,
371{
372    fn as_any(&self) -> &dyn Any {
373        self
374    }
375    fn equivalent(&self, other: &dyn ExtensionValue) -> bool {
376        other.as_any().downcast_ref::<T>() == Some(self)
377    }
378    fn encode_body(&self, w: &mut dyn Write, c: &Context<'_>) -> Result<(), StatusCode> {
379        self.encode(w, c)
380    }
381}
382
383#[derive(Clone, Debug)]
384enum ExtensionBody {
385    None,
386    Known(Arc<dyn ExtensionValue>),
387    Opaque { xml: bool, bytes: ByteString },
388}
389
390/// An encoded structure identified by its DataTypeEncoding NodeId. Unknown structures retain their original bytes.
391#[derive(Clone, Debug)]
392pub struct ExtensionObject {
393    type_id: NodeId,
394    body: ExtensionBody,
395}
396impl PartialEq for ExtensionObject {
397    fn eq(&self, other: &Self) -> bool {
398        self.type_id == other.type_id
399            && match (&self.body, &other.body) {
400                (ExtensionBody::None, ExtensionBody::None) => true,
401                (ExtensionBody::Known(a), ExtensionBody::Known(b)) => a.equivalent(b.as_ref()),
402                (
403                    ExtensionBody::Opaque { xml: a, bytes: av },
404                    ExtensionBody::Opaque { xml: b, bytes: bv },
405                ) => a == b && av == bv,
406                _ => false,
407            }
408    }
409}
410impl Default for ExtensionObject {
411    fn default() -> Self {
412        Self {
413            type_id: NodeId::default(),
414            body: ExtensionBody::None,
415        }
416    }
417}
418impl ExtensionObject {
419    pub fn new<T>(value: T) -> Self
420    where
421        T: MessageInfo + BinaryEncodable + fmt::Debug + PartialEq + Send + Sync + 'static,
422    {
423        Self {
424            type_id: NodeId::from(MessageInfo::type_id(&value) as u32),
425            body: ExtensionBody::Known(Arc::new(value)),
426        }
427    }
428    pub(super) fn decode_known<T>(bytes: &mut &[u8], c: &Context<'_>) -> Result<Self, StatusCode>
429    where
430        T: MessageInfo
431            + BinaryEncodable
432            + BinaryDecodable
433            + fmt::Debug
434            + PartialEq
435            + Send
436            + Sync
437            + 'static,
438    {
439        // The type-erased Arc stores the decoded structure and its strong/weak counters.
440        c.charge::<T>(1)?;
441        c.charge::<usize>(2)?;
442        Ok(Self::new(T::decode(bytes, c)?))
443    }
444
445    pub fn from_message<T>(value: T) -> Self
446    where
447        T: MessageInfo + BinaryEncodable + fmt::Debug + PartialEq + Send + Sync + 'static,
448    {
449        Self::new(value)
450    }
451    pub fn null() -> Self {
452        Self::default()
453    }
454    pub fn is_null(&self) -> bool {
455        self.type_id.is_null() && matches!(self.body, ExtensionBody::None)
456    }
457    /// Wrap host-encoded UA Binary for a vendor-defined DataTypeEncoding.
458    pub fn from_binary(encoding_id: NodeId, bytes: ByteString) -> Self {
459        Self {
460            type_id: encoding_id,
461            body: ExtensionBody::Opaque { xml: false, bytes },
462        }
463    }
464
465    pub fn encoding_id(&self) -> &NodeId {
466        &self.type_id
467    }
468    pub fn inner_as<T: 'static>(&self) -> Option<&T> {
469        let ExtensionBody::Known(value) = &self.body else {
470            return None;
471        };
472        value.as_any().downcast_ref()
473    }
474    /// Return the wire body of an unrecognized type and whether it uses XML encoding.
475    pub fn opaque_body(&self) -> Option<(&ByteString, bool)> {
476        let ExtensionBody::Opaque { xml, bytes } = &self.body else {
477            return None;
478        };
479        Some((bytes, *xml))
480    }
481}
482
483impl BinaryEncodable for ExtensionObject {
484    fn encode<W: Write + ?Sized>(&self, w: &mut W, c: &Context<'_>) -> Result<(), StatusCode> {
485        self.type_id.encode(w, c)?;
486        match &self.body {
487            ExtensionBody::None => 0u8.encode(w, c),
488            ExtensionBody::Known(value) => {
489                let c = &c.nested()?;
490                let mut body = super::binary::BoundedBuffer::new(
491                    c.max_byte_string_length.min(i32::MAX as usize),
492                );
493                value.encode_body(&mut body, c)?;
494                1u8.encode(w, c)?;
495                super::binary::write_bytes(Some(&body.into_vec()), w, c)
496            }
497            ExtensionBody::Opaque { xml, bytes } => {
498                (if *xml { 2u8 } else { 1u8 }).encode(w, c)?;
499                bytes.encode(w, c)
500            }
501        }
502    }
503}
504impl BinaryDecodable for ExtensionObject {
505    fn decode<R: Read + ?Sized>(r: &mut R, c: &Context<'_>) -> Result<Self, StatusCode> {
506        let type_id = NodeId::decode(r, c)?;
507        let tag = u8::decode(r, c)?;
508        if tag == 0 {
509            return Ok(Self {
510                type_id,
511                body: ExtensionBody::None,
512            });
513        }
514        if tag != 1 && tag != 2 {
515            return Err(StatusCode::BadDecodingError);
516        }
517        let bytes = ByteString::decode(r, c)?;
518        if tag == 1
519            && type_id.namespace == 0
520            && let Identifier::Numeric(id) = type_id.identifier
521            && let Some(body) = bytes.value.as_deref()
522            && let Some(value) = super::decode_extension(id, body, &c.nested()?)?
523        {
524            return Ok(value);
525        }
526        Ok(Self {
527            type_id,
528            body: ExtensionBody::Opaque {
529                xml: tag == 2,
530                bytes,
531            },
532        })
533    }
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539
540    #[test]
541    fn nested_arrays_share_the_message_budget_and_fresh_messages_reset_it() {
542        let input = Variant::from(vec![Variant::from(vec![1u8, 2]), Variant::from(vec![3u8])]);
543        let mut encoded = Vec::new();
544        let config = ContextOwned::default();
545        input.encode(&mut encoded, &config.context()).unwrap();
546        // Three Array boxes, two outer Variant entries and three inner entries.
547        let required = 3 * size_of::<Array>() + 5 * size_of::<Variant>();
548        let config = ContextOwned(DecodingOptions {
549            max_allocation_bytes: required,
550            ..Default::default()
551        });
552        let msg = config.context();
553        assert_eq!(
554            Variant::decode(&mut encoded.as_slice(), &msg).unwrap(),
555            input
556        );
557        assert_eq!(
558            Variant::decode(&mut encoded.as_slice(), &msg),
559            Err(StatusCode::BadEncodingLimitsExceeded)
560        );
561        assert_eq!(
562            Variant::decode(&mut encoded.as_slice(), &config.context()).unwrap(),
563            input
564        );
565        let tight = ContextOwned(DecodingOptions {
566            max_allocation_bytes: required - 1,
567            ..Default::default()
568        });
569        assert_eq!(
570            Variant::decode(&mut encoded.as_slice(), &tight.context()),
571            Err(StatusCode::BadEncodingLimitsExceeded)
572        );
573    }
574
575    #[test]
576    fn extension_body_and_decoded_fields_both_consume_the_budget() {
577        let info = EUInformation {
578            namespace_uri: "urn:fixture".into(),
579            ..Default::default()
580        };
581        let config = ContextOwned::default();
582        let mut body = Vec::new();
583        info.encode(&mut body, &config.context()).unwrap();
584        let limit =
585            body.len() + size_of::<EUInformation>() + 2 * size_of::<usize>() + "urn:fixture".len();
586        let object = ExtensionObject::new(info);
587        let mut encoded = Vec::new();
588        object.encode(&mut encoded, &config.context()).unwrap();
589        let config = ContextOwned(DecodingOptions {
590            max_allocation_bytes: limit,
591            ..Default::default()
592        });
593        assert_eq!(
594            ExtensionObject::decode(&mut encoded.as_slice(), &config.context()).unwrap(),
595            object
596        );
597        let tight = ContextOwned(DecodingOptions {
598            max_allocation_bytes: limit - 1,
599            ..Default::default()
600        });
601        assert_eq!(
602            ExtensionObject::decode(&mut encoded.as_slice(), &tight.context()),
603            Err(StatusCode::BadEncodingLimitsExceeded)
604        );
605    }
606
607    #[test]
608    fn timestamp_selection_preserves_absent_and_observed_picoseconds() {
609        let now = DateTime::now();
610        let mut value = DataValue {
611            source_timestamp: Some(now),
612            source_picoseconds: Some(17),
613            ..Default::default()
614        };
615        value.set_timestamps(TimestampsToReturn::Both, now, now);
616        assert_eq!(value.source_picoseconds, Some(17));
617        assert_eq!(value.server_picoseconds, None);
618        value.set_timestamps(TimestampsToReturn::Server, now, now);
619        assert_eq!(value.source_timestamp, None);
620        assert_eq!(value.source_picoseconds, None);
621    }
622
623    #[test]
624    fn typed_nulls_and_variant_arrays_preserve_their_wire_types() {
625        let c = ContextOwned::default();
626        for bytes in [
627            &[0x87, 255, 255, 255, 255][..],
628            &[0x98, 2, 0, 0, 0, 0, 1, 1],
629            &[0x87, 0, 0, 0, 0],
630        ] {
631            let v = Variant::decode(&mut &*bytes, &c.context()).unwrap();
632            let mut roundtrip = Vec::new();
633            v.encode(&mut roundtrip, &c.context()).unwrap();
634            assert_eq!(roundtrip, bytes);
635        }
636        let future = Variant::decode(&mut &[28, 1, 0, 0, 0, 9][..], &c.context()).unwrap();
637        assert!(matches!(
638            future,
639            Variant::Reserved(VariantScalarTypeId::Reserved28, _)
640        ));
641        assert!(future.encode(&mut Vec::new(), &c.context()).is_err());
642    }
643
644    #[test]
645    fn unknown_extension_preserves_namespace_id_and_payload() {
646        let c = ContextOwned::default();
647        let object =
648            ExtensionObject::from_binary(NodeId::new(3, "ValveEncoding"), vec![0, 1, 255].into());
649        let mut encoded = Vec::new();
650        object.encode(&mut encoded, &c.context()).unwrap();
651        let decoded = ExtensionObject::decode(&mut encoded.as_slice(), &c.context()).unwrap();
652        assert_eq!(decoded, object);
653        assert_eq!(decoded.encoding_id(), &NodeId::new(3, "ValveEncoding"));
654        let (bytes, xml) = decoded.opaque_body().unwrap();
655        assert_eq!(bytes.as_ref(), [0, 1, 255]);
656        assert!(!xml);
657    }
658
659    #[test]
660    fn inconsistent_matrices_and_excessive_nesting_are_rejected() {
661        let c = ContextOwned::default();
662        let bytes = [0xc3, 1, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0];
663        assert_eq!(
664            Variant::decode(&mut &bytes[..], &c.context()),
665            Err(StatusCode::BadDecodingError)
666        );
667        let nested = [0x40; 100];
668        assert_eq!(
669            DiagnosticInfo::decode(&mut &nested[..], &c.context()),
670            Err(StatusCode::BadEncodingLimitsExceeded)
671        );
672    }
673}