1extern crate alloc;
3
4use crate::alloc::string::ToString;
5use core::{borrow::Borrow, f64};
6
7use xml_no_std::{
8 ParserConfig, attribute::Attribute, common::XmlVersion, name::OwnedName, namespace::Namespace,
9 reader::XmlEvent,
10};
11
12use crate::{Decode, error::*, types::*, xer::BOOLEAN_TRUE_TAG};
13
14use self::fields::Field;
15
16use super::{
17 BOOLEAN_FALSE_TAG, MINUS_INFINITY_TAG, MINUS_INFINITY_VALUE, NAN_TAG, NAN_VALUE,
18 PLUS_INFINITY_TAG, PLUS_INFINITY_VALUE,
19};
20
21const OPTIONAL_ITEM_NOT_PRESENT: &str = "§_NOT_PRESENT_§";
22
23macro_rules! error {
24 ($kind:ident, $($arg:tt)*) => {
25 DecodeError::from(XerDecodeErrorKind::$kind {
26 details: alloc::format!($($arg)*)
27 })
28 };
29 ($kind:ident) => {
30 DecodeError::from(XerDecodeErrorKind::$kind { })
31 };
32}
33
34macro_rules! tag {
35 ($event:ident, $this:ident, $tag:expr) => {
36 match $this.next_element() {
37 Some(XmlEvent::$event { name, .. }) => {
38 if name.local_name.as_str() == $tag {
39 Ok(())
40 } else {
41 Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
42 needed: $tag,
43 found: alloc::format!("{name:?}"),
44 }))
45 }
46 }
47 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
48 needed: $tag,
49 found: alloc::format!("{elem:?}"),
50 })),
51 None => Err(error!(EndOfXmlInput)),
52 }
53 };
54 ($event:ident, $this:ident) => {
55 match $this.next_element() {
56 Some(XmlEvent::$event { .. }) => Ok(()),
57 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
58 needed: "StartElement or EndElement",
59 found: alloc::format!("{elem:?}"),
60 })),
61 None => Err(error!(EndOfXmlInput)),
62 }
63 };
64}
65
66macro_rules! decode_string {
67 ($this:ident, $tryfrom:path, $tag:path, $needed:literal) => {{
68 tag!(StartElement, $this)?;
69 let value = match $this.next_element() {
70 Some(XmlEvent::Characters(value)) => $tryfrom(value).map_err(|e| {
71 DecodeError::string_conversion_failed(
72 $tag,
73 alloc::format!("Error transforming string: {e:?}"),
74 crate::Codec::Xer,
75 )
76 }),
77 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
78 needed: $needed,
79 found: alloc::format!("{elem:?}"),
80 })),
81 None => Err(error!(EndOfXmlInput)),
82 };
83 tag!(EndElement, $this)?;
84 value
85 }};
86}
87
88macro_rules! decode_time {
89 ($this:ident, $decode_fn:path) => {{
90 tag!(StartElement, $this)?;
91 let value = match $this.next_element() {
92 Some(XmlEvent::Characters(value)) => $decode_fn(value),
93 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
94 needed: "Time value",
95 found: alloc::format!("{elem:?}"),
96 })),
97 None => Err(error!(EndOfXmlInput)),
98 };
99 tag!(EndElement, $this)?;
100 value
101 }};
102}
103
104macro_rules! value_or_empty {
105 ($this:ident, $parser:ident, $expected:expr) => {{
106 let value = match $this.peek() {
107 Some(XmlEvent::Characters(s)) => $parser(s),
108 Some(XmlEvent::EndElement { .. }) => return Ok(<_>::default()),
109 Some(elem) => {
110 return Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
111 needed: $expected,
112 found: alloc::format!("{elem:?}"),
113 }));
114 }
115 _ => return Err(DecodeError::from(XerDecodeErrorKind::EndOfXmlInput {})),
116 };
117 let _ = $this.next_element();
118 value
119 }};
120}
121
122#[derive(Debug)]
123struct XerElement {
124 events: alloc::collections::VecDeque<XmlEvent>,
125}
126
127impl XerElement {
128 pub fn next(&mut self) -> Option<XmlEvent> {
129 self.events.pop_front()
130 }
131
132 pub fn peek(&self) -> Option<&XmlEvent> {
133 self.events.front()
134 }
135
136 #[cfg(test)]
137 pub fn len(&self) -> usize {
138 self.events.len()
139 }
140}
141
142impl<I: IntoIterator<Item = XmlEvent>> From<I> for XerElement {
143 fn from(value: I) -> Self {
144 XerElement {
145 events: value.into_iter().collect(),
146 }
147 }
148}
149
150pub struct Decoder {
152 stack: alloc::vec::Vec<XerElement>,
153 in_list: bool,
154}
155
156impl Decoder {
157 pub fn new(input: &[u8]) -> Result<Self, <Decoder as crate::de::Decoder>::Error> {
159 let mut reader = ParserConfig::default().create_reader(input.iter());
160 let next = reader.next().map_err(|e| error!(XmlParser, "{e:?}"))?;
161 check_prolog(&next)?;
162 let mut elements = alloc::collections::VecDeque::new();
163 'read_xml: loop {
164 let next = reader.next().map_err(|e| error!(XmlParser, "{e:?}"))?;
165 if next == XmlEvent::EndDocument {
166 break 'read_xml;
167 }
168 elements.push_back(next);
169 }
170 elements.try_into()
171 }
172
173 fn next_element(&mut self) -> Option<XmlEvent> {
174 if let Some(mut elem) = self.stack.pop() {
175 let event = elem.next();
176 if !elem.events.is_empty() {
177 self.stack.push(elem);
178 }
179 event
180 } else {
181 None
182 }
183 }
184
185 #[cfg(test)]
186 fn len(&self) -> usize {
187 self.stack.iter().fold(0, |acc, evt| acc + evt.len())
188 }
189
190 fn peek(&self) -> Option<&XmlEvent> {
191 self.stack.last().and_then(XerElement::peek)
192 }
193
194 fn sort_by_field_tag_order(
195 &mut self,
196 field_indices: &[(usize, Field)],
197 ) -> Result<(), DecodeError> {
198 let field_names = field_indices.iter().map(|(_, f)| f.name).collect();
199 self.sort_by_field_name_order(field_names)
200 }
201
202 fn sort_by_field_name_order(
203 &mut self,
204 field_names: alloc::vec::Vec<&str>,
205 ) -> Result<(), DecodeError> {
206 let stack = core::mem::take(&mut self.stack);
207 let mut reordered = stack.into_iter().try_fold(
208 alloc::collections::BTreeMap::<usize, XerElement>::new(),
209 |mut acc, elem| {
210 let index = match elem.peek() {
211 Some(XmlEvent::StartElement { name, .. }) => field_names
212 .iter()
213 .enumerate()
214 .find_map(|(i, f)| (*f == name.local_name.as_str()).then_some(i))
215 .ok_or_else(|| {
216 XerDecodeErrorKind::XmlTag {
217 needed: name.local_name.clone(),
218 found: "nothing".into(),
219 }
220 .into()
221 }),
222 e => Err(error!(XmlParser, "Expected opening tag, found {e:?}")),
223 };
224 index.map(|i| {
225 acc.insert(i, elem);
226 acc
227 })
228 },
229 )?;
230 for i in (0..field_names.len()).rev() {
231 self.stack.push(reordered.remove(&i).unwrap_or(XerElement {
232 events: alloc::vec![XmlEvent::Characters(OPTIONAL_ITEM_NOT_PRESENT.into())].into(),
233 }));
234 }
235 Ok(())
236 }
237
238 fn into_list_decoder(mut self) -> Self {
239 self.in_list = true;
240 self
241 }
242
243 fn from_stack_elems<E: IntoIterator<Item = XmlEvent>, I: IntoIterator<Item = E>>(
244 elems: I,
245 ) -> Self {
246 Decoder {
247 stack: elems.into_iter().map(|i| XerElement::from(i)).collect(),
248 in_list: false,
249 }
250 }
251}
252
253impl TryFrom<alloc::collections::VecDeque<XmlEvent>> for Decoder {
254 type Error = DecodeError;
255 fn try_from(value: alloc::collections::VecDeque<XmlEvent>) -> Result<Self, Self::Error> {
256 let (mut stack, mut events, mut tag) =
257 (alloc::vec![], alloc::collections::VecDeque::new(), None);
258 let mut level_of_nested_items = 0;
259 'xml_elements: for evt in value {
260 match (&tag, evt) {
261 (_, XmlEvent::Whitespace(_)) => continue 'xml_elements,
262 (
263 None,
264 XmlEvent::StartElement {
265 name,
266 attributes,
267 namespace,
268 },
269 ) => {
270 tag = Some(name.clone());
271 events.push_back(XmlEvent::StartElement {
272 name,
273 attributes,
274 namespace,
275 });
276 }
277 (None, _) => {
278 continue 'xml_elements;
279 }
280 (
281 Some(t),
282 XmlEvent::StartElement {
283 name,
284 attributes,
285 namespace,
286 },
287 ) => {
288 if &name == t {
289 level_of_nested_items += 1;
290 }
291 events.push_back(XmlEvent::StartElement {
292 name,
293 attributes,
294 namespace,
295 });
296 }
297 (Some(t), XmlEvent::EndElement { name }) => {
298 if &name == t && level_of_nested_items != 0 {
299 level_of_nested_items -= 1;
300 events.push_back(XmlEvent::EndElement { name });
301 } else if &name == t {
302 events.push_back(XmlEvent::EndElement { name });
303 let collected_events: alloc::collections::VecDeque<XmlEvent> =
304 core::mem::take(&mut events);
305 stack.push(XerElement {
306 events: collected_events,
307 });
308 tag = None;
309 } else {
310 events.push_back(XmlEvent::EndElement { name });
311 }
312 }
313 (Some(_), XmlEvent::EndDocument) => return Err(error!(EndOfXmlInput)),
314 (Some(_), event) => events.push_back(event),
315 }
316 }
317 Ok(Self {
318 stack,
319 in_list: false,
320 })
321 }
322}
323
324fn check_prolog(prolog: &XmlEvent) -> Result<(), DecodeError> {
325 if let XmlEvent::StartDocument {
326 version, encoding, ..
327 } = prolog
328 {
329 if version != &XmlVersion::Version10 || encoding != &alloc::string::String::from("UTF-8") {
330 Err(error!(
331 SpecViolation,
332 r#"§8.2 The XML prolog shall either be empty; or shall consist of [...] <?xml
333 version="1.0"
334 encoding="UTF-8"?>"#
335 ))
336 } else {
337 Ok(())
338 }
339 } else {
340 Err(error!(XmlParser, "Expected XML prolog, found {:?}", prolog))
341 }
342}
343
344impl crate::Decoder for Decoder {
345 type Ok = ();
346
347 type AnyDecoder<const R: usize, const E: usize> = Decoder;
348 type Error = DecodeError;
349
350 fn codec(&self) -> crate::Codec {
351 crate::Codec::Xer
352 }
353
354 fn decode_any(&mut self, _tag: Tag) -> Result<crate::types::Any, Self::Error> {
355 tag!(StartElement, self)?;
356 let mut events = self
357 .stack
358 .pop()
359 .ok_or_else(|| error!(EndOfXmlInput))?
360 .events;
361 events.pop_back();
362 let mut xml_writer = xml_no_std::EmitterConfig::new()
363 .write_document_declaration(false)
364 .create_writer();
365
366 for reader_event in events {
367 match reader_event {
368 XmlEvent::EndDocument => return Err(XerDecodeErrorKind::EndOfXmlInput {}.into()),
369 XmlEvent::StartElement {
370 name,
371 attributes,
372 namespace,
373 } => {
374 let event = xml_no_std::writer::XmlEvent::StartElement {
375 name: name.borrow(),
376 namespace: namespace.borrow(),
377 attributes: attributes
378 .iter()
379 .map(|attr| Attribute::new(attr.name.borrow(), &attr.value))
380 .collect(),
381 };
382 xml_writer
383 .write(event)
384 .map_err(|e| XerDecodeErrorKind::InvalidOpenType { inner_err: e })?;
385 }
386 XmlEvent::Characters(text) => {
387 let text = text.borrow();
388 let event = xml_no_std::writer::XmlEvent::Characters(text);
389 xml_writer
390 .write(event)
391 .map_err(|e| XerDecodeErrorKind::InvalidOpenType { inner_err: e })?;
392 }
393 XmlEvent::Comment(text) => {
394 let text = text.borrow();
395 let event = xml_no_std::writer::XmlEvent::Comment(text);
396 xml_writer
397 .write(event)
398 .map_err(|e| XerDecodeErrorKind::InvalidOpenType { inner_err: e })?;
399 }
400 other => {
401 if let Some(writer_event) = other.as_writer_event() {
402 xml_writer
403 .write(writer_event)
404 .map_err(|e| XerDecodeErrorKind::InvalidOpenType { inner_err: e })?;
405 }
406 }
407 }
408 }
409 Ok(Any::new(xml_writer.into_inner().into_bytes()))
410 }
411
412 fn decode_bit_string(
413 &mut self,
414 __tag: Tag,
415 __constraints: Constraints,
416 ) -> Result<crate::types::BitString, Self::Error> {
417 tag!(StartElement, self)?;
418 let value = value_or_empty!(self, parse_bitstring_value, "`1` or `0`");
419 tag!(EndElement, self)?;
420 value
421 }
422
423 fn decode_bool(&mut self, __tag: Tag) -> Result<bool, Self::Error> {
424 if !self.in_list {
425 tag!(StartElement, self)?;
426 }
427 let value = match self.next_element() {
428 Some(XmlEvent::StartElement { name, .. }) => {
429 if name.local_name.as_str() == BOOLEAN_TRUE_TAG {
430 tag!(EndElement, self, BOOLEAN_TRUE_TAG).map(|_| true)
431 } else if name.local_name.as_str() == BOOLEAN_FALSE_TAG {
432 tag!(EndElement, self, BOOLEAN_FALSE_TAG).map(|_| false)
433 } else if self.in_list {
434 let boolean = match self.next_element() {
435 Some(XmlEvent::Characters(c)) if c == "0" => false,
436 Some(XmlEvent::Characters(c)) if c == "1" => true,
437 Some(XmlEvent::Characters(c)) if c == "false" => false,
438 Some(XmlEvent::Characters(c)) if c == "true" => true,
439 _ => {
440 return Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
441 needed: "`<true/>` or `<false/>`",
442 found: alloc::format!("{name:?}"),
443 }));
444 }
445 };
446 tag!(EndElement, self)?;
447 Ok(boolean)
448 } else {
449 Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
450 needed: "`<true/>` or `<false/>`",
451 found: alloc::format!("{name:?}"),
452 }))
453 }
454 }
455 Some(XmlEvent::Characters(c)) if c == "0" => Ok(false),
456 Some(XmlEvent::Characters(c)) if c == "1" => Ok(true),
457 Some(XmlEvent::Characters(c)) if c == "false" => Ok(false),
458 Some(XmlEvent::Characters(c)) if c == "true" => Ok(true),
459 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
460 needed: bool::IDENTIFIER.0.unwrap(),
461 found: alloc::format!("{elem:?}"),
462 })),
463 None => Err(error!(EndOfXmlInput)),
464 };
465 if !self.in_list {
466 tag!(EndElement, self)?;
467 }
468 value
469 }
470
471 fn decode_enumerated<E: Enumerated>(&mut self, __tag: Tag) -> Result<E, Self::Error> {
472 if !self.in_list {
473 tag!(StartElement, self)?;
474 }
475 let value = match self.next_element() {
476 Some(XmlEvent::StartElement {
477 name: OwnedName { local_name, .. },
478 ..
479 }) => {
480 if let Some(e) = E::from_identifier(&local_name) {
481 tag!(EndElement, self).map(|_| e)
482 } else {
483 Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
484 needed: "enumerated value",
485 found: local_name,
486 }))
487 }
488 }
489 Some(XmlEvent::Characters(c)) => E::from_identifier(&c).ok_or(DecodeError::from(
490 XerDecodeErrorKind::XmlTypeMismatch {
491 needed: "enumerated value",
492 found: c,
493 },
494 )),
495 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
496 needed: "enumerated value",
497 found: alloc::format!("{elem:?}"),
498 })),
499 None => Err(error!(EndOfXmlInput)),
500 };
501 if !self.in_list {
502 tag!(EndElement, self)?;
503 }
504 value
505 }
506
507 fn decode_integer<I: crate::types::IntegerType>(
508 &mut self,
509 _t: Tag,
510 _c: Constraints,
511 ) -> Result<I, Self::Error> {
512 tag!(StartElement, self)?;
513 let value = match self.next_element() {
514 Some(XmlEvent::Characters(value)) => {
515 if let Ok(int) = value.parse::<i128>() {
516 int.try_into()
517 .map_err(|_| DecodeError::integer_overflow(I::WIDTH, crate::Codec::Jer))
518 } else {
519 Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
520 needed: "integer value",
521 found: value,
522 }))
523 }
524 }
525 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
526 needed: "integer value",
527 found: alloc::format!("{elem:?}"),
528 })),
529 None => Err(error!(EndOfXmlInput)),
530 };
531 tag!(EndElement, self)?;
532 value
533 }
534
535 fn decode_null(&mut self, _tag: Tag) -> Result<(), Self::Error> {
536 tag!(StartElement, self)?;
537 tag!(EndElement, self)?;
538 Ok(())
539 }
540
541 fn decode_object_identifier(
542 &mut self,
543 _tag: Tag,
544 ) -> Result<crate::types::ObjectIdentifier, Self::Error> {
545 tag!(StartElement, self)?;
546 let value = match self.next_element() {
547 Some(XmlEvent::Characters(value)) => parse_object_identifier(&value),
548 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
549 needed: "'.'-separated numeric object identifier arcs",
550 found: alloc::format!("{elem:?}"),
551 })),
552 None => Err(error!(EndOfXmlInput)),
553 };
554 tag!(EndElement, self)?;
555 value
556 }
557
558 fn decode_sequence<const RC: usize, const EC: usize, D, DF, F>(
559 &mut self,
560 _: Tag,
561 _: Option<DF>,
562 decode_fn: F,
563 ) -> Result<D, Self::Error>
564 where
565 D: Constructed<RC, EC>,
566 F: FnOnce(&mut Self) -> Result<D, Self::Error>,
567 {
568 tag!(StartElement, self)?;
569 let mut field_names = D::FIELDS
570 .iter()
571 .map(|f| f.name)
572 .collect::<alloc::vec::Vec<&str>>();
573 if let Some(extended_fields) = D::EXTENDED_FIELDS {
574 field_names.extend(extended_fields.iter().map(|f| f.name));
575 }
576 let events = self
577 .stack
578 .pop()
579 .ok_or_else(|| error!(EndOfXmlInput))?
580 .events;
581 let mut sequence_decoder = Decoder::try_from(events)?;
582 sequence_decoder.sort_by_field_name_order(field_names)?;
583 (decode_fn)(&mut sequence_decoder)
584 }
585
586 fn decode_sequence_of<D: Decode>(
587 &mut self,
588 _tag: Tag,
589 _constraints: Constraints,
590 ) -> Result<alloc::vec::Vec<D>, Self::Error> {
591 decode_sequence_or_set_items(self)
592 }
593
594 fn decode_set_of<D: crate::Decode + Eq + core::hash::Hash>(
595 &mut self,
596 _t: Tag,
597 _c: Constraints,
598 ) -> Result<SetOf<D>, Self::Error> {
599 let items = decode_sequence_or_set_items::<D>(self)?;
600 Ok(SetOf::from_vec(items))
601 }
602
603 fn decode_octet_string<'b, T: From<alloc::vec::Vec<u8>> + From<&'b [u8]>>(
604 &'b mut self,
605 _: Tag,
606 _c: Constraints,
607 ) -> Result<T, Self::Error> {
608 tag!(StartElement, self)?;
609 let value = match self.peek() {
610 Some(XmlEvent::Characters(s)) => parse_octetstring_value(s),
611 Some(XmlEvent::EndElement { .. }) => return Ok(<T as From<&'b [u8]>>::from(&[])),
612 Some(elem) => {
613 return Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
614 needed: "hexadecimal characters",
615 found: alloc::format!("{elem:?}"),
616 }));
617 }
618 _ => return Err(DecodeError::from(XerDecodeErrorKind::EndOfXmlInput {})),
619 };
620 let _ = self.next_element();
621 tag!(EndElement, self)?;
622 value.map(T::from)
623 }
624
625 fn decode_utf8_string(
626 &mut self,
627 _tag: Tag,
628 _constraints: Constraints,
629 ) -> Result<crate::types::Utf8String, Self::Error> {
630 tag!(StartElement, self)?;
631 let value = match self.next_element() {
632 Some(XmlEvent::Characters(value)) => Ok(value),
633 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
634 needed: "UTF8 string value",
635 found: alloc::format!("{elem:?}"),
636 })),
637 None => Err(error!(EndOfXmlInput)),
638 };
639 tag!(EndElement, self)?;
640 value
641 }
642
643 fn decode_visible_string(
644 &mut self,
645 _tag: Tag,
646 _constraints: Constraints,
647 ) -> Result<crate::types::VisibleString, Self::Error> {
648 decode_string!(
649 self,
650 crate::types::VisibleString::try_from,
651 Tag::VISIBLE_STRING,
652 "VisibleString value"
653 )
654 }
655
656 fn decode_general_string(
657 &mut self,
658 _tag: Tag,
659 _constraints: Constraints,
660 ) -> Result<crate::types::GeneralString, Self::Error> {
661 decode_string!(
662 self,
663 crate::types::GeneralString::try_from,
664 Tag::GENERAL_STRING,
665 "GeneralString value"
666 )
667 }
668
669 fn decode_ia5_string(
670 &mut self,
671 _tag: Tag,
672 _constraints: Constraints,
673 ) -> Result<crate::types::Ia5String, Self::Error> {
674 decode_string!(
675 self,
676 crate::types::Ia5String::try_from,
677 Tag::IA5_STRING,
678 "IA5String value"
679 )
680 }
681
682 fn decode_graphic_string(
683 &mut self,
684 _tag: Tag,
685 _constraints: Constraints,
686 ) -> Result<crate::types::GraphicString, Self::Error> {
687 decode_string!(
688 self,
689 crate::types::GraphicString::try_from,
690 Tag::GRAPHIC_STRING,
691 "GraphicString value"
692 )
693 }
694
695 fn decode_printable_string(
696 &mut self,
697 _tag: Tag,
698 _constraints: Constraints,
699 ) -> Result<crate::types::PrintableString, Self::Error> {
700 decode_string!(
701 self,
702 crate::types::PrintableString::try_from,
703 Tag::PRINTABLE_STRING,
704 "PrintableString value"
705 )
706 }
707
708 fn decode_numeric_string(
709 &mut self,
710 _tag: Tag,
711 _constraints: Constraints,
712 ) -> Result<crate::types::NumericString, Self::Error> {
713 decode_string!(
714 self,
715 crate::types::NumericString::try_from,
716 Tag::NUMERIC_STRING,
717 "NumericString value"
718 )
719 }
720
721 fn decode_teletex_string(
722 &mut self,
723 _tag: Tag,
724 _constraints: Constraints,
725 ) -> Result<crate::types::TeletexString, Self::Error> {
726 todo!()
727 }
728
729 fn decode_bmp_string(
730 &mut self,
731 _tag: Tag,
732 _constraints: Constraints,
733 ) -> Result<crate::types::BmpString, Self::Error> {
734 decode_string!(
735 self,
736 crate::types::BmpString::try_from,
737 Tag::BMP_STRING,
738 "BMP String value"
739 )
740 }
741
742 fn decode_explicit_prefix<D: Decode>(&mut self, _tag: Tag) -> Result<D, Self::Error> {
743 D::decode(self)
744 }
745
746 fn decode_utc_time(&mut self, _tag: Tag) -> Result<crate::types::UtcTime, Self::Error> {
747 decode_time!(self, crate::ber::de::Decoder::parse_any_utc_time_string)
748 }
749
750 fn decode_generalized_time(
751 &mut self,
752 _tag: Tag,
753 ) -> Result<crate::types::GeneralizedTime, Self::Error> {
754 decode_time!(
755 self,
756 crate::ber::de::Decoder::parse_any_generalized_time_string
757 )
758 }
759
760 fn decode_set<const RC: usize, const EC: usize, FIELDS, SET, D, F>(
761 &mut self,
762 _t: Tag,
763 decode_fn: D,
764 field_fn: F,
765 ) -> Result<SET, Self::Error>
766 where
767 SET: crate::Decode + Constructed<RC, EC>,
768 FIELDS: crate::Decode,
769 D: Fn(&mut Self::AnyDecoder<RC, EC>, usize, Tag) -> Result<FIELDS, Self::Error>,
770 F: FnOnce(alloc::vec::Vec<FIELDS>) -> Result<SET, Self::Error>,
771 {
772 tag!(StartElement, self)?;
773 let events = self
774 .stack
775 .pop()
776 .ok_or_else(|| error!(EndOfXmlInput))?
777 .events;
778 let mut field_indices = SET::FIELDS
779 .iter()
780 .enumerate()
781 .collect::<alloc::vec::Vec<_>>();
782 let mut fields = alloc::vec![];
783 field_indices
784 .sort_by(|(_, a), (_, b)| a.tag_tree.smallest_tag().cmp(&b.tag_tree.smallest_tag()));
785 let mut sequence_decoder = Decoder::try_from(events)?;
786 sequence_decoder.sort_by_field_tag_order(&field_indices)?;
787 for (index, field) in field_indices {
788 fields.push((decode_fn)(&mut sequence_decoder, index, field.tag)?);
789 }
790
791 for (index, field) in SET::EXTENDED_FIELDS
792 .iter()
793 .flat_map(|fields| fields.iter())
794 .enumerate()
795 {
796 fields.push((decode_fn)(
797 &mut sequence_decoder,
798 index + SET::FIELDS.len(),
799 field.tag,
800 )?);
801 }
802
803 (field_fn)(fields)
804 }
805
806 fn decode_choice<D>(&mut self, _constraints: Constraints) -> Result<D, Self::Error>
807 where
808 D: crate::types::DecodeChoice,
809 {
810 if !self.in_list {
811 tag!(StartElement, self)?;
812 }
813 match self.peek() {
814 Some(XmlEvent::StartElement { name, .. }) => {
815 let tag = D::IDENTIFIERS
816 .iter()
817 .enumerate()
818 .find(|(_, id)| id.eq_ignore_ascii_case(&name.local_name))
819 .and_then(|(i, _)| {
820 variants::Variants::from_slice(
821 &[D::VARIANTS, D::EXTENDED_VARIANTS.unwrap_or(&[])].concat(),
822 )
823 .get(i)
824 .cloned()
825 })
826 .unwrap_or(Tag::EOC);
827 let events = self
828 .stack
829 .pop()
830 .ok_or_else(|| error!(EndOfXmlInput))?
831 .events;
832 let mut variant_decoder = Decoder::try_from(events)?;
833 D::from_tag(&mut variant_decoder, tag)
834 }
835 elem => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
836 needed: "Start element of choice option",
837 found: alloc::format!("{elem:?}"),
838 })),
839 }
840 }
841
842 fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error> {
843 match self.peek() {
844 Some(XmlEvent::Characters(c)) if c == OPTIONAL_ITEM_NOT_PRESENT => {
845 let _ = self.next_element();
846 return Ok(None);
847 }
848 _ => (),
849 }
850 D::decode(self).map(Some)
851 }
852
853 fn decode_optional_with_tag<D: Decode>(&mut self, _tag: Tag) -> Result<Option<D>, Self::Error> {
854 self.decode_optional()
855 }
856
857 fn decode_optional_with_constraints<D: Decode>(
858 &mut self,
859 _constraints: Constraints,
860 ) -> Result<Option<D>, Self::Error> {
861 self.decode_optional()
862 }
863
864 fn decode_optional_with_tag_and_constraints<D: Decode>(
865 &mut self,
866 _tag: Tag,
867 _constraints: Constraints,
868 ) -> Result<Option<D>, Self::Error> {
869 self.decode_optional()
870 }
871
872 fn decode_extension_addition_with_constraints<D>(
873 &mut self,
874 _constraints: Constraints,
875 ) -> Result<Option<D>, Self::Error>
876 where
877 D: Decode,
878 {
879 self.decode_optional()
880 }
881
882 fn decode_extension_addition_group<
883 const RC: usize,
884 const EC: usize,
885 D: crate::Decode + Constructed<RC, EC>,
886 >(
887 &mut self,
888 ) -> Result<Option<D>, Self::Error> {
889 self.decode_optional()
890 }
891
892 fn decode_real<R: crate::types::RealType>(
893 &mut self,
894 _tag: Tag,
895 _constraints: Constraints,
896 ) -> Result<R, Self::Error> {
897 tag!(StartElement, self)?;
898 let value = match self.next_element() {
899 Some(XmlEvent::Characters(value)) => match value.as_str().parse::<f64>() {
900 Ok(real) => R::try_from_float(real).ok_or_else(|| {
901 DecodeError::integer_overflow(R::BYTE_WIDTH as u32, crate::Codec::Xer)
902 }),
903 Err(_) if value.as_str() == PLUS_INFINITY_VALUE => Ok(R::INFINITY),
904 Err(_) if value.as_str() == MINUS_INFINITY_VALUE => Ok(R::NEG_INFINITY),
905 Err(_) if value.as_str() == NAN_VALUE => Ok(R::NAN),
906 _ => {
907 return Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
908 needed: "integer value",
909 found: value,
910 }));
911 }
912 },
913 Some(XmlEvent::StartElement { name, .. }) => {
914 tag!(EndElement, self)?;
915 match name.local_name.as_str() {
916 PLUS_INFINITY_TAG => Ok(R::INFINITY),
917 MINUS_INFINITY_TAG => Ok(R::NEG_INFINITY),
918 NAN_TAG => Ok(R::NAN),
919 _ => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
920 needed: "PLUS-INFINITY, MINUS-INFINITY or NOT-A-NUMBER",
921 found: name.local_name,
922 })),
923 }
924 }
925 Some(elem) => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
926 needed: "integer value",
927 found: alloc::format!("{elem:?}"),
928 })),
929 None => Err(error!(EndOfXmlInput)),
930 };
931 tag!(EndElement, self)?;
932 value
933 }
934
935 fn decode_optional_with_explicit_prefix<D: Decode>(
936 &mut self,
937 _tag: Tag,
938 ) -> Result<Option<D>, Self::Error> {
939 self.decode_optional()
940 }
941
942 fn decode_date(&mut self, _tag: Tag) -> Result<Date, Self::Error> {
943 decode_time!(
944 self,
945 crate::ber::de::Decoder::parse_any_generalized_time_string
946 )
947 .map(|dt| dt.date_naive())
948 }
949
950 fn decode_extension_addition_with_explicit_tag_and_constraints<D>(
951 &mut self,
952 _tag: Tag,
953 _constraints: Constraints,
954 ) -> Result<Option<D>, Self::Error>
955 where
956 D: Decode,
957 {
958 self.decode_extension_addition()
959 }
960
961 fn decode_extension_addition_with_tag_and_constraints<D>(
962 &mut self,
963 _tag: Tag,
964 _constraints: Constraints,
965 ) -> Result<Option<D>, Self::Error>
966 where
967 D: Decode,
968 {
969 self.decode_extension_addition()
970 }
971}
972
973fn parse_bitstring_value(val: &str) -> Result<BitString, DecodeError> {
974 if !val
976 .chars()
977 .all(|c| c == '1' || c == '0' || c.is_whitespace())
978 {
979 return Err(error!(
980 SpecViolation,
981 r#"§12.11 An "xmlbstring" shall consist of an arbitrary number (possibly zero) of zeros, ones or white-space"#
982 ));
983 }
984 Ok(BitString::from_iter(val.chars().filter_map(|c| {
985 (c == '1').then_some(true).or((c == '0').then_some(false))
986 })))
987}
988
989fn parse_octetstring_value(val: &str) -> Result<alloc::vec::Vec<u8>, DecodeError> {
990 (0..val.len())
991 .step_by(2)
992 .map(|i| u8::from_str_radix(&val[i..i + 2], 16))
993 .collect::<Result<alloc::vec::Vec<_>, _>>()
994 .map_err(|e| XerDecodeErrorKind::InvalidXerOctetstring { parse_int_err: e }.into())
995}
996
997fn parse_object_identifier(val: &str) -> Result<ObjectIdentifier, DecodeError> {
998 let arcs = val
999 .split('.')
1000 .try_fold(alloc::vec::Vec::<u32>::new(), |mut acc, curr| {
1001 curr.parse()
1002 .map(|i| {
1003 acc.push(i);
1004 acc
1005 })
1006 .map_err(|_| {
1007 DecodeError::from(XerDecodeErrorKind::InvalidInput {
1008 details: "Invalid Object Identifier value.",
1009 })
1010 })
1011 })?;
1012 ObjectIdentifier::new(arcs).ok_or_else(|| {
1013 XerDecodeErrorKind::InvalidInput {
1014 details: "Invalid Object Identifier value.",
1015 }
1016 .into()
1017 })
1018}
1019
1020fn decode_sequence_or_set_items<D: Decode>(
1021 decoder: &mut Decoder,
1022) -> Result<alloc::vec::Vec<D>, DecodeError> {
1023 let identifier = match decoder.next_element() {
1024 Some(XmlEvent::StartElement { name, .. }) => Ok(name),
1025 elem => Err(DecodeError::from(XerDecodeErrorKind::XmlTypeMismatch {
1026 needed: "StartElement of SEQUENCE OF",
1027 found: alloc::format!("{elem:?}"),
1028 })),
1029 }?;
1030
1031 let mut inner_decoder: Decoder = if let Some(XmlEvent::Characters(c)) = decoder.peek() {
1032 let mut elems = alloc::vec![alloc::vec![XmlEvent::EndElement {
1033 name: identifier.clone()
1034 }]];
1035 elems.extend(c.split_ascii_whitespace().map(|item| {
1036 alloc::vec![
1037 XmlEvent::StartElement {
1038 name: OwnedName {
1039 local_name: D::IDENTIFIER.0.unwrap_or("dummy").to_string(),
1040 namespace: None,
1041 prefix: None,
1042 },
1043 attributes: alloc::vec::Vec::new(),
1044 namespace: Namespace::empty(),
1045 },
1046 XmlEvent::Characters(item.to_string()),
1047 XmlEvent::EndElement {
1048 name: OwnedName {
1049 local_name: D::IDENTIFIER.0.unwrap_or("dummy").to_string(),
1050 namespace: None,
1051 prefix: None,
1052 },
1053 },
1054 ]
1055 }));
1056 let _ = decoder.stack.pop();
1057 Decoder::from_stack_elems(elems)
1058 } else {
1059 decoder
1060 .stack
1061 .pop()
1062 .ok_or_else(|| error!(EndOfXmlInput))?
1063 .events
1064 .try_into()?
1065 }
1066 .into_list_decoder();
1067
1068 let mut items = alloc::vec::Vec::new();
1069 let mut level_of_nesting = 0;
1070 loop {
1071 match inner_decoder.peek() {
1072 Some(XmlEvent::StartElement { name, .. }) if name == &identifier => {
1073 level_of_nesting += 1;
1074 items.push(D::decode(&mut inner_decoder)?)
1075 }
1076 Some(XmlEvent::EndElement { name }) if name == &identifier && level_of_nesting == 0 => {
1077 break;
1078 }
1079 Some(XmlEvent::EndElement { name }) if name == &identifier => {
1080 level_of_nesting -= 1;
1081 inner_decoder.next_element();
1082 }
1083 None => break,
1084 _ => items.push(D::decode(&mut inner_decoder)?),
1085 }
1086 }
1087 items.reverse();
1088
1089 Ok(items)
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094 use super::Decoder;
1095 use crate::{AsnType, Decode, Decoder as _, types::*};
1096 use bitvec::order::Msb0;
1097
1098 macro_rules! decode_test_1 {
1099 ($suite:ident, $method:ident, $xml:literal, $expected:expr) => {
1100 #[test]
1101 fn $suite() {
1102 let mut decoder = Decoder::new($xml.as_bytes()).unwrap();
1103 assert_eq!(
1104 crate::Decoder::$method(&mut decoder, Tag::CHOICE).unwrap(),
1105 $expected
1106 )
1107 }
1108 };
1109 }
1110
1111 macro_rules! decode_test_2 {
1112 ($suite:ident, $method:path, $xml:literal, $expected:expr) => {
1113 #[test]
1114 fn $suite() {
1115 let mut decoder = Decoder::new($xml.as_bytes()).unwrap();
1116 assert_eq!(
1117 $method(&mut decoder, Tag::CHOICE, Constraints::NONE).unwrap(),
1118 $expected
1119 )
1120 }
1121 };
1122 }
1123
1124 #[test]
1125 fn creates_decoder() {
1126 Decoder::new(
1127 r#"<?xml version="1.0" encoding="UTF-8"?>
1128 <Actual>
1129 <errorCode>
1130 <local>1</local>
1131 </errorCode>
1132 <parameter>
1133 <BOOLEAN><false/></BOOLEAN>
1134 </parameter>
1135 </Actual>"#
1136 .as_bytes(),
1137 )
1138 .unwrap();
1139 }
1140
1141 decode_test_1!(
1142 boolean_true,
1143 decode_bool,
1144 "<BOOLEAN><true/></BOOLEAN>",
1145 true
1146 );
1147 decode_test_1!(
1148 boolean_false,
1149 decode_bool,
1150 "<BOOLEAN><false/></BOOLEAN>",
1151 false
1152 );
1153 decode_test_2!(
1154 bit_string,
1155 crate::Decoder::decode_bit_string,
1156 "<BIT_STRING>1010</BIT_STRING>",
1157 bitvec::bitvec![u8, Msb0; 1, 0, 1, 0]
1158 );
1159 decode_test_2!(
1160 bit_string_ws,
1161 crate::Decoder::decode_bit_string,
1162 "<BIT_STRING> 1 0 1 0 </BIT_STRING>",
1163 bitvec::bitvec![u8, Msb0; 1, 0, 1, 0]
1164 );
1165 decode_test_2!(
1166 bit_string_empty,
1167 crate::Decoder::decode_bit_string,
1168 "<BIT_STRING/>",
1169 bitvec::bitvec![u8, Msb0;]
1170 );
1171
1172 #[derive(AsnType, Decode, Debug, PartialEq)]
1173 #[rasn(automatic_tags)]
1174 #[rasn(crate_root = "crate")]
1175 struct TestTypeA {
1176 wine: bool,
1177 grappa: BitString,
1178 }
1179
1180 #[derive(AsnType, Decode, Debug, PartialEq)]
1181 #[rasn(automatic_tags)]
1182 #[rasn(crate_root = "crate")]
1183 struct TestTypeParent {
1184 sinmin: bool,
1185 nested: TestTypeA,
1186 }
1187
1188 #[test]
1189 fn sequence() {
1190 let mut decoder = Decoder::new(
1191 "<TestTypeA><grappa>1010</grappa><wine><false/></wine></TestTypeA>".as_bytes(),
1192 )
1193 .unwrap();
1194 assert_eq!(
1195 TestTypeA::decode(&mut decoder).unwrap(),
1196 TestTypeA {
1197 wine: false,
1198 grappa: bitvec::bitvec![u8, Msb0; 1, 0, 1, 0]
1199 }
1200 )
1201 }
1202
1203 #[test]
1204 fn sequence_nested() {
1205 let mut decoder = Decoder::new(
1206 "<TestTypeParent><nested><grappa>1 11 1 </grappa><wine><false/></wine></nested><sinmin><true/></sinmin></TestTypeParent>".as_bytes(),
1207 )
1208 .unwrap();
1209 assert_eq!(
1210 TestTypeParent::decode(&mut decoder).unwrap(),
1211 TestTypeParent {
1212 nested: TestTypeA {
1213 wine: false,
1214 grappa: bitvec::bitvec![u8, Msb0; 1, 1, 1, 1]
1215 },
1216 sinmin: true
1217 }
1218 )
1219 }
1220
1221 #[derive(AsnType, Clone, Debug, Decode, PartialEq)]
1222 #[rasn(crate_root = "crate", automatic_tags, set)]
1223 struct TestSetA {
1224 wine: bool,
1225 grappa: BitString,
1226 }
1227
1228 #[test]
1229 fn set() {
1230 let mut decoder = Decoder::new(
1231 "<TestTypeA><grappa>1010</grappa><wine><false/></wine></TestTypeA>".as_bytes(),
1232 )
1233 .unwrap();
1234 assert_eq!(
1235 TestSetA::decode(&mut decoder).unwrap(),
1236 TestSetA {
1237 wine: false,
1238 grappa: bitvec::bitvec![u8, Msb0; 1, 0, 1, 0]
1239 }
1240 )
1241 }
1242
1243 decode_test_2!(
1244 positive_int,
1245 crate::Decoder::decode_integer::<i128>,
1246 "<INTEGER>1283749501626451264</INTEGER>",
1247 1283749501626451264_i128
1248 );
1249
1250 decode_test_2!(
1251 negative_int,
1252 crate::Decoder::decode_integer::<i32>,
1253 "<INTEGER>-124142</INTEGER>",
1254 -124142_i32
1255 );
1256
1257 #[derive(AsnType, Decode, Debug, PartialEq, Clone, Copy)]
1258 #[rasn(enumerated)]
1259 #[rasn(automatic_tags)]
1260 #[rasn(crate_root = "crate")]
1261 enum TestEnum {
1262 #[rasn(identifier = "option-A")]
1263 OptionA,
1264 #[rasn(identifier = "option-B")]
1265 OptionB,
1266 }
1267
1268 #[test]
1269 fn enumerated() {
1270 let mut decoder = Decoder::new("<TestEnum><option-B/></TestEnum>".as_bytes()).unwrap();
1271 assert_eq!(TestEnum::decode(&mut decoder).unwrap(), TestEnum::OptionB);
1272 assert_eq!(decoder.len(), 0);
1273 let mut decoder = Decoder::new("<TestEnum>option-B</TestEnum>".as_bytes()).unwrap();
1274 assert_eq!(TestEnum::decode(&mut decoder).unwrap(), TestEnum::OptionB);
1275 assert_eq!(decoder.len(), 0);
1276 }
1277
1278 #[derive(AsnType, Debug, Decode, PartialEq)]
1279 #[rasn(automatic_tags)]
1280 #[rasn(delegate)]
1281 #[rasn(crate_root = "crate")]
1282 struct SeqOfType(SequenceOf<Integer>);
1283
1284 #[test]
1285 fn sequence_of() {
1286 let mut decoder = Decoder::new(
1287 r#"<SeqOfType>
1288 <INTEGER>-1</INTEGER>
1289 <INTEGER>-5</INTEGER>
1290 <INTEGER>0</INTEGER>
1291 <INTEGER>55</INTEGER>
1292 <INTEGER>212424214</INTEGER>
1293 </SeqOfType>"#
1294 .as_bytes(),
1295 )
1296 .unwrap();
1297 assert_eq!(
1298 SeqOfType::decode(&mut decoder).unwrap(),
1299 SeqOfType(vec![
1300 Integer::from(-1),
1301 Integer::from(-5),
1302 Integer::from(0),
1303 Integer::from(55),
1304 Integer::from(212424214)
1305 ])
1306 )
1307 }
1308
1309 #[derive(AsnType, Debug, Decode, PartialEq)]
1310 #[rasn(automatic_tags)]
1311 #[rasn(delegate)]
1312 #[rasn(crate_root = "crate")]
1313 struct NestedSeqOf(SequenceOf<SeqOfType>);
1314
1315 #[test]
1316 fn nested_sequence_of() {
1317 let mut decoder = Decoder::new(
1318 r#"<NestedSeqOf>
1319 <SeqOfType>
1320 <INTEGER>-1</INTEGER>
1321 <INTEGER>-5</INTEGER>
1322 <INTEGER>0</INTEGER>
1323 <INTEGER>55</INTEGER>
1324 <INTEGER>212424214</INTEGER>
1325 </SeqOfType>
1326 <SeqOfType>
1327 <INTEGER>1</INTEGER>
1328 <INTEGER>5</INTEGER>
1329 <INTEGER>0</INTEGER>
1330 <INTEGER>55</INTEGER>
1331 <INTEGER>212424214</INTEGER>
1332 </SeqOfType>
1333 </NestedSeqOf>"#
1334 .as_bytes(),
1335 )
1336 .unwrap();
1337 assert_eq!(
1338 NestedSeqOf::decode(&mut decoder).unwrap(),
1339 NestedSeqOf(vec![
1340 SeqOfType(vec![
1341 Integer::from(-1),
1342 Integer::from(-5),
1343 Integer::from(0),
1344 Integer::from(55),
1345 Integer::from(212424214)
1346 ]),
1347 SeqOfType(vec![
1348 Integer::from(1),
1349 Integer::from(5),
1350 Integer::from(0),
1351 Integer::from(55),
1352 Integer::from(212424214)
1353 ])
1354 ])
1355 )
1356 }
1357
1358 #[derive(AsnType, Debug, Decode, PartialEq)]
1359 #[rasn(automatic_tags)]
1360 #[rasn(delegate)]
1361 #[rasn(crate_root = "crate")]
1362 struct SetOfType(crate::types::SetOf<Integer>);
1363
1364 #[test]
1365 fn set_of() {
1366 let mut decoder = Decoder::new(
1367 r#"<SeqOfType>
1368 <INTEGER>-1</INTEGER>
1369 <INTEGER>-5</INTEGER>
1370 <INTEGER>0</INTEGER>
1371 <INTEGER>55</INTEGER>
1372 <INTEGER>212424214</INTEGER>
1373 </SeqOfType>"#
1374 .as_bytes(),
1375 )
1376 .unwrap();
1377 let expected = SetOf::from_vec(
1378 [
1379 Integer::from(-1),
1380 Integer::from(-5),
1381 Integer::from(0),
1382 Integer::from(55),
1383 Integer::from(212424214),
1384 ]
1385 .into_iter()
1386 .collect::<Vec<_>>(),
1387 );
1388
1389 assert_eq!(
1390 SetOfType::decode(&mut decoder).unwrap(),
1391 SetOfType(expected)
1392 )
1393 }
1394
1395 #[test]
1396 fn generalized_time() {
1397 let mut decoder =
1398 Decoder::new(r#"<TimeType>20001231235959.999+0000</TimeType>"#.as_bytes()).unwrap();
1399
1400 assert_eq!(
1401 crate::types::GeneralizedTime::decode(&mut decoder).unwrap(),
1402 GeneralizedTime::from(
1403 chrono::NaiveDate::from_ymd_opt(2000, 12, 31)
1404 .unwrap()
1405 .and_hms_milli_opt(23, 59, 59, 999)
1406 .unwrap()
1407 .and_utc()
1408 )
1409 )
1410 }
1411
1412 #[test]
1413 fn utc_time() {
1414 let mut decoder = Decoder::new(r#"<TimeType>991231235900Z</TimeType>"#.as_bytes()).unwrap();
1415
1416 assert_eq!(
1417 crate::types::UtcTime::decode(&mut decoder).unwrap(),
1418 UtcTime::from(
1419 chrono::NaiveDate::from_ymd_opt(1999, 12, 31)
1420 .unwrap()
1421 .and_hms_opt(23, 59, 0)
1422 .unwrap()
1423 .and_utc()
1424 )
1425 )
1426 }
1427
1428 #[derive(AsnType, Debug, Decode, PartialEq)]
1429 #[rasn(automatic_tags)]
1430 #[rasn(choice)]
1431 #[rasn(crate_root = "crate")]
1432 enum ChoiceType {
1433 #[rasn(identifier = "int")]
1434 Int(u8),
1435 #[rasn(identifier = "bool")]
1436 Bool(bool),
1437 }
1438
1439 #[test]
1440 fn choice() {
1441 let mut decoder = Decoder::new(
1442 r#"<ChoiceType>
1443 <int>5</int>
1444 </ChoiceType>"#
1445 .as_bytes(),
1446 )
1447 .unwrap();
1448
1449 assert_eq!(
1450 ChoiceType::decode(&mut decoder).unwrap(),
1451 ChoiceType::Int(5)
1452 )
1453 }
1454
1455 #[test]
1456 fn sequence_of_choices() {
1457 let mut decoder = Decoder::new(
1458 r#"
1459 <SEQUENCE_OF>
1460 <int>5</int>
1461 <bool><false/></bool>
1462 </SEQUENCE_OF>"#
1463 .as_bytes(),
1464 )
1465 .unwrap();
1466
1467 assert_eq!(
1468 SequenceOf::<ChoiceType>::decode(&mut decoder).unwrap(),
1469 vec![ChoiceType::Int(5), ChoiceType::Bool(false)]
1470 )
1471 }
1472
1473 #[derive(AsnType, Debug, Decode, PartialEq)]
1474 #[rasn(automatic_tags)]
1475 #[rasn(crate_root = "crate")]
1476 struct OptionalTest {
1477 wine: Option<bool>,
1478 grappa: BitString,
1479 }
1480
1481 #[test]
1482 fn optional_present() {
1483 let mut decoder = Decoder::new(
1484 "<TestTypeA><grappa>1010</grappa><wine><false/></wine></TestTypeA>".as_bytes(),
1485 )
1486 .unwrap();
1487 assert_eq!(
1488 OptionalTest::decode(&mut decoder).unwrap(),
1489 OptionalTest {
1490 wine: Some(false),
1491 grappa: bitvec::bitvec![u8, Msb0; 1, 0, 1, 0]
1492 }
1493 );
1494 }
1495
1496 #[test]
1497 fn optional_absent() {
1498 let mut decoder =
1499 Decoder::new("<TestTypeA><grappa>1010</grappa></TestTypeA>".as_bytes()).unwrap();
1500 assert_eq!(
1501 OptionalTest::decode(&mut decoder).unwrap(),
1502 OptionalTest {
1503 wine: None,
1504 grappa: bitvec::bitvec![u8, Msb0; 1, 0, 1, 0]
1505 }
1506 );
1507 }
1508
1509 #[derive(AsnType, Debug, Decode, PartialEq)]
1510 #[rasn(automatic_tags)]
1511 #[rasn(crate_root = "crate")]
1512 struct AnyTest {
1513 grappa: Any,
1514 }
1515
1516 #[test]
1517 fn decodes_any() {
1518 let mut decoder = Decoder::new(
1519 "<AnyTest><grappa><Actual><Hello>7</Hello><Text>Text</Text></Actual></grappa></AnyTest>".as_bytes(),
1520 )
1521 .unwrap();
1522 assert_eq!(
1523 "<Actual><Hello>7</Hello><Text>Text</Text></Actual>".as_bytes(),
1524 AnyTest::decode(&mut decoder).unwrap().grappa.as_bytes()
1525 )
1526 }
1527
1528 #[test]
1529 fn decodes_object_identifier() {
1530 let mut decoder =
1531 Decoder::new("<OBJECT_IDENTIFIER>1.0.8571.2.1</OBJECT_IDENTIFIER>".as_bytes()).unwrap();
1532 assert_eq!(
1533 ObjectIdentifier::decode(&mut decoder).unwrap(),
1534 ObjectIdentifier::new(&[1, 0, 8571, 2, 1]).unwrap()
1535 )
1536 }
1537
1538 #[test]
1539 fn mapem() {
1540 use crate::Encode;
1541 #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq)]
1542 #[rasn(delegate, crate_root = "crate", size("1..=63"))]
1543 pub struct DescriptiveName(pub Ia5String);
1544 #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq)]
1545 #[rasn(automatic_tags, crate_root = "crate")]
1546 #[non_exhaustive]
1547 pub struct IntersectionGeometry {
1548 pub name: Option<DescriptiveName>,
1549 }
1550 impl IntersectionGeometry {
1551 pub fn new(name: Option<DescriptiveName>) -> Self {
1552 Self { name }
1553 }
1554 }
1555 #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq)]
1556 #[rasn(delegate, crate_root = "crate", size("1..=32"))]
1557 pub struct IntersectionGeometryList(pub SequenceOf<IntersectionGeometry>);
1558 #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq)]
1559 #[rasn(automatic_tags, crate_root = "crate")]
1560 #[allow(clippy::upper_case_acronyms)]
1561 pub struct MAPEM {
1562 pub map: MapData,
1563 }
1564 #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq)]
1565 #[rasn(automatic_tags, crate_root = "crate")]
1566 #[non_exhaustive]
1567 pub struct MapData {
1568 pub intersections: Option<IntersectionGeometryList>,
1569 }
1570 impl MapData {
1571 pub fn new(intersections: Option<IntersectionGeometryList>) -> Self {
1572 Self { intersections }
1573 }
1574 }
1575
1576 let encoded = r#"<?xml version="1.0"?><MAPEM><map><intersections><IntersectionGeometry><name>MAP_ITS_00\19\19.3</name></IntersectionGeometry></intersections></map></MAPEM>"#;
1577 assert_eq!(
1578 MAPEM {
1579 map: MapData::new(Some(IntersectionGeometryList(vec![
1580 IntersectionGeometry::new(Some(DescriptiveName(
1581 Ia5String::from_iso646_bytes(r#"MAP_ITS_00\19\19.3"#.as_bytes()).unwrap()
1582 )))
1583 ])))
1584 },
1585 crate::xer::decode::<MAPEM>(encoded.as_bytes()).unwrap()
1586 );
1587 }
1588
1589 #[derive(AsnType, Debug, Clone, Decode, PartialEq)]
1590 #[rasn(automatic_tags, crate_root = "crate")]
1591 #[rasn(delegate, size("1..=8", extensible))]
1592 pub struct ZoneIds(pub SequenceOf<Zid>);
1593
1594 #[derive(AsnType, Debug, Clone, Decode, PartialEq, PartialOrd, Eq, Ord, Hash)]
1595 #[rasn(automatic_tags, crate_root = "crate")]
1596 #[rasn(delegate, value("1..=32", extensible))]
1597 pub struct Zid(pub Integer);
1598
1599 #[derive(AsnType, Debug, Clone, Decode, PartialEq)]
1600 #[rasn(automatic_tags, crate_root = "crate")]
1601 #[non_exhaustive]
1602 pub struct GicPart {
1603 #[rasn(identifier = "detectionZoneIds")]
1604 pub detection_zone_ids: Option<ZoneIds>,
1605 #[rasn(identifier = "relevanceZoneIds")]
1606 pub relevance_zone_ids: Option<ZoneIds>,
1607 pub direction: Option<u32>,
1608 }
1609
1610 #[test]
1611 fn simple_type_sequence_of() {
1612 let mut encoded = r#"<ZoneIds>2 5</ZoneIds>"#;
1613 assert_eq!(
1614 ZoneIds(vec![Zid(2.into()), Zid(5.into())]),
1615 crate::xer::decode::<ZoneIds>(encoded.as_bytes()).unwrap()
1616 );
1617 encoded = r#"<ZoneIds>2</ZoneIds>"#;
1618 assert_eq!(
1619 ZoneIds(vec![Zid(2.into())]),
1620 crate::xer::decode::<ZoneIds>(encoded.as_bytes()).unwrap()
1621 );
1622 encoded = r#"<GicPart>
1623 <detectionZoneIds>2</detectionZoneIds>
1624 <relevanceZoneIds>1</relevanceZoneIds>
1625 <direction>0</direction>
1626 </GicPart>"#;
1627 assert_eq!(
1628 GicPart {
1629 detection_zone_ids: Some(ZoneIds(alloc::vec![Zid(2.into())])),
1630 relevance_zone_ids: Some(ZoneIds(alloc::vec![Zid(1.into())])),
1631 direction: Some(0),
1632 },
1633 crate::xer::decode::<GicPart>(encoded.as_bytes()).unwrap()
1634 );
1635 }
1636
1637 #[test]
1638 fn decodes_with_and_without_default() {
1639 #[derive(AsnType, Debug, Decode, PartialEq)]
1640 #[rasn(automatic_tags)]
1641 #[rasn(crate_root = "crate")]
1642 struct DefaultSequence {
1643 #[rasn(identifier = "bool-df", default = "bool_default")]
1644 bool_with_default: bool,
1645 recursion: Vec<DefaultSequence>,
1646 }
1647
1648 fn bool_default() -> bool {
1649 bool::default()
1650 }
1651
1652 assert_eq!(
1653 crate::xer::decode::<DefaultSequence>(
1654 r#"
1655 <DefaultSequence>
1656 <recursion>
1657 <DefaultSequence>
1658 <bool-df>
1659 <false />
1660 </bool-df>
1661 <recursion />
1662 </DefaultSequence>
1663 <DefaultSequence>
1664 <recursion />
1665 </DefaultSequence>
1666 </recursion>
1667 </DefaultSequence>
1668 "#
1669 .as_bytes()
1670 )
1671 .unwrap(),
1672 DefaultSequence {
1673 bool_with_default: false,
1674 recursion: vec![
1675 DefaultSequence {
1676 bool_with_default: false,
1677 recursion: vec![]
1678 },
1679 DefaultSequence {
1680 bool_with_default: false,
1681 recursion: vec![]
1682 }
1683 ]
1684 }
1685 )
1686 }
1687
1688 #[test]
1689 fn decodes_extended_boolean_notation() {
1690 assert_eq!(
1691 crate::xer::decode::<SequenceOf<bool>>(
1692 r#"
1693 <SEQUENCE_OF>
1694 <true />
1695 <false />
1696 <BOOLEAN>0</BOOLEAN>
1697 <BOOLEAN>1</BOOLEAN>
1698 <BOOLEAN>true</BOOLEAN>
1699 <BOOLEAN>false</BOOLEAN>
1700 </SEQUENCE_OF>
1701 "#
1702 .as_bytes()
1703 )
1704 .unwrap(),
1705 vec![true, false, false, true, true, false]
1706 )
1707 }
1708
1709 #[test]
1710 fn decodes_nested_extended_boolean_notation() {
1711 #[derive(AsnType, Debug, Decode, PartialEq)]
1712 #[rasn(automatic_tags)]
1713 #[rasn(crate_root = "crate")]
1714 struct Boolean {
1715 val: bool,
1716 }
1717
1718 assert_eq!(
1719 crate::xer::decode::<SequenceOf<Boolean>>(
1720 r#"
1721 <SEQUENCE_OF>
1722 <Boolean><val><true /></val></Boolean>
1723 <Boolean><val><false /></val></Boolean>
1724 <Boolean><val>0</val></Boolean>
1725 <Boolean><val>1</val></Boolean>
1726 <Boolean><val>true</val></Boolean>
1727 <Boolean><val>false</val></Boolean>
1728 </SEQUENCE_OF>
1729 "#
1730 .as_bytes()
1731 )
1732 .unwrap(),
1733 vec![
1734 Boolean { val: true },
1735 Boolean { val: false },
1736 Boolean { val: false },
1737 Boolean { val: true },
1738 Boolean { val: true },
1739 Boolean { val: false }
1740 ]
1741 )
1742 }
1743}